blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
3cccd7a771d255ff83f565f4a9885b8b2b564884
21,045,339,766,055
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/27/27_fab509bb4215807c94dcfac542a68c1b51bad4eb/IChannelManager/27_fab509bb4215807c94dcfac542a68c1b51bad4eb_IChannelManager_t.java
e0efd6aff150627bbf19c7b511ef7dec99229374
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
/******************************************************************************* * Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.tcf.core.interfaces; import java.util.Map; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.tcf.osgi.services.IValueAddService; import org.eclipse.tcf.protocol.IChannel; import org.eclipse.tcf.protocol.IPeer; /** * TCF channel manager public API declaration. */ public interface IChannelManager extends IAdaptable { /** * If set to <code>true</code>, a new and not reference counted channel is opened. * The returned channel must be closed by the caller himself. The channel manager * is not keeping track of non reference counted channels. * <p> * If not present in the flags map passed in to open channel, the default value is * <code>false</code>. */ public static final String FLAG_FORCE_NEW = "forceNew"; //$NON-NLS-1$ /** * If set to <code>true</code>, a new and not reference counted channel is is opened, * and no value add is launched and associated with the channel. This option should * be used with extreme caution. * <p> * The returned channel must be closed by the caller himself. The channel manager * is not keeping track of non reference counted channels. * <p> * If not present in the flags map passed in to open channel, the default value is * <code>false</code>. */ public static final String FLAG_NO_VALUE_ADD = "noValueAdd"; //$NON-NLS-1$ /** * Client call back interface for openChannel(...). */ interface DoneOpenChannel { /** * Called when the channel fully opened or failed to open. * <p> * <b>Note:</b> If error is of type {@link OperationCanceledException}, than it signals that * the channel got closed normally while still in state {@link IChannel#STATE_OPENING}. Clients * should handle the case explicitly if necessary. * * @param error The error description if operation failed, <code>null</code> if succeeded. * @param channel The channel object or <code>null</code>. */ void doneOpenChannel(Throwable error, IChannel channel); } /** * Opens a new channel to communicate with the given peer. * <p> * Reference counted channels are cached by the channel manager and must be closed via {@link #closeChannel(IChannel)}. * <p> * The method can be called from any thread context. * * @param peer The peer. Must not be <code>null</code>. * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void openChannel(IPeer peer, Map<String, Boolean> flags, DoneOpenChannel done); /** * Opens a new channel to communicate with the peer described by the given peer attributes. * <p> * Reference counted channels are cached by the channel manager and must be closed via {@link #closeChannel(IChannel)}. * <p> * The method can be called from any thread context. * * @param peerAttributes The peer attributes. Must not be <code>null</code>. * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void openChannel(Map<String, String> peerAttributes, Map<String, Boolean> flags, DoneOpenChannel done); /** * Returns the shared channel instance for the given peer. Channels retrieved using this * method cannot be closed by the caller. * <p> * Callers of this method are expected to test for the current channel state themselves. * <p> * The method can be called from any thread context. * * @param peer The peer. Must not be <code>null</code>. * @return The channel instance or <code>null</code>. */ public IChannel getChannel(IPeer peer); /** * Returns the redirection path for the given peer. If needed, the required * value-add's are launched. * * @param peer The peer. Must not be <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void getRedirectionPath(IPeer peer, IValueAddService.DoneGetRedirectionPath done); /** * Closes the given channel. * <p> * If the given channel is a reference counted channel, the channel will be closed if the reference counter * reaches 0. For non reference counted channels, the channel is closed immediately. * <p> * The method can be called from any thread context. * * @param channel The channel. Must not be <code>null</code>. */ public void closeChannel(IChannel channel); /** * Close all open channel, no matter of the current reference count. * <p> * The method can be called from any thread context. */ public void closeAll(); }
UTF-8
Java
5,346
java
27_fab509bb4215807c94dcfac542a68c1b51bad4eb_IChannelManager_t.java
Java
[]
null
[]
/******************************************************************************* * Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.tcf.core.interfaces; import java.util.Map; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.tcf.osgi.services.IValueAddService; import org.eclipse.tcf.protocol.IChannel; import org.eclipse.tcf.protocol.IPeer; /** * TCF channel manager public API declaration. */ public interface IChannelManager extends IAdaptable { /** * If set to <code>true</code>, a new and not reference counted channel is opened. * The returned channel must be closed by the caller himself. The channel manager * is not keeping track of non reference counted channels. * <p> * If not present in the flags map passed in to open channel, the default value is * <code>false</code>. */ public static final String FLAG_FORCE_NEW = "forceNew"; //$NON-NLS-1$ /** * If set to <code>true</code>, a new and not reference counted channel is is opened, * and no value add is launched and associated with the channel. This option should * be used with extreme caution. * <p> * The returned channel must be closed by the caller himself. The channel manager * is not keeping track of non reference counted channels. * <p> * If not present in the flags map passed in to open channel, the default value is * <code>false</code>. */ public static final String FLAG_NO_VALUE_ADD = "noValueAdd"; //$NON-NLS-1$ /** * Client call back interface for openChannel(...). */ interface DoneOpenChannel { /** * Called when the channel fully opened or failed to open. * <p> * <b>Note:</b> If error is of type {@link OperationCanceledException}, than it signals that * the channel got closed normally while still in state {@link IChannel#STATE_OPENING}. Clients * should handle the case explicitly if necessary. * * @param error The error description if operation failed, <code>null</code> if succeeded. * @param channel The channel object or <code>null</code>. */ void doneOpenChannel(Throwable error, IChannel channel); } /** * Opens a new channel to communicate with the given peer. * <p> * Reference counted channels are cached by the channel manager and must be closed via {@link #closeChannel(IChannel)}. * <p> * The method can be called from any thread context. * * @param peer The peer. Must not be <code>null</code>. * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void openChannel(IPeer peer, Map<String, Boolean> flags, DoneOpenChannel done); /** * Opens a new channel to communicate with the peer described by the given peer attributes. * <p> * Reference counted channels are cached by the channel manager and must be closed via {@link #closeChannel(IChannel)}. * <p> * The method can be called from any thread context. * * @param peerAttributes The peer attributes. Must not be <code>null</code>. * @param flags Map containing the flags to parameterize the channel opening, or <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void openChannel(Map<String, String> peerAttributes, Map<String, Boolean> flags, DoneOpenChannel done); /** * Returns the shared channel instance for the given peer. Channels retrieved using this * method cannot be closed by the caller. * <p> * Callers of this method are expected to test for the current channel state themselves. * <p> * The method can be called from any thread context. * * @param peer The peer. Must not be <code>null</code>. * @return The channel instance or <code>null</code>. */ public IChannel getChannel(IPeer peer); /** * Returns the redirection path for the given peer. If needed, the required * value-add's are launched. * * @param peer The peer. Must not be <code>null</code>. * @param done The client callback. Must not be <code>null</code>. */ public void getRedirectionPath(IPeer peer, IValueAddService.DoneGetRedirectionPath done); /** * Closes the given channel. * <p> * If the given channel is a reference counted channel, the channel will be closed if the reference counter * reaches 0. For non reference counted channels, the channel is closed immediately. * <p> * The method can be called from any thread context. * * @param channel The channel. Must not be <code>null</code>. */ public void closeChannel(IChannel channel); /** * Close all open channel, no matter of the current reference count. * <p> * The method can be called from any thread context. */ public void closeAll(); }
5,346
0.681444
0.678638
131
39.801525
35.445564
121
false
false
0
0
0
0
0
0
1.145038
false
false
4
69d2e0a9158f623d7ecf5fe112f4fedc8f91b56a
9,921,374,488,260
f35d9ccef8641cc7b6839761328354534789888e
/app/src/main/java/com/congtyhai/dms/order/ShowOrderActivity.java
847435ab9a8ee5443c3b651bb9c0f786bf57e80a
[ "Apache-2.0" ]
permissive
nnamlh/haidms
https://github.com/nnamlh/haidms
67d15521aba35c3f7395b7a3f2eb17079410acf2
c7bdeae2818dc3c9da5f4acbe69efa055ad14668
refs/heads/master
2021-09-18T14:15:12.217000
2018-07-15T10:26:22
2018-07-15T10:26:22
100,441,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.congtyhai.dms.order; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.congtyhai.adapter.ProductOrderAdapter; import com.congtyhai.dms.BaseActivity; import com.congtyhai.dms.R; import com.congtyhai.model.api.ProductOrder; import com.congtyhai.util.HAIRes; import com.congtyhai.view.DividerItemDecoration; import butterknife.BindView; import butterknife.ButterKnife; public class ShowOrderActivity extends BaseActivity { @BindView(R.id.recycler_view) RecyclerView recyclerView; ProductOrderAdapter adapter; @BindView(R.id.txtmoney) TextView txtMoney; String agencyCode; // int indexSelect = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_order); createToolbar(); ButterKnife.bind(this); agencyCode = HAIRes.getInstance().c2Select.getCode(); getSupportActionBar().setTitle("Đơn hàng của " + HAIRes.getInstance().c2Select.getStore()); adapter = new ProductOrderAdapter(this); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); resetMoneyAll(); } public void changeQuantity(int quantity, final int boxNumber, final int position) { int countCan = quantity / boxNumber; int countBox = quantity - countCan*boxNumber; View viewDialog = ShowOrderActivity.this.getLayoutInflater().inflate(R.layout.dialog_change_quantity_order, null); final EditText eCan = (EditText) viewDialog.findViewById(R.id.ecan); eCan.setText("" + countCan); final EditText eBox = (EditText) viewDialog.findViewById(R.id.ebox); eBox.setText("" + countBox); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Thao tác"); builder.setMessage("Thay đổi số lượng mua"); builder.setIcon(R.mipmap.ic_logo); builder.setView(viewDialog); builder.setNegativeButton("Thôi", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.setPositiveButton("Nhập", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (!TextUtils.isEmpty(eCan.getText().toString()) && !TextUtils.isEmpty(eBox.getText().toString())) { try{ int quantityCan = Integer.parseInt(eCan.getText().toString()); int quantityBox = Integer.parseInt(eBox.getText().toString()); int quantity = quantityBox + boxNumber*quantityCan; HAIRes.getInstance().getProductOrder().get(position).setQuantity(quantity); notifyAdapter(); resetMoneyAll(); }catch (Exception e) { } }else { commons.makeToast(ShowOrderActivity.this, "Nhập số lượng").show(); } } }); builder.show(); } public void notifyAdapter() { adapter.notifyDataSetChanged(); } public void resetMoneyAll() { double price = 0; for(ProductOrder order: HAIRes.getInstance().getProductOrder()) { price+= order.getPrice() * order.getQuantity(); } txtMoney.setText(HAIRes.getInstance().formatMoneyToText(price)); } @Override public void onResume() { super.onResume(); notifyAdapter(); resetMoneyAll(); } public void orderClick(View view) { if (HAIRes.getInstance().getProductOrder() == null || HAIRes.getInstance().getProductOrder().size() == 0) { commons.makeToast(ShowOrderActivity.this, "Chọn mặt hàng cần đặt").show(); } else { commons.showAlertCancel( ShowOrderActivity.this,"Cảnh báo", "Kiểm tra các mặt hàng và số lượng trước khi đặt hàng", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { commons.startActivity(ShowOrderActivity.this, CompleteOrderActivity.class); } }); } } }
UTF-8
Java
5,090
java
ShowOrderActivity.java
Java
[]
null
[]
package com.congtyhai.dms.order; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.congtyhai.adapter.ProductOrderAdapter; import com.congtyhai.dms.BaseActivity; import com.congtyhai.dms.R; import com.congtyhai.model.api.ProductOrder; import com.congtyhai.util.HAIRes; import com.congtyhai.view.DividerItemDecoration; import butterknife.BindView; import butterknife.ButterKnife; public class ShowOrderActivity extends BaseActivity { @BindView(R.id.recycler_view) RecyclerView recyclerView; ProductOrderAdapter adapter; @BindView(R.id.txtmoney) TextView txtMoney; String agencyCode; // int indexSelect = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_order); createToolbar(); ButterKnife.bind(this); agencyCode = HAIRes.getInstance().c2Select.getCode(); getSupportActionBar().setTitle("Đơn hàng của " + HAIRes.getInstance().c2Select.getStore()); adapter = new ProductOrderAdapter(this); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); resetMoneyAll(); } public void changeQuantity(int quantity, final int boxNumber, final int position) { int countCan = quantity / boxNumber; int countBox = quantity - countCan*boxNumber; View viewDialog = ShowOrderActivity.this.getLayoutInflater().inflate(R.layout.dialog_change_quantity_order, null); final EditText eCan = (EditText) viewDialog.findViewById(R.id.ecan); eCan.setText("" + countCan); final EditText eBox = (EditText) viewDialog.findViewById(R.id.ebox); eBox.setText("" + countBox); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Thao tác"); builder.setMessage("Thay đổi số lượng mua"); builder.setIcon(R.mipmap.ic_logo); builder.setView(viewDialog); builder.setNegativeButton("Thôi", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.setPositiveButton("Nhập", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (!TextUtils.isEmpty(eCan.getText().toString()) && !TextUtils.isEmpty(eBox.getText().toString())) { try{ int quantityCan = Integer.parseInt(eCan.getText().toString()); int quantityBox = Integer.parseInt(eBox.getText().toString()); int quantity = quantityBox + boxNumber*quantityCan; HAIRes.getInstance().getProductOrder().get(position).setQuantity(quantity); notifyAdapter(); resetMoneyAll(); }catch (Exception e) { } }else { commons.makeToast(ShowOrderActivity.this, "Nhập số lượng").show(); } } }); builder.show(); } public void notifyAdapter() { adapter.notifyDataSetChanged(); } public void resetMoneyAll() { double price = 0; for(ProductOrder order: HAIRes.getInstance().getProductOrder()) { price+= order.getPrice() * order.getQuantity(); } txtMoney.setText(HAIRes.getInstance().formatMoneyToText(price)); } @Override public void onResume() { super.onResume(); notifyAdapter(); resetMoneyAll(); } public void orderClick(View view) { if (HAIRes.getInstance().getProductOrder() == null || HAIRes.getInstance().getProductOrder().size() == 0) { commons.makeToast(ShowOrderActivity.this, "Chọn mặt hàng cần đặt").show(); } else { commons.showAlertCancel( ShowOrderActivity.this,"Cảnh báo", "Kiểm tra các mặt hàng và số lượng trước khi đặt hàng", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { commons.startActivity(ShowOrderActivity.this, CompleteOrderActivity.class); } }); } } }
5,090
0.653159
0.651371
142
34.450703
32.32811
166
false
false
0
0
0
0
0
0
0.612676
false
false
4
3fcfffc9bdcb910bdb43559748a9531a7c2ed523
532,575,994,361
744fb0e5226a0e85b9493f01f1c17386d1633ccd
/Java_Thread/src/com/bjsxt/new1/Te2.java
8fd16fab7c36561bfec29e7e8aa824439458e438
[]
no_license
Strwenhao1/Learn2
https://github.com/Strwenhao1/Learn2
13fc19e95bee2de1a515a581bb3890d2ad27e65c
7e8fbb065609c62653c24275938313727575a8df
refs/heads/master
2020-07-24T17:00:17.900000
2019-10-19T08:43:37
2019-10-19T08:43:37
207,989,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bjsxt.new1; import java.util.ArrayList; import java.util.List; public class Te2 { public static void main(String[] args) throws InterruptedException { final MyContainer c = new MyContainer(); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { for (int n = 0; n < 10; n++) { c.add(new Object()); } } }, "add-" + i).start(); } Thread.sleep(10); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { for (int n = 0; n < 10; n++) { System.out.println(Thread.currentThread().getName() + "get-" + c.get(0)); } } }, "get-" + i).start(); } } } class MyContainer { List list = new ArrayList(); final Object writeLock = new Object(); boolean isWrite = false; boolean isRead = false; public void add(Object obj) { while (isRead) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (writeLock) { try { while (isWrite) { try { writeLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } isWrite = true; list.add(obj); System.out.println(Thread.currentThread().getName() + "add-" + obj); writeLock.notifyAll(); } finally { isWrite = false; } } } public Object get(int index) { if (index >= list.size()) { throw new IndexOutOfBoundsException(); } while (isWrite) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } try { isRead = true; Object value = list.get(index); return value; } finally { isRead = false; } } }
UTF-8
Java
2,395
java
Te2.java
Java
[]
null
[]
package com.bjsxt.new1; import java.util.ArrayList; import java.util.List; public class Te2 { public static void main(String[] args) throws InterruptedException { final MyContainer c = new MyContainer(); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { for (int n = 0; n < 10; n++) { c.add(new Object()); } } }, "add-" + i).start(); } Thread.sleep(10); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { for (int n = 0; n < 10; n++) { System.out.println(Thread.currentThread().getName() + "get-" + c.get(0)); } } }, "get-" + i).start(); } } } class MyContainer { List list = new ArrayList(); final Object writeLock = new Object(); boolean isWrite = false; boolean isRead = false; public void add(Object obj) { while (isRead) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (writeLock) { try { while (isWrite) { try { writeLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } isWrite = true; list.add(obj); System.out.println(Thread.currentThread().getName() + "add-" + obj); writeLock.notifyAll(); } finally { isWrite = false; } } } public Object get(int index) { if (index >= list.size()) { throw new IndexOutOfBoundsException(); } while (isWrite) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } try { isRead = true; Object value = list.get(index); return value; } finally { isRead = false; } } }
2,395
0.410021
0.402088
92
25.032608
18.525219
97
false
false
0
0
0
0
0
0
0.423913
false
false
4
2c4a5777559fb9006e5832ef8a60ee1d036ad894
32,238,024,546,930
65e0ff961c162a0a6a03c293c9417800463c7e5e
/src/BalancedBinaryTree.java
55914ddc532e383198bdaf22771800b125bb72a0
[]
no_license
rktechie/LC
https://github.com/rktechie/LC
15cf71e729b17d7d06392d696c96456ec10e5e1b
ad87402810ec03bf97ff91174ff387d5f425ad31
refs/heads/master
2021-01-11T18:10:15.504000
2019-05-30T18:17:37
2019-05-30T18:17:37
79,506,864
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Problem 110: Balanced Binary Tree * Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. */ public class BalancedBinaryTree { public boolean isBalanced(TreeNode root) { if (root == null) return true; int diff = isBalancedHelper(root); if (diff == -1) return false; return true; } /* * Approach is from cracking the coding interview. */ public int isBalancedHelper(TreeNode root) { if (root == null) return 0; int left = isBalancedHelper(root.left); if (left == -1) return -1; int right = isBalancedHelper(root.right); if (right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
UTF-8
Java
1,146
java
BalancedBinaryTree.java
Java
[]
null
[]
/* * Problem 110: Balanced Binary Tree * Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. */ public class BalancedBinaryTree { public boolean isBalanced(TreeNode root) { if (root == null) return true; int diff = isBalancedHelper(root); if (diff == -1) return false; return true; } /* * Approach is from cracking the coding interview. */ public int isBalancedHelper(TreeNode root) { if (root == null) return 0; int left = isBalancedHelper(root.left); if (left == -1) return -1; int right = isBalancedHelper(root.right); if (right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
1,146
0.552356
0.541012
49
22.387754
25.6243
158
false
false
0
0
0
0
0
0
0.367347
false
false
4
f7fe161f2fd48a54006d65ec8dae19497a557a6c
27,470,610,867,180
d8c841894bdb404e188d468861d8000a571b4ab1
/Lab5_Anagrammi/src/it/polito/tdp/anagrammi/DAO/ParolaDAO.java
20757fa02c6ce088ef6f07403101715322b66a57
[]
no_license
dalessandromark/Lab05
https://github.com/dalessandromark/Lab05
1674ab50d285f5116b049a1e61c22364cba72018
9f5dc8546873517b207390121a25a5ae4e328b77
refs/heads/master
2020-05-04T16:16:26.239000
2019-04-09T07:54:19
2019-04-09T07:54:19
179,273,769
0
0
null
true
2019-04-03T11:14:42
2019-04-03T11:14:41
2019-04-03T01:39:09
2019-04-03T01:39:08
5,392
0
0
0
null
false
null
package it.polito.tdp.anagrammi.DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import it.polito.tdp.anagrammi.model.Anagramma; import it.polito.tdp.anagrammi.model.Parola; public class ParolaDAO { public ArrayList<Parola> getDictionary(){ final String sql = "SELECT * FROM parola"; ArrayList<Parola> dictionary = new ArrayList<Parola>(); try { Connection conn = ConnectDB.getConnection(); PreparedStatement st = conn.prepareStatement(sql); ResultSet rs = st.executeQuery() ; while(rs.next()) { int id = rs.getInt("id"); String nome = rs.getString("nome"); Parola nuova = new Parola(id, nome); dictionary.add(nuova); } return dictionary; } catch (SQLException e) { throw new RuntimeException("Errore Db"); } } public Boolean isCorrect(Anagramma a) { final String sql = "SELECT * FROM parola WHERE nome=?"; try { Connection conn = ConnectDB.getConnection(); PreparedStatement st = conn.prepareStatement(sql); boolean result = false; String anagr = a.getString(); st.setString(1, anagr); ResultSet rs = st.executeQuery() ; if(rs.next()) result = true; return result; } catch (SQLException e) { throw new RuntimeException("Errore Db"); } } }
UTF-8
Java
1,517
java
ParolaDAO.java
Java
[]
null
[]
package it.polito.tdp.anagrammi.DAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import it.polito.tdp.anagrammi.model.Anagramma; import it.polito.tdp.anagrammi.model.Parola; public class ParolaDAO { public ArrayList<Parola> getDictionary(){ final String sql = "SELECT * FROM parola"; ArrayList<Parola> dictionary = new ArrayList<Parola>(); try { Connection conn = ConnectDB.getConnection(); PreparedStatement st = conn.prepareStatement(sql); ResultSet rs = st.executeQuery() ; while(rs.next()) { int id = rs.getInt("id"); String nome = rs.getString("nome"); Parola nuova = new Parola(id, nome); dictionary.add(nuova); } return dictionary; } catch (SQLException e) { throw new RuntimeException("Errore Db"); } } public Boolean isCorrect(Anagramma a) { final String sql = "SELECT * FROM parola WHERE nome=?"; try { Connection conn = ConnectDB.getConnection(); PreparedStatement st = conn.prepareStatement(sql); boolean result = false; String anagr = a.getString(); st.setString(1, anagr); ResultSet rs = st.executeQuery() ; if(rs.next()) result = true; return result; } catch (SQLException e) { throw new RuntimeException("Errore Db"); } } }
1,517
0.629532
0.628873
74
18.5
17.988922
57
false
false
0
0
0
0
0
0
2.445946
false
false
4
cdafdb4a6bf1b17ecbcaba42a4bdd2119a527add
27,470,610,866,389
0b353f896f41197cd690eefc288b37c9e039c0c0
/src/main/java/com/pablo/system/domain/CtypeVo.java
eb545256b3814272e1b81414135c22b06a518149
[]
no_license
PabloSongyang/UrbanEnergyAllocation
https://github.com/PabloSongyang/UrbanEnergyAllocation
854773571903c8f2a5c4698d4a06a0cc17267fda
52a3f6bd9c3ffe9a2b73c05beb630ba1ff7d9c94
refs/heads/master
2022-12-21T04:04:45.664000
2020-04-08T03:19:34
2020-04-08T03:19:34
252,333,391
0
0
null
false
2022-12-16T15:06:44
2020-04-02T02:13:19
2020-04-08T03:20:01
2022-12-16T15:06:39
3,150
0
0
15
HTML
false
false
package com.pablo.system.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; /** * @author Pablo.风暴洋 * @time 2020/3/26 14:04 * @package com.pablo.system.domain * @characterization 设备子类实体类 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class CtypeVo implements Serializable { private Integer ctid; private String ctname; }
UTF-8
Java
472
java
CtypeVo.java
Java
[ { "context": "ing;\n\nimport java.io.Serializable;\n\n/**\n * @author Pablo.风暴洋\n * @time 2020/3/26 14:04\n * @package com.pablo.sy", "end": 200, "score": 0.9275336861610413, "start": 191, "tag": "NAME", "value": "Pablo.风暴洋" } ]
null
[]
package com.pablo.system.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; /** * @author Pablo.风暴洋 * @time 2020/3/26 14:04 * @package com.pablo.system.domain * @characterization 设备子类实体类 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class CtypeVo implements Serializable { private Integer ctid; private String ctname; }
472
0.772124
0.747788
23
18.652174
13.222539
46
false
false
0
0
0
0
0
0
0.347826
false
false
4
5727a98743a80e812df07af77e45d2660c8baaa2
23,278,722,785,177
6e35545238bba0cea762dddec03c8dd7d0b75ac5
/InnoMES/src/main/java/com/innomes/main/repository/impl/MST140RepositoryImpl.java
c29d17a625532c570d0442e73a3b945660cbd742
[]
no_license
kim-doan/InnoMES_backend
https://github.com/kim-doan/InnoMES_backend
df955ade58aff9afa314f6df9c4f2c73f812c88f
883d298942fae78cc9846412e57943bade8f3ce2
refs/heads/master
2023-06-04T13:29:05.625000
2021-06-22T12:49:19
2021-06-22T12:49:19
326,349,187
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.innomes.main.repository.impl; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; import com.innomes.main.master.model.MST140; import com.innomes.main.master.model.QMST140; import com.innomes.main.master.model.QMST141; import com.innomes.main.master.model.QMST142; import com.innomes.main.master.param.MasterUserParam; import com.innomes.main.repository.custom.MST140RepositoryCustom; import com.innomes.main.system.model.QSYS800; import com.innomes.main.system.model.SYS810; import com.microsoft.sqlserver.jdbc.StringUtils; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.QueryResults; import com.querydsl.jpa.impl.JPAQueryFactory; public class MST140RepositoryImpl extends QuerydslRepositorySupport implements MST140RepositoryCustom { public MST140RepositoryImpl() { super(MST140.class); } @Override public Page<MST140> findAllLike(MasterUserParam masterUserParam, Pageable pageable){ JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QSYS800 sys800 = QSYS800.sYS800; BooleanBuilder builder = new BooleanBuilder(); if(!StringUtils.isEmpty(masterUserParam.getUserNo())) { builder.and(mst140.userNo.like(masterUserParam.getUserNo())); } if(!StringUtils.isEmpty(masterUserParam.getUserId())) { builder.and(sys800.userId.like("%" + masterUserParam.getUserId() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getUserType())) { builder.and(mst140.userType.like("%" + masterUserParam.getUserType() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getUserName())) { builder.and(mst140.userName.like("%" + masterUserParam.getUserName() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getDepartmentCode())) { builder.and(mst140.departmentCode.like("%" + masterUserParam.getDepartmentCode() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getGradeCode())) { builder.and(mst140.gradeCode.like("%" + masterUserParam.getGradeCode() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getTeamCode())) { builder.and(mst140.teamCode.like("%" + masterUserParam.getTeamCode() + "%")); } // builder.and(qmst140.used.eq(0)); QueryResults<MST140> result = query.from(mst140) .select(mst140) .where(builder) .innerJoin(mst140.sys800, sys800) .fetchJoin() .offset(pageable.getOffset()) .limit(pageable.getPageSize()) .orderBy(mst140.createTime.desc(), mst140.userNo.asc()) .fetchResults(); return new PageImpl<>(result.getResults(), pageable, result.getTotal()); } @Override public List<MST140> findAll() { JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QMST141 mst141 = QMST141.mST141; QSYS800 sys800 = QSYS800.sYS800; List<MST140> result = query.from(mst140) .select(mst140) .innerJoin(mst140.sys800, sys800) .fetchJoin() .innerJoin(mst140.sys800.roles) .fetchJoin() .leftJoin(mst140.mst141, mst141) .fetchJoin() .fetch().stream().distinct().collect(Collectors.toList()); return result; } @Override public Optional<MST140> findByIdCustom(String userNo) { JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QMST141 mst141 = QMST141.mST141; QSYS800 sys800 = QSYS800.sYS800; BooleanBuilder builder = new BooleanBuilder(); builder.and(mst140.userNo.eq(userNo)); Optional<MST140> result = Optional.ofNullable(query.from(mst140) .select(mst140) .where(builder) .leftJoin(mst140.sys800, sys800) .fetchJoin() .leftJoin(sys800.roles) .fetchJoin() .leftJoin(mst140.mst141, mst141) .fetchJoin() .fetchOne()); return result; } }
UTF-8
Java
4,014
java
MST140RepositoryImpl.java
Java
[]
null
[]
package com.innomes.main.repository.impl; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.support.QuerydslRepositorySupport; import com.innomes.main.master.model.MST140; import com.innomes.main.master.model.QMST140; import com.innomes.main.master.model.QMST141; import com.innomes.main.master.model.QMST142; import com.innomes.main.master.param.MasterUserParam; import com.innomes.main.repository.custom.MST140RepositoryCustom; import com.innomes.main.system.model.QSYS800; import com.innomes.main.system.model.SYS810; import com.microsoft.sqlserver.jdbc.StringUtils; import com.querydsl.core.BooleanBuilder; import com.querydsl.core.QueryResults; import com.querydsl.jpa.impl.JPAQueryFactory; public class MST140RepositoryImpl extends QuerydslRepositorySupport implements MST140RepositoryCustom { public MST140RepositoryImpl() { super(MST140.class); } @Override public Page<MST140> findAllLike(MasterUserParam masterUserParam, Pageable pageable){ JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QSYS800 sys800 = QSYS800.sYS800; BooleanBuilder builder = new BooleanBuilder(); if(!StringUtils.isEmpty(masterUserParam.getUserNo())) { builder.and(mst140.userNo.like(masterUserParam.getUserNo())); } if(!StringUtils.isEmpty(masterUserParam.getUserId())) { builder.and(sys800.userId.like("%" + masterUserParam.getUserId() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getUserType())) { builder.and(mst140.userType.like("%" + masterUserParam.getUserType() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getUserName())) { builder.and(mst140.userName.like("%" + masterUserParam.getUserName() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getDepartmentCode())) { builder.and(mst140.departmentCode.like("%" + masterUserParam.getDepartmentCode() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getGradeCode())) { builder.and(mst140.gradeCode.like("%" + masterUserParam.getGradeCode() + "%")); } if(!StringUtils.isEmpty(masterUserParam.getTeamCode())) { builder.and(mst140.teamCode.like("%" + masterUserParam.getTeamCode() + "%")); } // builder.and(qmst140.used.eq(0)); QueryResults<MST140> result = query.from(mst140) .select(mst140) .where(builder) .innerJoin(mst140.sys800, sys800) .fetchJoin() .offset(pageable.getOffset()) .limit(pageable.getPageSize()) .orderBy(mst140.createTime.desc(), mst140.userNo.asc()) .fetchResults(); return new PageImpl<>(result.getResults(), pageable, result.getTotal()); } @Override public List<MST140> findAll() { JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QMST141 mst141 = QMST141.mST141; QSYS800 sys800 = QSYS800.sYS800; List<MST140> result = query.from(mst140) .select(mst140) .innerJoin(mst140.sys800, sys800) .fetchJoin() .innerJoin(mst140.sys800.roles) .fetchJoin() .leftJoin(mst140.mst141, mst141) .fetchJoin() .fetch().stream().distinct().collect(Collectors.toList()); return result; } @Override public Optional<MST140> findByIdCustom(String userNo) { JPAQueryFactory query = new JPAQueryFactory(this.getEntityManager()); QMST140 mst140 = QMST140.mST140; QMST141 mst141 = QMST141.mST141; QSYS800 sys800 = QSYS800.sYS800; BooleanBuilder builder = new BooleanBuilder(); builder.and(mst140.userNo.eq(userNo)); Optional<MST140> result = Optional.ofNullable(query.from(mst140) .select(mst140) .where(builder) .leftJoin(mst140.sys800, sys800) .fetchJoin() .leftJoin(sys800.roles) .fetchJoin() .leftJoin(mst140.mst141, mst141) .fetchJoin() .fetchOne()); return result; } }
4,014
0.736423
0.673393
119
32.731091
25.707043
103
false
false
0
0
0
0
0
0
2.504202
false
false
4
4ab9972903487a37b2f31a96ed8ef2e7792a241c
37,400,575,228,836
b50de2737cc27cfa765a95dddc2fcee7c039b3dd
/src/main/java/br/com/db1/passwordmeter/meter/addition/NumberCharactersAdditionMeter.java
306be38c1eefd9d7608ab2b4e4f58893c36c21e6
[]
no_license
altitdb/passwordmeter
https://github.com/altitdb/passwordmeter
080a17b5f5824acff37dfb8210df4bd0618aea1a
8be38594c2d4265fd41611db85548947eabeddfa
refs/heads/master
2020-03-18T08:10:32.972000
2018-05-23T03:57:16
2018-05-23T03:57:16
134,478,467
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.db1.passwordmeter.meter.addition; import br.com.db1.passwordmeter.meter.Meter; public class NumberCharactersAdditionMeter implements Meter { @Override public Integer calculate(String password) { Integer len = password.length(); return len * 4; } }
UTF-8
Java
295
java
NumberCharactersAdditionMeter.java
Java
[]
null
[]
package br.com.db1.passwordmeter.meter.addition; import br.com.db1.passwordmeter.meter.Meter; public class NumberCharactersAdditionMeter implements Meter { @Override public Integer calculate(String password) { Integer len = password.length(); return len * 4; } }
295
0.715254
0.705085
13
21.692308
22.147701
61
false
false
0
0
0
0
0
0
0.307692
false
false
4
82a5bfa0a572f66c6f155719ce338c166b8deae5
34,677,565,985,237
4b10bb3e21493bb9a9fd50ecde83d1b25742cabc
/lab4/src/CarFactory/Factory/EngineSupplier.java
9ecbc8608371085d14ef6f79b9dfca8c62d51c82
[]
no_license
n-pogodaev/java-labs
https://github.com/n-pogodaev/java-labs
81edd00d0ce9103a070e8a138eeea9753cba8e26
108cdebdfbe70cf6ff6d05c996a5dff8470a09c9
refs/heads/master
2021-04-10T04:03:52.811000
2020-06-27T04:17:13
2020-06-27T04:17:13
248,909,302
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package CarFactory.Factory; public class EngineSupplier extends Supplier { private final CarFactoryStatistics stat; public EngineSupplier(Stock stock, int milliseconds, CarFactoryStatistics stat) { super(stock, milliseconds); this.stat = stat; } @Override protected Engine create() { stat.incrementTotalEngines(); return new Engine(); } @Override protected void incrementStockSize() { stat.incrementEngineStockSize(); } }
UTF-8
Java
501
java
EngineSupplier.java
Java
[]
null
[]
package CarFactory.Factory; public class EngineSupplier extends Supplier { private final CarFactoryStatistics stat; public EngineSupplier(Stock stock, int milliseconds, CarFactoryStatistics stat) { super(stock, milliseconds); this.stat = stat; } @Override protected Engine create() { stat.incrementTotalEngines(); return new Engine(); } @Override protected void incrementStockSize() { stat.incrementEngineStockSize(); } }
501
0.676647
0.676647
20
24.049999
21.327154
85
false
false
0
0
0
0
0
0
0.5
false
false
4
bca89a44df97eb5deb2435ad32f7d465d62db294
38,835,094,301,674
2e300b6c8022c0795ad113881240eecc3f7e6454
/library-rest/src/main/java/com/library/demo/controller/BookController.java
e162f987b91dc55440fda03674f278844f4dff50
[]
no_license
ayodhyagurram12/libraryApi
https://github.com/ayodhyagurram12/libraryApi
e23af004da4ec4ae83266b5f63b60c8c8b0392b8
bf08d53f4d24ae9beb0b5c7ccbd8bde5ad98513a
refs/heads/main
2023-05-09T05:34:56.688000
2021-06-06T12:51:29
2021-06-06T12:51:29
374,057,916
0
0
null
false
2021-06-06T12:51:30
2021-06-05T08:10:58
2021-06-06T12:35:12
2021-06-06T12:51:29
0
0
0
0
Java
false
false
package com.library.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.library.demo.entity.Book; import com.library.demo.service.BookService; @RestController @RequestMapping("/bookapi") public class BookController { // this is git // Testing Git @Autowired private BookService bookService; public BookController() { // TODO Auto-generated constructor stub } // Create End Point all books "/books" @GetMapping("/books") public List<Book> getAllBooks() { return bookService.findAll(); } // End point "/find/{bookId}" based on Id @GetMapping("/find/{bookId}") public Book findById(@PathVariable int bookId) { try { return bookService.findById(bookId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // End Point "/delete/{bookId}" @GetMapping("/delete/{bookId}") public void deleteById(@PathVariable int bookId) { bookService.deleteById(bookId); } // create new book "/newBook" @PostMapping("/newBook") public Book addBook(@RequestBody Book book) { book.setId(0); // remove id ,if passed bookService.save(book); return book; } // create UpdatBook "/updateBook" @PostMapping("/updateBook") public Book updateBook(@RequestBody Book book) { // book.setId(0); // remove id ,if passed bookService.save(book); return book; } }
UTF-8
Java
1,771
java
BookController.java
Java
[]
null
[]
package com.library.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.library.demo.entity.Book; import com.library.demo.service.BookService; @RestController @RequestMapping("/bookapi") public class BookController { // this is git // Testing Git @Autowired private BookService bookService; public BookController() { // TODO Auto-generated constructor stub } // Create End Point all books "/books" @GetMapping("/books") public List<Book> getAllBooks() { return bookService.findAll(); } // End point "/find/{bookId}" based on Id @GetMapping("/find/{bookId}") public Book findById(@PathVariable int bookId) { try { return bookService.findById(bookId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // End Point "/delete/{bookId}" @GetMapping("/delete/{bookId}") public void deleteById(@PathVariable int bookId) { bookService.deleteById(bookId); } // create new book "/newBook" @PostMapping("/newBook") public Book addBook(@RequestBody Book book) { book.setId(0); // remove id ,if passed bookService.save(book); return book; } // create UpdatBook "/updateBook" @PostMapping("/updateBook") public Book updateBook(@RequestBody Book book) { // book.setId(0); // remove id ,if passed bookService.save(book); return book; } }
1,771
0.743648
0.742518
71
23.943663
19.812422
62
false
false
0
0
0
0
0
0
1.197183
false
false
4
28bf6e7ab7e85dcd46f738689f04b97a2f90e516
8,005,819,092,455
ecb7a096c4ac4f138c3dbc5f45063b32b450bc85
/app/src/main/java/com/mtk/activity/MainActivity.java
368fb16e8eeb3dce13e0967d0693dcca86456c01
[]
no_license
chenjzcj/SmartBand
https://github.com/chenjzcj/SmartBand
fff90be4a8ccafcb89f83942f575dd91e877f78d
219aaa5ac5b728519099e42ed8783c5ef6d2cf59
refs/heads/master
2022-10-03T13:52:20.713000
2022-09-18T07:08:55
2022-09-18T07:08:55
143,897,583
5
10
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mtk.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.mtk.adapter.HomeAdapter; import com.mtk.band.AlarmActivity; import com.mtk.band.SportActivity; import com.mtk.band.utils.SharedPreferencesUtils; import com.mtk.band.utils.Tools; import com.mtk.base.BaseActivity; import com.mtk.data.PreferenceData; import com.mtk.eventbus.DataUpdateEvent; import com.mtk.receiver.ScreenBroadcastReceiver; import com.mtk.remotecamera.RemoteCameraService; import com.mtk.service.MainService; import com.mtk.util.BluetoothUtils; import com.mtk.util.DateUtils; import com.mtk.util.FileUtils; import com.mtk.util.LogUtils; import com.ruanan.btnotification.R; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; /** * 首页 */ public class MainActivity extends BaseActivity { //指向右边的箭头 private ImageView arrowRight0, arrowRight1, arrowRight2, arrowRight3, arrowRight4; //指向左边的箭头 private ImageView arrowLeft0, arrowLeft1, arrowLeft2, arrowLeft3, arrowLeft4; //蓝牙连接状态 private TextView tvConnectStatus; private GridView gridview; //存放箭头图片ImageView private ArrayList<ImageView> imageViews; private Timer timer; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); //LogUtils.i("msg.arg1=" + msg.arg1); setBTLinkState(); //实时获取蓝牙状态并刷新显示 for (ImageView imageView : imageViews) { imageView.setSelected(imageViews.get(msg.arg1) == imageView); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); setBTLinkState(); //如果蓝牙通知服务不可用并且通知服务对象为null,则弹出对话框提示用户启用辅助功能 if (!PreferenceData.isNotificationServiceEnable() && !MainService.isNotificationServiceActived()) { //智能手环暂时不需要这个,先注释 //DialogHelper.showAccessibilityPrompt(context); } //短信服务和通知服务是否在运行 if (PreferenceData.isSmsServiceEnable() || PreferenceData.isNotificationServiceEnable()) { startMainService(); } //检查更新 //UpdateUtils.checkAppUpdate(true, context); //开始箭头动画 this.startArrowAnim(); registerReceiver(new ScreenBroadcastReceiver(), ScreenBroadcastReceiver.genIntentFilter()); } @Override protected void initView() { super.initView(); arrowRight0 = (ImageView) findViewById(R.id.iv_connect_right_0); arrowRight1 = (ImageView) findViewById(R.id.iv_connect_right_1); arrowRight2 = (ImageView) findViewById(R.id.iv_connect_right_2); arrowRight3 = (ImageView) findViewById(R.id.iv_connect_right_3); arrowRight4 = (ImageView) findViewById(R.id.iv_connect_right_4); arrowLeft0 = (ImageView) findViewById(R.id.iv_connect_left_0); arrowLeft1 = (ImageView) findViewById(R.id.iv_connect_left_1); arrowLeft2 = (ImageView) findViewById(R.id.iv_connect_left_2); arrowLeft3 = (ImageView) findViewById(R.id.iv_connect_left_3); arrowLeft4 = (ImageView) findViewById(R.id.iv_connect_left_4); tvConnectStatus = (TextView) findViewById(R.id.tv_connect_status); gridview = (GridView) findViewById(R.id.gridview); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = null; switch (position) { case 0://找手表 MobclickAgent.onEvent(context, "click_findwatch", "find_watch"); //统计找手表点击次数 findWatch(); break; case 1://应用开关 MobclickAgent.onEvent(context, "click_notif_mannager", "notif_mannager"); //统计应用开关点击次数 openAccessibilitySettings(); break; case 2://设置 MobclickAgent.onEvent(context, "click_settings", "settings"); //统计设置点击次数 intent = new Intent(context, SettingsActivity.class); break; case 3://打开蓝牙配对 MobclickAgent.onEvent(context, "click_bluetooth_settings", "blue_settings"); //统计设置点击次数 openBluetoothSettings(); break; case 4://运动计步 intent = SportActivity.enterSportActivity(context, false); break; case 5://睡眠监测 intent = SportActivity.enterSportActivity(context, true); break; case 6://智能闹钟 intent = new Intent(context, AlarmActivity.class); break; case 7://关于 intent = new Intent(context, AboutActivity.class); break; } if (intent != null) { startActivity(intent); overridePendingTransition(R.anim.push_left_acc, 0); } } }); } @Override protected void initData() { super.initData(); //将箭头放入集合中 imageViews = new ArrayList<>(); this.imageViews.add(arrowRight0); this.imageViews.add(arrowRight1); this.imageViews.add(arrowRight2); this.imageViews.add(arrowRight3); this.imageViews.add(arrowRight4); this.imageViews.add(arrowLeft4); this.imageViews.add(arrowLeft3); this.imageViews.add(arrowLeft2); this.imageViews.add(arrowLeft1); this.imageViews.add(arrowLeft0); /************初始化griView相关数据************/ String[] itemTexts = getResources().getStringArray(R.array.home_items); ArrayList<Integer> imgResIds = new ArrayList<>(); imgResIds.add(R.drawable.ic_findwatch); imgResIds.add(R.drawable.ic_app_license); imgResIds.add(R.drawable.ic_settings); imgResIds.add(R.drawable.ic_blutooth_repair); imgResIds.add(R.drawable.ic_sport); imgResIds.add(R.drawable.ic_sleep); imgResIds.add(R.drawable.icon_alarm); imgResIds.add(R.drawable.ic_about); this.gridview.setAdapter(new HomeAdapter(this, itemTexts, imgResIds)); } /** * 设置蓝牙连接状态 */ private void setBTLinkState() { boolean btConnected = MainService.mBluetoothManager.isBTConnected(); tvConnectStatus.setText(btConnected ? getString(R.string.connected) : getString(R.string.disconnected)); } private int arrowIndex = 0;//箭头角标 /** * 运行箭头动画效果 */ private void startArrowAnim() { this.timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { mHandler.obtainMessage(0, arrowIndex++ % imageViews.size(), 0).sendToTarget(); } }; this.timer.schedule(task, 1000, 1000); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(this.getClass().getSimpleName()); MobclickAgent.onResume(context); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(this.getClass().getSimpleName()); MobclickAgent.onPause(context); } /** * 开启主服务 */ private void startMainService() { startService(new Intent(context, MainService.class)); } /** * 打开蓝牙设置页面 */ private void openBluetoothSettings() { startActivity(BluetoothUtils.repairBluetooth()); } /** * 打开辅助功能设置页面 */ private void openAccessibilitySettings() { startActivity(new Intent("android.settings.ACCESSIBILITY_SETTINGS")); } /** * 找手表 */ private void findWatch() { String command = String.valueOf(6) + RemoteCameraService.Commands.NUM_OF_START_ACTIFITY_ARGS; if (BluetoothUtils.getBlutootnLinkState()) { MainService.getInstance().sendCAPCResult(command); } else { openBluetoothSettings(); } } @Override public void onBackPressed() { //统计程序退出 MobclickAgent.onProfileSignOff(); Tools.stepStop(); //super.onBackPressed(); moveTaskToBack(true); } @Override protected void onDestroy() { if (this.imageViews != null) { this.imageViews.clear(); this.imageViews = null; } if (timer != null) { this.timer.cancel(); this.timer = null; } super.onDestroy(); } @Override public void onEventMainThread(Object obj) { if (obj instanceof DataUpdateEvent) { int length = ((DataUpdateEvent) obj).getLength(); String data = ((DataUpdateEvent) obj).getData().substring(0, length); if (!data.contains("GET,")) { return; } LogUtils.i("MainActivity data = " + data); String[] split = data.split(","); String sleepData = split[3];//睡眠数据 //如果当前时间在头一天的晚上11点与第二天早上7点之间,则启动睡眠 if (DateUtils.isCurTimeInRange()) { parseSleepData(sleepData); } } } /** * 解析睡眠监测数据 * * @param sleepData 格式:1|1479720600|0|5 */ private void parseSleepData(String sleepData) { LogUtils.i("parseSleepData sleepData " + sleepData); FileUtils.writeFile(sleepData, "sleep", DateUtils.getDateStr(System.currentTimeMillis(), "yyyyMMddHHmmss") + ".txt"); //在睡眠状态走的步数,根据这个值来判断睡眠质量 String sleepStep = sleepData.split("\\|")[3]; SharedPreferencesUtils.saveSleepStep(context, Integer.parseInt(sleepStep)); } }
UTF-8
Java
10,966
java
MainActivity.java
Java
[]
null
[]
package com.mtk.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.mtk.adapter.HomeAdapter; import com.mtk.band.AlarmActivity; import com.mtk.band.SportActivity; import com.mtk.band.utils.SharedPreferencesUtils; import com.mtk.band.utils.Tools; import com.mtk.base.BaseActivity; import com.mtk.data.PreferenceData; import com.mtk.eventbus.DataUpdateEvent; import com.mtk.receiver.ScreenBroadcastReceiver; import com.mtk.remotecamera.RemoteCameraService; import com.mtk.service.MainService; import com.mtk.util.BluetoothUtils; import com.mtk.util.DateUtils; import com.mtk.util.FileUtils; import com.mtk.util.LogUtils; import com.ruanan.btnotification.R; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; /** * 首页 */ public class MainActivity extends BaseActivity { //指向右边的箭头 private ImageView arrowRight0, arrowRight1, arrowRight2, arrowRight3, arrowRight4; //指向左边的箭头 private ImageView arrowLeft0, arrowLeft1, arrowLeft2, arrowLeft3, arrowLeft4; //蓝牙连接状态 private TextView tvConnectStatus; private GridView gridview; //存放箭头图片ImageView private ArrayList<ImageView> imageViews; private Timer timer; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); //LogUtils.i("msg.arg1=" + msg.arg1); setBTLinkState(); //实时获取蓝牙状态并刷新显示 for (ImageView imageView : imageViews) { imageView.setSelected(imageViews.get(msg.arg1) == imageView); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); setBTLinkState(); //如果蓝牙通知服务不可用并且通知服务对象为null,则弹出对话框提示用户启用辅助功能 if (!PreferenceData.isNotificationServiceEnable() && !MainService.isNotificationServiceActived()) { //智能手环暂时不需要这个,先注释 //DialogHelper.showAccessibilityPrompt(context); } //短信服务和通知服务是否在运行 if (PreferenceData.isSmsServiceEnable() || PreferenceData.isNotificationServiceEnable()) { startMainService(); } //检查更新 //UpdateUtils.checkAppUpdate(true, context); //开始箭头动画 this.startArrowAnim(); registerReceiver(new ScreenBroadcastReceiver(), ScreenBroadcastReceiver.genIntentFilter()); } @Override protected void initView() { super.initView(); arrowRight0 = (ImageView) findViewById(R.id.iv_connect_right_0); arrowRight1 = (ImageView) findViewById(R.id.iv_connect_right_1); arrowRight2 = (ImageView) findViewById(R.id.iv_connect_right_2); arrowRight3 = (ImageView) findViewById(R.id.iv_connect_right_3); arrowRight4 = (ImageView) findViewById(R.id.iv_connect_right_4); arrowLeft0 = (ImageView) findViewById(R.id.iv_connect_left_0); arrowLeft1 = (ImageView) findViewById(R.id.iv_connect_left_1); arrowLeft2 = (ImageView) findViewById(R.id.iv_connect_left_2); arrowLeft3 = (ImageView) findViewById(R.id.iv_connect_left_3); arrowLeft4 = (ImageView) findViewById(R.id.iv_connect_left_4); tvConnectStatus = (TextView) findViewById(R.id.tv_connect_status); gridview = (GridView) findViewById(R.id.gridview); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = null; switch (position) { case 0://找手表 MobclickAgent.onEvent(context, "click_findwatch", "find_watch"); //统计找手表点击次数 findWatch(); break; case 1://应用开关 MobclickAgent.onEvent(context, "click_notif_mannager", "notif_mannager"); //统计应用开关点击次数 openAccessibilitySettings(); break; case 2://设置 MobclickAgent.onEvent(context, "click_settings", "settings"); //统计设置点击次数 intent = new Intent(context, SettingsActivity.class); break; case 3://打开蓝牙配对 MobclickAgent.onEvent(context, "click_bluetooth_settings", "blue_settings"); //统计设置点击次数 openBluetoothSettings(); break; case 4://运动计步 intent = SportActivity.enterSportActivity(context, false); break; case 5://睡眠监测 intent = SportActivity.enterSportActivity(context, true); break; case 6://智能闹钟 intent = new Intent(context, AlarmActivity.class); break; case 7://关于 intent = new Intent(context, AboutActivity.class); break; } if (intent != null) { startActivity(intent); overridePendingTransition(R.anim.push_left_acc, 0); } } }); } @Override protected void initData() { super.initData(); //将箭头放入集合中 imageViews = new ArrayList<>(); this.imageViews.add(arrowRight0); this.imageViews.add(arrowRight1); this.imageViews.add(arrowRight2); this.imageViews.add(arrowRight3); this.imageViews.add(arrowRight4); this.imageViews.add(arrowLeft4); this.imageViews.add(arrowLeft3); this.imageViews.add(arrowLeft2); this.imageViews.add(arrowLeft1); this.imageViews.add(arrowLeft0); /************初始化griView相关数据************/ String[] itemTexts = getResources().getStringArray(R.array.home_items); ArrayList<Integer> imgResIds = new ArrayList<>(); imgResIds.add(R.drawable.ic_findwatch); imgResIds.add(R.drawable.ic_app_license); imgResIds.add(R.drawable.ic_settings); imgResIds.add(R.drawable.ic_blutooth_repair); imgResIds.add(R.drawable.ic_sport); imgResIds.add(R.drawable.ic_sleep); imgResIds.add(R.drawable.icon_alarm); imgResIds.add(R.drawable.ic_about); this.gridview.setAdapter(new HomeAdapter(this, itemTexts, imgResIds)); } /** * 设置蓝牙连接状态 */ private void setBTLinkState() { boolean btConnected = MainService.mBluetoothManager.isBTConnected(); tvConnectStatus.setText(btConnected ? getString(R.string.connected) : getString(R.string.disconnected)); } private int arrowIndex = 0;//箭头角标 /** * 运行箭头动画效果 */ private void startArrowAnim() { this.timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { mHandler.obtainMessage(0, arrowIndex++ % imageViews.size(), 0).sendToTarget(); } }; this.timer.schedule(task, 1000, 1000); } @Override public void onResume() { super.onResume(); MobclickAgent.onPageStart(this.getClass().getSimpleName()); MobclickAgent.onResume(context); } @Override public void onPause() { super.onPause(); MobclickAgent.onPageEnd(this.getClass().getSimpleName()); MobclickAgent.onPause(context); } /** * 开启主服务 */ private void startMainService() { startService(new Intent(context, MainService.class)); } /** * 打开蓝牙设置页面 */ private void openBluetoothSettings() { startActivity(BluetoothUtils.repairBluetooth()); } /** * 打开辅助功能设置页面 */ private void openAccessibilitySettings() { startActivity(new Intent("android.settings.ACCESSIBILITY_SETTINGS")); } /** * 找手表 */ private void findWatch() { String command = String.valueOf(6) + RemoteCameraService.Commands.NUM_OF_START_ACTIFITY_ARGS; if (BluetoothUtils.getBlutootnLinkState()) { MainService.getInstance().sendCAPCResult(command); } else { openBluetoothSettings(); } } @Override public void onBackPressed() { //统计程序退出 MobclickAgent.onProfileSignOff(); Tools.stepStop(); //super.onBackPressed(); moveTaskToBack(true); } @Override protected void onDestroy() { if (this.imageViews != null) { this.imageViews.clear(); this.imageViews = null; } if (timer != null) { this.timer.cancel(); this.timer = null; } super.onDestroy(); } @Override public void onEventMainThread(Object obj) { if (obj instanceof DataUpdateEvent) { int length = ((DataUpdateEvent) obj).getLength(); String data = ((DataUpdateEvent) obj).getData().substring(0, length); if (!data.contains("GET,")) { return; } LogUtils.i("MainActivity data = " + data); String[] split = data.split(","); String sleepData = split[3];//睡眠数据 //如果当前时间在头一天的晚上11点与第二天早上7点之间,则启动睡眠 if (DateUtils.isCurTimeInRange()) { parseSleepData(sleepData); } } } /** * 解析睡眠监测数据 * * @param sleepData 格式:1|1479720600|0|5 */ private void parseSleepData(String sleepData) { LogUtils.i("parseSleepData sleepData " + sleepData); FileUtils.writeFile(sleepData, "sleep", DateUtils.getDateStr(System.currentTimeMillis(), "yyyyMMddHHmmss") + ".txt"); //在睡眠状态走的步数,根据这个值来判断睡眠质量 String sleepStep = sleepData.split("\\|")[3]; SharedPreferencesUtils.saveSleepStep(context, Integer.parseInt(sleepStep)); } }
10,966
0.600792
0.592772
298
33.724831
26.214106
125
false
false
0
0
0
0
0
0
0.674497
false
false
4
c7e1721f56d9663ff5dd1c897fa69d375905f137
9,002,251,512,579
40a93333394e5e90dd503e53edd0131ede6bf6e2
/src/main/java/edu/jmu/sudi/controller/comment/CommentController.java
d09b3bd2424b34fe2cee81cb9de23a6fee0c0ef9
[]
no_license
hwx1210912620/snack_pro
https://github.com/hwx1210912620/snack_pro
43521dc7b45540a51fc3824620925f47c584591e
3133810a5c9206439811bab7da07a9096cf41d68
refs/heads/main
2023-03-28T14:50:34.518000
2021-03-30T09:33:13
2021-03-30T09:33:13
352,930,443
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.jmu.sudi.controller.comment; import com.alibaba.fastjson.JSON; import edu.jmu.sudi.service.CommentService; import edu.jmu.sudi.vo.CommentVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.Map; /** * 评论控制器 * @author LiangJie */ @RestController @RequestMapping("/reception/comment") public class CommentController { @Autowired private CommentService commentService; /** * 用户发表评论 * @param vo * @param session * @return */ @RequestMapping("/add") public String addComment(CommentVo vo, HttpSession session){ Map<String, Object> map = commentService.addComment(vo, session); return JSON.toJSONString(map); } /** * 查询该菜品下的所有评论 * @param foodId * @return */ @RequestMapping("/findByFood") public String findByFood(Long foodId){ Map<String, Object> map = commentService.findByFood(foodId); return JSON.toJSONString(map); } /** * 查询该用户的所有评论 * @param session * @return */ @RequestMapping("/findByUser") public String findByUser(HttpSession session){ Map<String, Object> map = commentService.findByUser(session); return JSON.toJSONString(map); } }
UTF-8
Java
1,490
java
CommentController.java
Java
[ { "context": "on;\nimport java.util.Map;\n\n/**\n * 评论控制器\n * @author LiangJie\n */\n@RestController\n@RequestMapping(\"/reception/c", "end": 438, "score": 0.998775064945221, "start": 430, "tag": "NAME", "value": "LiangJie" } ]
null
[]
package edu.jmu.sudi.controller.comment; import com.alibaba.fastjson.JSON; import edu.jmu.sudi.service.CommentService; import edu.jmu.sudi.vo.CommentVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.Map; /** * 评论控制器 * @author LiangJie */ @RestController @RequestMapping("/reception/comment") public class CommentController { @Autowired private CommentService commentService; /** * 用户发表评论 * @param vo * @param session * @return */ @RequestMapping("/add") public String addComment(CommentVo vo, HttpSession session){ Map<String, Object> map = commentService.addComment(vo, session); return JSON.toJSONString(map); } /** * 查询该菜品下的所有评论 * @param foodId * @return */ @RequestMapping("/findByFood") public String findByFood(Long foodId){ Map<String, Object> map = commentService.findByFood(foodId); return JSON.toJSONString(map); } /** * 查询该用户的所有评论 * @param session * @return */ @RequestMapping("/findByUser") public String findByUser(HttpSession session){ Map<String, Object> map = commentService.findByUser(session); return JSON.toJSONString(map); } }
1,490
0.683029
0.683029
58
23.586206
20.97785
73
false
false
0
0
0
0
0
0
0.362069
false
false
4
21254e384156e8570558b2a749f7d26bed5f9435
24,464,133,770,275
e95fbb81f00864cc37084cfc67e42ed6649479e2
/src/main/java/com/servicesImpl/UserServiceImpl.java
03ffa33209f227d6356bc958eb7974395b777960
[]
no_license
revatureclass/1808java-nick-project1-christian-dawson
https://github.com/revatureclass/1808java-nick-project1-christian-dawson
2ed02713358ac1b33c64c4fda613a7bc8fe23a57
a7fbc8d15d8ab9959f434cf1d40444e31034b5f0
refs/heads/master
2018-12-22T18:31:17.915000
2018-10-03T20:55:36
2018-10-03T20:55:36
150,826,988
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.servicesImpl; import java.util.ArrayList; import com.daoImpl.UserDaoImpl; import com.daoModel.UserDaoModel; import com.exceptions.DuplicateIdException; import com.exceptions.MissingDataException; import com.pojos.User; import com.servicesModel.UserServiceModel; public class UserServiceImpl implements UserServiceModel{ UserDaoModel userDB; public UserServiceImpl() { userDB = new UserDaoImpl(); } @Override public User authenticateUser(User user) { User authenticated = userDB.find(user.getEmployeeID()); if(authenticated == null || !authenticated.getPassword().equals(user.getPassword())) return null; return authenticated; } public void registerUser(User user) throws MissingDataException, DuplicateIdException{ if(userDB.find(user.getEmployeeID()) != null) throw new DuplicateIdException(); if(user.getAddress().equals("") || user.getBirthdate().equals("") || user.getEmployeeID().equals("") || user.getFirstName().equals("") || user.getLastName().equals("") || user.getPassword().equals("") || user.getPosition().equals("") || user.getSuperID().equals("")) { throw new MissingDataException(); } userDB.insert(user); } @Override public User getUser(User user) { User toReturn = userDB.find(user.getEmployeeID()); return toReturn; } @Override public ArrayList<User> getAll() { return userDB.getAll(); } }
UTF-8
Java
1,378
java
UserServiceImpl.java
Java
[]
null
[]
package com.servicesImpl; import java.util.ArrayList; import com.daoImpl.UserDaoImpl; import com.daoModel.UserDaoModel; import com.exceptions.DuplicateIdException; import com.exceptions.MissingDataException; import com.pojos.User; import com.servicesModel.UserServiceModel; public class UserServiceImpl implements UserServiceModel{ UserDaoModel userDB; public UserServiceImpl() { userDB = new UserDaoImpl(); } @Override public User authenticateUser(User user) { User authenticated = userDB.find(user.getEmployeeID()); if(authenticated == null || !authenticated.getPassword().equals(user.getPassword())) return null; return authenticated; } public void registerUser(User user) throws MissingDataException, DuplicateIdException{ if(userDB.find(user.getEmployeeID()) != null) throw new DuplicateIdException(); if(user.getAddress().equals("") || user.getBirthdate().equals("") || user.getEmployeeID().equals("") || user.getFirstName().equals("") || user.getLastName().equals("") || user.getPassword().equals("") || user.getPosition().equals("") || user.getSuperID().equals("")) { throw new MissingDataException(); } userDB.insert(user); } @Override public User getUser(User user) { User toReturn = userDB.find(user.getEmployeeID()); return toReturn; } @Override public ArrayList<User> getAll() { return userDB.getAll(); } }
1,378
0.736575
0.736575
47
28.319149
29.342516
105
false
false
0
0
0
0
0
0
1.808511
false
false
4
f8fba52721e40ea5cb92ef32ef02e17391a2ab8b
12,412,455,490,091
9fdd151c15d4604f263b7f3a19d29fbcfd0bed08
/src/main/java/com/cofco/appservice/service/UserService.java
21a3b6f0ec5af118de0d22e46ee210d75ad4d9b9
[]
no_license
hankuiwei/COFCOService
https://github.com/hankuiwei/COFCOService
f9d77f05724ae1e440dd0c5c530e39edc4e309bd
05f0be56cd23898b4c03ca5d9b647c74fb5aa2e4
refs/heads/master
2020-03-23T12:14:32.149000
2018-10-18T02:40:51
2018-10-18T02:40:51
141,546,100
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cofco.appservice.service; import com.cofco.appservice.bean.RestFulBean; import com.cofco.appservice.bean.UserBean; import com.cofco.appservice.util.RestFulUtil; import com.cofco.appservice.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * Created by ywl5320 on 2017/10/12. */ @Transactional public class UserService { @Autowired private UserDao userDao; /*public RestFulBean<UserBean> registorServer(UserBean userBean) { UserBean user = userDao.getUser(userBean.getPhone()); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(null, 1, "已经注册过了"); } else { user = userDao.registor(userBean); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(user, 0, "注册成功"); } else{ return RestFulUtil.getInstance().getResuFulBean(null, 1, "注册失败"); } } }*/ public RestFulBean<UserBean> login(String username, String usercode) { UserBean user = userDao.login(username, usercode); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(user, 200, "登录成功"); } else { return RestFulUtil.getInstance().getResuFulBean(null, 201, "用户不存在"); } } }
UTF-8
Java
1,515
java
UserService.java
Java
[ { "context": "ction.annotation.Transactional;\n\n/**\n * Created by ywl5320 on 2017/10/12.\n */\n@Transactional\npublic class Us", "end": 369, "score": 0.9990906715393066, "start": 362, "tag": "USERNAME", "value": "ywl5320" } ]
null
[]
package com.cofco.appservice.service; import com.cofco.appservice.bean.RestFulBean; import com.cofco.appservice.bean.UserBean; import com.cofco.appservice.util.RestFulUtil; import com.cofco.appservice.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * Created by ywl5320 on 2017/10/12. */ @Transactional public class UserService { @Autowired private UserDao userDao; /*public RestFulBean<UserBean> registorServer(UserBean userBean) { UserBean user = userDao.getUser(userBean.getPhone()); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(null, 1, "已经注册过了"); } else { user = userDao.registor(userBean); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(user, 0, "注册成功"); } else{ return RestFulUtil.getInstance().getResuFulBean(null, 1, "注册失败"); } } }*/ public RestFulBean<UserBean> login(String username, String usercode) { UserBean user = userDao.login(username, usercode); if(user != null) { return RestFulUtil.getInstance().getResuFulBean(user, 200, "登录成功"); } else { return RestFulUtil.getInstance().getResuFulBean(null, 201, "用户不存在"); } } }
1,515
0.619469
0.605174
54
26.203703
26.393307
81
false
false
0
0
0
0
0
0
0.518519
false
false
4
116d542eaa84b58168604442dae8dd35d001a63a
12,412,455,485,761
40608328ae11258c14e48339e4a3b3c7729a98d9
/app/src/main/java/com/example/last/DetailsAdapter.java
bd6664a5856c169d1fe55d90914bf5f2128fe904
[]
no_license
fardoush/CountryProject
https://github.com/fardoush/CountryProject
ea7e8f08ed7a0323b802f349b91a2e6656c02e70
a0b4009d5e549525217f163cd3086bfea3102781
refs/heads/master
2020-09-27T09:35:10.545000
2019-12-07T09:29:40
2019-12-07T09:29:40
226,486,389
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.last; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; //class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.ViewHolder> { //} import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.ViewHolder> { //context+data private Context context; //model private List<Details>detailsList; public DetailsAdapter(Context context, List<Details> cricketerList) { this.context = context; this.detailsList = cricketerList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {//call 1st step View view= LayoutInflater.from(context).inflate(R.layout.sample,null); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {//set 3 rd step // img,name set viewHolder.imageView.setImageResource(detailsList.get(i).getImage()); viewHolder.textView.setText(detailsList.get(i).getName()); viewHolder.textView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(context,SecondActivity.class); /* intent.putExtra("Name",(detailsList.get(i).getName())); intent.putExtra("img",(detailsList.get(i).getImage()));*/ // intent.putExtra("detailse",(detailsList.get(i).getName())); context.startActivity(intent); } }); } @Override public int getItemCount() { return detailsList.size(); } class ViewHolder extends RecyclerView.ViewHolder{//find|hold 2nd step //find ImageView imageView; TextView textView,textView1; public ViewHolder(@NonNull View itemView) { super(itemView); imageView= itemView.findViewById(R.id.imageviewId); textView= itemView.findViewById(R.id.textviewId); textView1=itemView.findViewById(R.id.texDetails); } } { } }
UTF-8
Java
2,377
java
DetailsAdapter.java
Java
[]
null
[]
package com.example.last; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; //class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.ViewHolder> { //} import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.ViewHolder> { //context+data private Context context; //model private List<Details>detailsList; public DetailsAdapter(Context context, List<Details> cricketerList) { this.context = context; this.detailsList = cricketerList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {//call 1st step View view= LayoutInflater.from(context).inflate(R.layout.sample,null); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {//set 3 rd step // img,name set viewHolder.imageView.setImageResource(detailsList.get(i).getImage()); viewHolder.textView.setText(detailsList.get(i).getName()); viewHolder.textView1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(context,SecondActivity.class); /* intent.putExtra("Name",(detailsList.get(i).getName())); intent.putExtra("img",(detailsList.get(i).getImage()));*/ // intent.putExtra("detailse",(detailsList.get(i).getName())); context.startActivity(intent); } }); } @Override public int getItemCount() { return detailsList.size(); } class ViewHolder extends RecyclerView.ViewHolder{//find|hold 2nd step //find ImageView imageView; TextView textView,textView1; public ViewHolder(@NonNull View itemView) { super(itemView); imageView= itemView.findViewById(R.id.imageviewId); textView= itemView.findViewById(R.id.textviewId); textView1=itemView.findViewById(R.id.texDetails); } } { } }
2,377
0.670593
0.668069
86
26.651163
28.050522
94
false
false
0
0
0
0
0
0
0.5
false
false
4
6026cf9f49b035bcc202a1c5dc2bd1b5a85f0d4b
33,569,464,387,854
0255630ddf9a1ae73f654865da9d6e73e62dd214
/client/src/main/java/ru/benedictfonshuse/tm/command/assign/create/AssignCreatePTCommand.java
842404835a6692334b9017ec92b28b9a558827d3
[]
no_license
BenedictFonShuse/unknownTm2
https://github.com/BenedictFonShuse/unknownTm2
6b7740dc15fb3804977c785c8d6b3261da0cdd8f
7f9430b2c0354806115843148e8bf7926f842c8c
refs/heads/master
2020-05-20T14:04:35.125000
2019-05-28T16:04:19
2019-05-28T16:04:19
185,614,717
0
0
null
false
2020-07-01T23:04:01
2019-05-08T13:46:51
2019-05-28T16:04:27
2020-07-01T23:03:59
97
0
0
2
Java
false
false
package ru.benedictfonshuse.tm.command.assign.create; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ru.benedictfonshuse.tm.command.AbstractCommand; import ru.benedictfonshuse.tm.endpoint.AdminEndpoint; @Component @NoArgsConstructor public final class AssignCreatePTCommand extends AbstractCommand { @NotNull public static final String NAME = "createassignPT"; @Autowired private AdminEndpoint adminEndpoint; @Override @NotNull public final String getName() { return NAME; } @Override public @Nullable String getDescription() { return null; } @Override public final void execute() { String projectId = terminalService.nextLine(); System.out.println("Напишите id проекта"); String taskId = terminalService.nextLine(); System.out.println("Напишите id задачи"); adminEndpoint.createAssignProjectTask(tokenOperation.getService().getToken(), projectId, taskId); } @Override @NotNull public final boolean isNeedAuthoryze() { return true; } }
UTF-8
Java
1,298
java
AssignCreatePTCommand.java
Java
[]
null
[]
package ru.benedictfonshuse.tm.command.assign.create; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ru.benedictfonshuse.tm.command.AbstractCommand; import ru.benedictfonshuse.tm.endpoint.AdminEndpoint; @Component @NoArgsConstructor public final class AssignCreatePTCommand extends AbstractCommand { @NotNull public static final String NAME = "createassignPT"; @Autowired private AdminEndpoint adminEndpoint; @Override @NotNull public final String getName() { return NAME; } @Override public @Nullable String getDescription() { return null; } @Override public final void execute() { String projectId = terminalService.nextLine(); System.out.println("Напишите id проекта"); String taskId = terminalService.nextLine(); System.out.println("Напишите id задачи"); adminEndpoint.createAssignProjectTask(tokenOperation.getService().getToken(), projectId, taskId); } @Override @NotNull public final boolean isNeedAuthoryze() { return true; } }
1,298
0.729708
0.729708
45
27.200001
23.887327
105
false
false
0
0
0
0
0
0
0.444444
false
false
4
26d708c1521086ceb2b8a15895d9ddd145742fd2
13,967,233,704,317
2aff89b98a1e6d7052671f77e156017ff15a99d9
/src/test/java/daos/CarTest.java
a6ad137a3fd2ee4622b8e05a5c903402e416f08c
[]
no_license
muhammeta7/Maven.JDBC-DAO
https://github.com/muhammeta7/Maven.JDBC-DAO
73196bb63825893e780c7ef742355f49bb23de5b
c6d40b4d552bfb28770d89b4d6ffeda475069bd6
refs/heads/master
2021-03-27T02:57:14.536000
2020-03-22T01:09:49
2020-03-22T01:09:49
247,779,102
0
0
null
true
2020-03-16T17:36:51
2020-03-16T17:36:50
2019-03-20T16:55:32
2019-12-13T19:20:20
6
0
0
0
null
false
false
package daos; import static org.junit.Assert.*; import org.junit.Test; import java.util.List; public class CarTest { CarDAO car = new CarDAO(); CarDTO carDTO = new CarDTO( 6, "Honda", "Civic", 2016, "blue" ); @Test public void getCarFromResultSetTest(){ CarDTO newCar = car.findById(1); assertEquals(newCar.getId(), newCar.getCarById()); } @Test public void findCarByIdTest(){ CarDTO newCar = car.findById(1); assertEquals("Honda", newCar.getMake()); assertEquals("Civic", newCar.getModel()); assertEquals(2019, newCar.getYear()); assertEquals("red", newCar.getColor()); } @Test public void findAllTest(){ List<CarDTO> list = car.findAll(); int expectedSize = 5; int actualSize = list.size(); assertEquals(expectedSize, actualSize); } @Test public void createCarTest(){ assertTrue(car.create(carDTO)); car.delete(6); } @Test public void deleteCarTest(){ car.create(carDTO); assertEquals(6, carDTO.getId()); car.delete(6); assertNull(car.findById(6)); } @Test public void UpdateCarTest(){ car.create(carDTO); CarDTO expected = new CarDTO(6, "Benz", "350", 2019, "pink"); car.update(expected); CarDTO actual = car.findById(6); assertEquals(expected.getColor(), actual.getColor()); assertEquals(expected.getModel(), actual.getModel()); assertEquals(expected.getYear(), actual.getYear()); assertEquals(expected.getMake(), actual.getMake()); } }
UTF-8
Java
1,701
java
CarTest.java
Java
[ { "context": "carDTO);\n CarDTO expected = new CarDTO(6, \"Benz\", \"350\", 2019, \"pink\");\n car.update(expect", "end": 1352, "score": 0.882908284664154, "start": 1348, "tag": "NAME", "value": "Benz" } ]
null
[]
package daos; import static org.junit.Assert.*; import org.junit.Test; import java.util.List; public class CarTest { CarDAO car = new CarDAO(); CarDTO carDTO = new CarDTO( 6, "Honda", "Civic", 2016, "blue" ); @Test public void getCarFromResultSetTest(){ CarDTO newCar = car.findById(1); assertEquals(newCar.getId(), newCar.getCarById()); } @Test public void findCarByIdTest(){ CarDTO newCar = car.findById(1); assertEquals("Honda", newCar.getMake()); assertEquals("Civic", newCar.getModel()); assertEquals(2019, newCar.getYear()); assertEquals("red", newCar.getColor()); } @Test public void findAllTest(){ List<CarDTO> list = car.findAll(); int expectedSize = 5; int actualSize = list.size(); assertEquals(expectedSize, actualSize); } @Test public void createCarTest(){ assertTrue(car.create(carDTO)); car.delete(6); } @Test public void deleteCarTest(){ car.create(carDTO); assertEquals(6, carDTO.getId()); car.delete(6); assertNull(car.findById(6)); } @Test public void UpdateCarTest(){ car.create(carDTO); CarDTO expected = new CarDTO(6, "Benz", "350", 2019, "pink"); car.update(expected); CarDTO actual = car.findById(6); assertEquals(expected.getColor(), actual.getColor()); assertEquals(expected.getModel(), actual.getModel()); assertEquals(expected.getYear(), actual.getYear()); assertEquals(expected.getMake(), actual.getMake()); } }
1,701
0.580247
0.56555
71
22.957747
19.367052
69
false
false
0
0
0
0
0
0
0.704225
false
false
4
60a8ecdcdc2a7553942b4545b47d14b790b1518b
13,967,233,705,395
90dea0ade353e87567f49a3e157d6cb2afb5edaf
/WOB_SERVER_2/atavism_source_from_Procyon/atavism/msgsys/MessageDispatch.java
6dafc7876be7ebcb8510ac9eb6928f42ac3c9ae0
[]
no_license
huangwei2wei/app
https://github.com/huangwei2wei/app
1f13925d5171b96a63c50ab536a9da74deb6a1e0
a06ed33c48ccda03095bb709870494d5842d38d5
refs/heads/master
2020-12-21T00:38:23.494000
2017-02-13T10:14:24
2017-02-13T10:14:24
56,054,605
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
// // Decompiled by Procyon v0.5.30 // package atavism.msgsys; public interface MessageDispatch { void dispatchMessage(final Message p0, final int p1, final MessageCallback p2); }
UTF-8
Java
188
java
MessageDispatch.java
Java
[]
null
[]
// // Decompiled by Procyon v0.5.30 // package atavism.msgsys; public interface MessageDispatch { void dispatchMessage(final Message p0, final int p1, final MessageCallback p2); }
188
0.739362
0.702128
10
17.799999
25.134836
83
false
false
0
0
0
0
0
0
0.4
false
false
4
e4eb6ac3456cc38dde9272d88f36c054759d0e86
10,419,590,673,948
05113928e482dc076af75c13f2e8b89abcf1390c
/designPatterns/ch16State/State.java
1510698e769ee817a2eccde446ad17717831270f
[]
no_license
CatherineLiyuankun/DesignPatterns
https://github.com/CatherineLiyuankun/DesignPatterns
721e0d44469288c09e55e42357f94c650f700f68
d418b58efc1f7d0d0e90386581fea69c3774d9de
refs/heads/master
2020-05-17T04:06:20.752000
2015-08-17T13:17:15
2015-08-17T13:17:15
40,895,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package designPatterns.ch16State; /** * Created by Catherine on 15/3/4. */ public abstract class State { public abstract void Handle(Context context); }
UTF-8
Java
157
java
State.java
Java
[ { "context": "ckage designPatterns.ch16State;\n\n/**\n * Created by Catherine on 15/3/4.\n */\npublic abstract class State {\n\tpub", "end": 62, "score": 0.9990952610969543, "start": 53, "tag": "NAME", "value": "Catherine" } ]
null
[]
package designPatterns.ch16State; /** * Created by Catherine on 15/3/4. */ public abstract class State { public abstract void Handle(Context context); }
157
0.738854
0.700637
8
18.625
17.485262
46
false
false
0
0
0
0
0
0
0.375
false
false
4
c7b9737f4d1d62e7f300e091a9f96a6ea1727375
31,275,951,914,574
b7e99495fdc3631b94ec737444eaa18abd9c5215
/smzdm-model/src/main/java/com/smzdm/model/CommodityTimeInfo.java
23d088a8afa361687509734adebbcce2009a689b
[]
no_license
changdy/Spider4smzdm
https://github.com/changdy/Spider4smzdm
82908438145d2d3055f34da5e823235263a1fc7a
002ad6788db7bfb7c15918f2e650eec078171dea
refs/heads/master
2022-12-23T04:34:31.193000
2019-08-03T03:29:24
2019-08-03T03:29:24
84,454,329
2
0
null
false
2022-12-16T11:04:24
2017-03-09T14:58:13
2020-07-30T12:40:23
2022-12-16T11:04:21
5,476
0
0
13
JavaScript
false
false
package com.smzdm.model; import java.util.Date; public class CommodityTimeInfo { private Integer id; private Long articleId; private Integer comment; private Integer collection; private Integer worthy; private Integer unworthy; private Integer soldOut; private Integer timeout; private Integer discoveryFlag; private Date updateTime; public CommodityTimeInfo() { } public CommodityTimeInfo(Integer id, Long articleId, Integer comment, Integer collection, Integer worthy, Integer unworthy, Integer soldOut, Integer timeout, Integer discoveryFlag, Date updateTime) { this.id = id; this.articleId = articleId; this.comment = comment; this.collection = collection; this.worthy = worthy; this.unworthy = unworthy; this.soldOut = soldOut; this.timeout = timeout; this.discoveryFlag = discoveryFlag; this.updateTime = updateTime; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Long getArticleId() { return articleId; } public void setArticleId(Long articleId) { this.articleId = articleId; } public Integer getComment() { return comment; } public void setComment(Integer comment) { this.comment = comment; } public Integer getCollection() { return collection; } public void setCollection(Integer collection) { this.collection = collection; } public Integer getWorthy() { return worthy; } public void setWorthy(Integer worthy) { this.worthy = worthy; } public Integer getUnworthy() { return unworthy; } public void setUnworthy(Integer unworthy) { this.unworthy = unworthy; } public Integer getSoldOut() { return soldOut; } public void setSoldOut(Integer soldOut) { this.soldOut = soldOut; } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public Integer getDiscoveryFlag() { return discoveryFlag; } public void setDiscoveryFlag(Integer discoveryFlag) { this.discoveryFlag = discoveryFlag; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "CommodityTimeInfo{" + "id=" + id + ", articleId=" + articleId + ", comment=" + comment + ", collection=" + collection + ", worthy=" + worthy + ", unworthy=" + unworthy + ", soldOut=" + soldOut + ", timeout=" + timeout + ", discoveryFlag=" + discoveryFlag + ", updateTime=" + updateTime + '}'; } }
UTF-8
Java
3,056
java
CommodityTimeInfo.java
Java
[]
null
[]
package com.smzdm.model; import java.util.Date; public class CommodityTimeInfo { private Integer id; private Long articleId; private Integer comment; private Integer collection; private Integer worthy; private Integer unworthy; private Integer soldOut; private Integer timeout; private Integer discoveryFlag; private Date updateTime; public CommodityTimeInfo() { } public CommodityTimeInfo(Integer id, Long articleId, Integer comment, Integer collection, Integer worthy, Integer unworthy, Integer soldOut, Integer timeout, Integer discoveryFlag, Date updateTime) { this.id = id; this.articleId = articleId; this.comment = comment; this.collection = collection; this.worthy = worthy; this.unworthy = unworthy; this.soldOut = soldOut; this.timeout = timeout; this.discoveryFlag = discoveryFlag; this.updateTime = updateTime; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Long getArticleId() { return articleId; } public void setArticleId(Long articleId) { this.articleId = articleId; } public Integer getComment() { return comment; } public void setComment(Integer comment) { this.comment = comment; } public Integer getCollection() { return collection; } public void setCollection(Integer collection) { this.collection = collection; } public Integer getWorthy() { return worthy; } public void setWorthy(Integer worthy) { this.worthy = worthy; } public Integer getUnworthy() { return unworthy; } public void setUnworthy(Integer unworthy) { this.unworthy = unworthy; } public Integer getSoldOut() { return soldOut; } public void setSoldOut(Integer soldOut) { this.soldOut = soldOut; } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public Integer getDiscoveryFlag() { return discoveryFlag; } public void setDiscoveryFlag(Integer discoveryFlag) { this.discoveryFlag = discoveryFlag; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "CommodityTimeInfo{" + "id=" + id + ", articleId=" + articleId + ", comment=" + comment + ", collection=" + collection + ", worthy=" + worthy + ", unworthy=" + unworthy + ", soldOut=" + soldOut + ", timeout=" + timeout + ", discoveryFlag=" + discoveryFlag + ", updateTime=" + updateTime + '}'; } }
3,056
0.588024
0.588024
139
20.992805
22.905655
203
false
false
0
0
0
0
0
0
0.438849
false
false
4
2818da8236c3eda4630f62a16a6654009f12bbaa
10,780,367,979,735
0387eb73a518f5cdc5be26f2cdae1ca88a32bac0
/schedule/src/main/java/com/y3school/schedule/serviceImpl/FinishServiceImpl.java
a2b94801a391811d2810e7c179e46ad96137ba8d
[]
no_license
NikitaY3/ScheduleService
https://github.com/NikitaY3/ScheduleService
8a3418b6905d8a4458f7e74dc1caa6f8c13ea1c5
0a1583891b1693fb78492d77678afb4ed035d50d
refs/heads/master
2020-07-16T15:59:22.174000
2019-09-02T09:17:07
2019-09-02T09:17:07
205,819,738
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.y3school.schedule.serviceImpl; import com.y3school.schedule.entity.FinishTable; import com.y3school.schedule.enums.ScheduleEnum; import com.y3school.schedule.exceptions.ScheduleException; import com.y3school.schedule.repository.FinishRepository; import com.y3school.schedule.service.FinishService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @Author TomShiDi * @Description * @Date 2019/8/17 **/ @Service @Transactional(rollbackFor = Exception.class) public class FinishServiceImpl implements FinishService { private FinishRepository repository; @Autowired public FinishServiceImpl(FinishRepository repository) { this.repository = repository; } @Override public FinishTable findByFinishId(String finishId) { FinishTable finishTable = repository.findByFinishId(finishId); if (finishTable == null) { throw new ScheduleException(ScheduleEnum.FINISH_INFO_NOT_FOUND); } return finishTable; } @Override public List<FinishTable> findByDayIdLike(String dayId) { return repository.findByDayIdLike("%" + dayId + "%"); } @Override public FinishTable insertFinishInfo(FinishTable finishTable) { return repository.save(finishTable); } @Override public FinishTable updateFinishInfo(FinishTable finishTable) { FinishTable finishTable1 = repository.findByFinishId(finishTable.getFinishId()); if (finishTable1 == null) { throw new ScheduleException(ScheduleEnum.FINISH_INFO_NOT_FOUND); } BeanUtils.copyProperties(finishTable, finishTable1, "createTime"); return repository.save(finishTable1); } @Override public void deleteByFinishId(String finishId) { repository.deleteById(finishId); } @Override public void deleteByDayIdLike(String dayId) { repository.deleteByDayIdLike("%" + dayId + "%"); } }
UTF-8
Java
2,135
java
FinishServiceImpl.java
Java
[ { "context": "sactional;\n\nimport java.util.List;\n\n/**\n * @Author TomShiDi\n * @Description\n * @Date 2019/8/17\n **/\n@Servi", "end": 575, "score": 0.5263112783432007, "start": 570, "tag": "USERNAME", "value": "TomSh" }, { "context": "nal;\n\nimport java.util.List;\n\n/**\n * @Author TomShiDi\n * @Description\n * @Date 2019/8/17\n **/\n@Service\n", "end": 578, "score": 0.6023832559585571, "start": 575, "tag": "NAME", "value": "iDi" } ]
null
[]
package com.y3school.schedule.serviceImpl; import com.y3school.schedule.entity.FinishTable; import com.y3school.schedule.enums.ScheduleEnum; import com.y3school.schedule.exceptions.ScheduleException; import com.y3school.schedule.repository.FinishRepository; import com.y3school.schedule.service.FinishService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @Author TomShiDi * @Description * @Date 2019/8/17 **/ @Service @Transactional(rollbackFor = Exception.class) public class FinishServiceImpl implements FinishService { private FinishRepository repository; @Autowired public FinishServiceImpl(FinishRepository repository) { this.repository = repository; } @Override public FinishTable findByFinishId(String finishId) { FinishTable finishTable = repository.findByFinishId(finishId); if (finishTable == null) { throw new ScheduleException(ScheduleEnum.FINISH_INFO_NOT_FOUND); } return finishTable; } @Override public List<FinishTable> findByDayIdLike(String dayId) { return repository.findByDayIdLike("%" + dayId + "%"); } @Override public FinishTable insertFinishInfo(FinishTable finishTable) { return repository.save(finishTable); } @Override public FinishTable updateFinishInfo(FinishTable finishTable) { FinishTable finishTable1 = repository.findByFinishId(finishTable.getFinishId()); if (finishTable1 == null) { throw new ScheduleException(ScheduleEnum.FINISH_INFO_NOT_FOUND); } BeanUtils.copyProperties(finishTable, finishTable1, "createTime"); return repository.save(finishTable1); } @Override public void deleteByFinishId(String finishId) { repository.deleteById(finishId); } @Override public void deleteByDayIdLike(String dayId) { repository.deleteByDayIdLike("%" + dayId + "%"); } }
2,135
0.727869
0.719906
69
29.942028
25.829926
88
false
false
0
0
0
0
0
0
0.376812
false
false
4
6c38362d16842bf305471774e2da77aa77520a9f
1,331,439,877,893
32b33e6f5e6749c294a7ff5ec88c85b3d7fd2907
/src/Advanced/Search/PathSum.java
989858d1f61142e4fd8cbd4eb071c0e5811081b1
[]
no_license
KevinWorkSpace/91-Algorithm2
https://github.com/KevinWorkSpace/91-Algorithm2
bd14ba8dc78417b48a4e0e554458380a20aa6969
d3302a22ea15634698b648e3ba4137b664258c79
refs/heads/master
2023-02-25T16:02:44.351000
2021-02-05T12:13:20
2021-02-05T12:13:20
308,846,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Advanced.Search; import java.util.ArrayList; import java.util.List; public class PathSum { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); if (root == null) return res; path.add(root.val); backTrace(res, path, root, root.val, targetSum); return res; } public void backTrace(List<List<Integer>> res, List<Integer> path, TreeNode node, int tmp, int targetSum) { if (targetSum == tmp && node.left == null && node.right == null) { res.add(new ArrayList<>(path)); } if (node == null) return; if (node.left != null) { path.add(node.left.val); tmp += node.left.val; backTrace(res, path, node.left, tmp, targetSum); path.remove(path.size() - 1); tmp -= node.left.val; } if (node.right != null) { path.add(node.right.val); tmp += node.right.val; backTrace(res, path, node.right, tmp, targetSum); path.remove(path.size() - 1); tmp -= node.right.val; } } public static void main(String[] args) { TreeNode n1 = new TreeNode(-2); TreeNode n2 = new TreeNode(-3); n1.right = n2; PathSum sum = new PathSum(); sum.pathSum(n1, -5); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
UTF-8
Java
1,706
java
PathSum.java
Java
[]
null
[]
package Advanced.Search; import java.util.ArrayList; import java.util.List; public class PathSum { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); if (root == null) return res; path.add(root.val); backTrace(res, path, root, root.val, targetSum); return res; } public void backTrace(List<List<Integer>> res, List<Integer> path, TreeNode node, int tmp, int targetSum) { if (targetSum == tmp && node.left == null && node.right == null) { res.add(new ArrayList<>(path)); } if (node == null) return; if (node.left != null) { path.add(node.left.val); tmp += node.left.val; backTrace(res, path, node.left, tmp, targetSum); path.remove(path.size() - 1); tmp -= node.left.val; } if (node.right != null) { path.add(node.right.val); tmp += node.right.val; backTrace(res, path, node.right, tmp, targetSum); path.remove(path.size() - 1); tmp -= node.right.val; } } public static void main(String[] args) { TreeNode n1 = new TreeNode(-2); TreeNode n2 = new TreeNode(-3); n1.right = n2; PathSum sum = new PathSum(); sum.pathSum(n1, -5); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
1,706
0.543962
0.538101
58
28.413794
21.688257
111
false
false
0
0
0
0
0
0
0.913793
false
false
4
253bd10a1b293a3fed07ce045fd0ace43bfb9b02
32,469,952,824,246
e5f06932730106c6f5b785315bfdea00075f7d89
/studio-idea-plugin/src/main/java/com/evolveum/midpoint/studio/lang/axiomquery/AxiomQueryLanguage.java
48a05e929212659f2cc26866a686ae10cdc43c9a
[ "Apache-2.0" ]
permissive
Evolveum/midpoint-studio
https://github.com/Evolveum/midpoint-studio
4377acc067bb6add1805378791623aca17e2059e
9fb8beb9adc2c87771a864aea4b4308cd5623371
refs/heads/master
2023-08-16T14:16:41.224000
2023-08-14T13:39:58
2023-08-14T13:39:58
208,789,988
4
2
Apache-2.0
false
2021-02-09T08:15:13
2019-09-16T12:06:54
2021-02-08T16:10:52
2021-02-08T16:10:49
1,115
0
1
0
Java
false
false
package com.evolveum.midpoint.studio.lang.axiomquery; import com.evolveum.midpoint.studio.MidPointIcons; import com.intellij.lang.Language; import javax.swing.*; /** * Created by Viliam Repan (lazyman). */ public class AxiomQueryLanguage extends Language { public static final AxiomQueryLanguage INSTANCE = new AxiomQueryLanguage(); public static final Icon ICON = MidPointIcons.Midpoint; private AxiomQueryLanguage() { super("Axiom Query"); } }
UTF-8
Java
478
java
AxiomQueryLanguage.java
Java
[ { "context": "anguage;\n\nimport javax.swing.*;\n\n/**\n * Created by Viliam Repan (lazyman).\n */\npublic class AxiomQueryLanguage ex", "end": 195, "score": 0.9998831748962402, "start": 183, "tag": "NAME", "value": "Viliam Repan" }, { "context": "t javax.swing.*;\n\n/**\n * Created by Viliam Repan (lazyman).\n */\npublic class AxiomQueryLanguage extends Lan", "end": 204, "score": 0.9995651245117188, "start": 197, "tag": "USERNAME", "value": "lazyman" } ]
null
[]
package com.evolveum.midpoint.studio.lang.axiomquery; import com.evolveum.midpoint.studio.MidPointIcons; import com.intellij.lang.Language; import javax.swing.*; /** * Created by <NAME> (lazyman). */ public class AxiomQueryLanguage extends Language { public static final AxiomQueryLanguage INSTANCE = new AxiomQueryLanguage(); public static final Icon ICON = MidPointIcons.Midpoint; private AxiomQueryLanguage() { super("Axiom Query"); } }
472
0.74477
0.74477
20
22.9
24.545671
79
false
false
0
0
0
0
0
0
0.35
false
false
4
20c3d3d1a4306f68a9e5bd70404b069ee479413e
7,842,610,293,241
fb18fd51cc9e065c042a96a9e907b181deca4f81
/.svn/pristine/20/20c3d3d1a4306f68a9e5bd70404b069ee479413e.svn-base
cd4e9bb6860050c058006b2662b13d0cf15b1125
[]
no_license
fanyajun186/InteallMEDHTML5
https://github.com/fanyajun186/InteallMEDHTML5
8fd76d850c4ae2998000e15d4a0b71edb1bba3f8
490e57eee561409c3ebe6c6e39b6f57aef53a26e
refs/heads/master
2022-11-08T10:01:16.014000
2020-06-15T07:00:51
2020-06-15T11:31:43
272,365,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.inteall.image.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.inteall.image.pojo.ReportTraceWithBLOBs; import com.inteall.image.service.ReportTraceService; import com.inteall.image.util.UUid; /** * @author 韩明君 * @date 创建时间:2018年2月7日 下午1:17:38 * @version 1.0 * @parameter */ @Controller @RequestMapping("/reporttrace") public class ReportTraceController { private static Logger log = Logger.getLogger(ReportTraceController.class.getName()); @Resource private ReportTraceService reportTraceService; /** * 根据报告明细的id查询报告明细信息 * @param id * @return */ @RequestMapping(value="/getById.do",method=RequestMethod.GET) @ResponseBody public Object getById(@RequestParam String id){ log.info("getById"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = reportTraceService.getById(id); map.put("reportTrace", reportTrace); return map; } /** * 根据报告明细的id查询报告明细信息 * @param id * @return */ @RequestMapping(value="/getAll.do",method=RequestMethod.GET) @ResponseBody public Object getAll(HttpServletRequest request,Model model){ log.info("getAll"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); List<ReportTraceWithBLOBs> reportTraceList = reportTraceService.getAll(reportTrace); map.put("报告明细数量", reportTraceList.size()); map.put("reportTraceList", reportTraceList); return map; } /** * 根据报告明细id删除报告明细 * @param id * @return */ @RequestMapping(value="/delById.do",method=RequestMethod.GET) @ResponseBody public Object delById(@RequestParam String id){ log.info("delById"); Map<String,Object> map = new HashMap<String,Object>(); int row = reportTraceService.delById(id); map.put("删除了的行数:", row); return map; } /** * 新增报告明细信息 * @param request * @param model * @return */ @RequestMapping(value="/save.do",method=RequestMethod.GET) @ResponseBody public Object save(HttpServletRequest request,Model model){ log.info("save"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); // reportTrace.setCheckView("食道钡剂下流通畅、未见充盈缺损、未见病理性狭窄及粘膜破坏。胃形态呈:鱼钩型。胃张力:中等。 胃角切迹在髂嵴:上。胃内潴留液:少量。 胃轮廓:正常。胃粘膜纹:正常。 胃动力:正常。胃蠕动:正常。 胃排空:正常。十二指肠球部:正常。十二指肠框部:正常。小肠运动增强,0.5小时结肠显影。"); // reportTrace.setDiagnosisResult("小肠运动亢进,请结合临床。"); // reportTrace.setUserId("1"); // reportTrace.setUserName("hmj"); // reportTrace.setIsDel("0"); // reportTrace.setReportTraceKey(UUid.getUUID()); // reportTrace.setCreatePerson("hmj"); // reportTrace.setCreateTime(new Date()); // // // int row = reportTraceService.save(reportTrace); // // map.put("新增的行数", row); // map.put("保存的信息", reportTrace); return map; } /** * 根据报告明细id修改报告明细信息 * @param id * @param request * @param model * @return */ @RequestMapping(value="/updateById.do",method=RequestMethod.GET) @ResponseBody public Object updateById(@RequestParam String id,HttpServletRequest request,Model model){ log.info("updateById"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); int row = reportTraceService.updateById(reportTrace); map.put("修改的行数", row); map.put("修改的信息", reportTrace); return map; } }
UTF-8
Java
4,522
20c3d3d1a4306f68a9e5bd70404b069ee479413e.svn-base
Java
[ { "context": "com.inteall.image.util.UUid;\r\n\r\n\r\n/** \r\n* @author 韩明君 \r\n* @date 创建时间:2018年2月7日 下午1:17:38 \r\n* @version ", "end": 767, "score": 0.9997979998588562, "start": 764, "tag": "NAME", "value": "韩明君" }, { "context": "ace.setUserId(\"1\");\r\n//\t\treportTrace.setUserName(\"hmj\");\r\n//\t\treportTrace.setIsDel(\"0\");\r\n//\t\treportTra", "end": 3102, "score": 0.9992736577987671, "start": 3099, "tag": "USERNAME", "value": "hmj" }, { "context": "setIsDel(\"0\");\r\n//\t\treportTrace.setReportTraceKey(UUid.getUUID());\r\n//\t\treportTrace.setCreatePerson(\"hmj\");\r\n//\t", "end": 3185, "score": 0.8419148325920105, "start": 3173, "tag": "KEY", "value": "UUid.getUUID" } ]
null
[]
package com.inteall.image.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.inteall.image.pojo.ReportTraceWithBLOBs; import com.inteall.image.service.ReportTraceService; import com.inteall.image.util.UUid; /** * @author 韩明君 * @date 创建时间:2018年2月7日 下午1:17:38 * @version 1.0 * @parameter */ @Controller @RequestMapping("/reporttrace") public class ReportTraceController { private static Logger log = Logger.getLogger(ReportTraceController.class.getName()); @Resource private ReportTraceService reportTraceService; /** * 根据报告明细的id查询报告明细信息 * @param id * @return */ @RequestMapping(value="/getById.do",method=RequestMethod.GET) @ResponseBody public Object getById(@RequestParam String id){ log.info("getById"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = reportTraceService.getById(id); map.put("reportTrace", reportTrace); return map; } /** * 根据报告明细的id查询报告明细信息 * @param id * @return */ @RequestMapping(value="/getAll.do",method=RequestMethod.GET) @ResponseBody public Object getAll(HttpServletRequest request,Model model){ log.info("getAll"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); List<ReportTraceWithBLOBs> reportTraceList = reportTraceService.getAll(reportTrace); map.put("报告明细数量", reportTraceList.size()); map.put("reportTraceList", reportTraceList); return map; } /** * 根据报告明细id删除报告明细 * @param id * @return */ @RequestMapping(value="/delById.do",method=RequestMethod.GET) @ResponseBody public Object delById(@RequestParam String id){ log.info("delById"); Map<String,Object> map = new HashMap<String,Object>(); int row = reportTraceService.delById(id); map.put("删除了的行数:", row); return map; } /** * 新增报告明细信息 * @param request * @param model * @return */ @RequestMapping(value="/save.do",method=RequestMethod.GET) @ResponseBody public Object save(HttpServletRequest request,Model model){ log.info("save"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); // reportTrace.setCheckView("食道钡剂下流通畅、未见充盈缺损、未见病理性狭窄及粘膜破坏。胃形态呈:鱼钩型。胃张力:中等。 胃角切迹在髂嵴:上。胃内潴留液:少量。 胃轮廓:正常。胃粘膜纹:正常。 胃动力:正常。胃蠕动:正常。 胃排空:正常。十二指肠球部:正常。十二指肠框部:正常。小肠运动增强,0.5小时结肠显影。"); // reportTrace.setDiagnosisResult("小肠运动亢进,请结合临床。"); // reportTrace.setUserId("1"); // reportTrace.setUserName("hmj"); // reportTrace.setIsDel("0"); // reportTrace.setReportTraceKey(<KEY>()); // reportTrace.setCreatePerson("hmj"); // reportTrace.setCreateTime(new Date()); // // // int row = reportTraceService.save(reportTrace); // // map.put("新增的行数", row); // map.put("保存的信息", reportTrace); return map; } /** * 根据报告明细id修改报告明细信息 * @param id * @param request * @param model * @return */ @RequestMapping(value="/updateById.do",method=RequestMethod.GET) @ResponseBody public Object updateById(@RequestParam String id,HttpServletRequest request,Model model){ log.info("updateById"); Map<String,Object> map = new HashMap<String,Object>(); ReportTraceWithBLOBs reportTrace = new ReportTraceWithBLOBs(); int row = reportTraceService.updateById(reportTrace); map.put("修改的行数", row); map.put("修改的信息", reportTrace); return map; } }
4,515
0.707585
0.703094
139
26.848921
26.688158
191
false
false
0
0
0
0
0
0
1.733813
false
false
4
eae319fad52ee8ce390e2b98bcf28e1743d38ba1
12,506,944,774,363
06dc0beb644d88f93b962e3606f2e8e94896388c
/java/BBLibJFX/src/com/borisborgobello/jfx/utils/BBPDF.java
430033763a108095e82e352bbcc4b669de51f702
[ "MIT" ]
permissive
borisborgobello/bblib-open-source-utils
https://github.com/borisborgobello/bblib-open-source-utils
9bd8865703ff485139181698bdb65a0ff7bfa6ea
cee64a0010aea4491dbcd43929c5fddd4626e673
refs/heads/master
2022-02-22T10:05:34.343000
2019-06-28T23:49:27
2019-06-28T23:49:27
232,924,464
0
0
MIT
false
2022-02-01T01:00:33
2020-01-09T23:14:10
2020-01-09T23:15:03
2022-02-01T01:00:31
38,545
0
0
2
Java
false
false
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.borisborgobello.jfx.utils; import com.borisborgobello.jfx.io.BBFileInout; import com.borisborgobello.jfx.ui.controllers.BBSuperController; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; /** * * @author borisborgobello */ public class BBPDF { private static final String PASSWORD = "-password"; private static final String START_PAGE = "-startPage"; private static final String END_PAGE = "-endPage"; private static final String END_PAGE_FROM_LAST = "-endPageFromLast"; private static final String PAGE = "-page"; private static final String IMAGE_TYPE = "-imageType"; private static final String FORMAT = "-format"; private static final String OUTPUT_PREFIX = "-outputPrefix"; private static final String PREFIX = "-prefix"; private static final String COLOR = "-color"; private static final String RESOLUTION = "-resolution"; private static final String DPI = "-dpi"; private static final String CROPBOX = "-cropbox"; private static final String TIME = "-time"; /** * private constructor. */ private BBPDF() { //static class } /** * Infamous main method. * * @param args Command line arguments, should be one and a reference to a file. * * @throws IOException If there is an error parsing the document. */ public static ArrayList<String> main(BBSuperController c, String... args ) throws IOException { // suppress the Dock icon on OS X //System.setProperty("apple.awt.UIElement", "true"); String password = ""; String pdfFile = null; String outputPrefix = null; String imageFormat = "jpg"; int startPage = 1; int endPage = Integer.MAX_VALUE; int endPageFromLastPage = Integer.MAX_VALUE; String color = "rgb"; int dpi; float cropBoxLowerLeftX = 0; float cropBoxLowerLeftY = 0; float cropBoxUpperRightX = 0; float cropBoxUpperRightY = 0; boolean showTime = false; try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); } catch( HeadlessException e ) { dpi = 96; } for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else if( args[i].equals( START_PAGE ) ) { i++; if( i >= args.length ) { usage(); } startPage = Integer.parseInt( args[i] ); } else if( args[i].equals( END_PAGE ) ) { i++; if( i >= args.length ) { usage(); } endPage = Integer.parseInt( args[i] ); } else if( args[i].equals( END_PAGE_FROM_LAST ) ) { i++; if( i >= args.length ) { usage(); } endPageFromLastPage = Integer.parseInt( args[i] ); } else if( args[i].equals( PAGE ) ) { i++; if( i >= args.length ) { usage(); } startPage = Integer.parseInt( args[i] ); endPage = Integer.parseInt( args[i] ); } else if( args[i].equals(IMAGE_TYPE) || args[i].equals(FORMAT) ) { i++; imageFormat = args[i]; } else if( args[i].equals( OUTPUT_PREFIX ) || args[i].equals( PREFIX ) ) { i++; outputPrefix = args[i]; } else if( args[i].equals( COLOR ) ) { i++; color = args[i]; } else if( args[i].equals( RESOLUTION ) || args[i].equals( DPI ) ) { i++; dpi = Integer.parseInt(args[i]); } else if( args[i].equals( CROPBOX ) ) { i++; cropBoxLowerLeftX = Float.valueOf(args[i]); i++; cropBoxLowerLeftY = Float.valueOf(args[i]); i++; cropBoxUpperRightX = Float.valueOf(args[i]); i++; cropBoxUpperRightY = Float.valueOf(args[i]); } else if( args[i].equals( TIME ) ) { showTime = true; } else { if( pdfFile == null ) { pdfFile = args[i]; } } } if( pdfFile == null ) { usage(); } else { if(outputPrefix == null) { outputPrefix = pdfFile.substring( 0, pdfFile.lastIndexOf( '.' )); } PDDocument document = null; try { document = PDDocument.load(new File(pdfFile), password); ImageType imageType = null; if ("bilevel".equalsIgnoreCase(color)) { imageType = ImageType.BINARY; } else if ("gray".equalsIgnoreCase(color)) { imageType = ImageType.GRAY; } else if ("rgb".equalsIgnoreCase(color)) { imageType = ImageType.RGB; } else if ("rgba".equalsIgnoreCase(color)) { imageType = ImageType.ARGB; } if (imageType == null) { throw new RuntimeException("Error: Invalid color." ); } //if a CropBox has been specified, update the CropBox: //changeCropBoxes(PDDocument document,float a, float b, float c,float d) if ( cropBoxLowerLeftX!=0 || cropBoxLowerLeftY!=0 || cropBoxUpperRightX!=0 || cropBoxUpperRightY!=0 ) { changeCropBox(document, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX, cropBoxUpperRightY); } long startTime = System.nanoTime(); ArrayList<String> files = new ArrayList<>(); // render the pages boolean success = true; if (endPageFromLastPage != Integer.MAX_VALUE) { endPage = document.getNumberOfPages()-endPageFromLastPage; } endPage = Math.min(endPage, document.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(document); for (int i = startPage - 1; i < endPage; i++) { BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType); String fileName = outputPrefix + (i + 1) + "." + imageFormat; success &= ImageIOUtil.writeImage(image, fileName, dpi); files.add(fileName); } // performance stats long endTime = System.nanoTime(); long duration = endTime - startTime; int count = 1 + endPage - startPage; if (showTime) { System.err.printf("Rendered %d page%s in %dms\n", count, count == 1 ? "" : "s", duration / 1000000); } if (!success) { throw new RuntimeException( "Error: no writer found for image format '" + imageFormat + "'" ); } return files; } finally { if( document != null ) { document.close(); } } } return null; } /** * This will print the usage requirements and exit. */ private static void usage() { String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFToImage [options] <inputfile>\n" + "\nOptions:\n" + " -password <password> : Password to decrypt document\n" + " -format <string> : Image format: " + getImageFormats() + "\n" + " -prefix <string> : Filename prefix for image files\n" + " -page <number> : The only page to extract (1-based)\n" + " -startPage <int> : The first page to start extraction (1-based)\n" + " -endPage <int> : The last page to extract(inclusive)\n" + " -color <int> : The color depth (valid: bilevel, gray, rgb, rgba)\n" + " -dpi <int> : The DPI of the output image\n" + " -cropbox <int> <int> <int> <int> : The page area to export\n" + " -time : Prints timing information to stdout\n" + " <inputfile> : The PDF document to use\n"; System.out.println(message); throw new RuntimeException("Wrong PDF to images params"); } private static String getImageFormats() { StringBuilder retval = new StringBuilder(); String[] formats = ImageIO.getReaderFormatNames(); for( int i = 0; i < formats.length; i++ ) { if (formats[i].equalsIgnoreCase(formats[i])) { retval.append( formats[i] ); if( i + 1 < formats.length ) { retval.append( ", " ); } } } return retval.toString(); } private static void changeCropBox(PDDocument document, float a, float b, float c, float d) { for (PDPage page : document.getPages()) { System.out.println("resizing page"); PDRectangle rectangle = new PDRectangle(); rectangle.setLowerLeftX(a); rectangle.setLowerLeftY(b); rectangle.setUpperRightX(c); rectangle.setUpperRightY(d); page.setCropBox(rectangle); } } public static void generatePDF(BBSuperController c, File dir, ArrayList<File> files) { generatePDF(c, dir, files, true); } public static void generatePDF(BBSuperController c, File dir, ArrayList<File> files, boolean sort) { // Export PDF if (sort) { files.sort((File o1, File o2) -> BBFileInout.extractFilename(o1.getAbsolutePath(), false).compareToIgnoreCase(BBFileInout.extractFilename(o2.getAbsolutePath(), false))); } File fPdf = new File(dir, "out.pdf"); PDDocument document = new PDDocument(); //int pageNb = 0; try { for (File f : files) { //WritableImage p = ISUIHelper.getImageFromNode(bpl.load()); //bpl.unload(); BufferedImage a1 = ImageIO.read(f); //p = null; //a1 = Scalr.resize(a1, Scalr.Method.QUALITY, Scalr.Mode.BEST_FIT_BOTH, finalWidth, finalHeight); //String extension = bpl.preferJpg ? "jpg" : "png"; //File pageFile = new File(dir, String.format("%s_%d.%s", fp.prodcode.getAsS(), ++pageNb, extension)); //ImageIO.write(bpl.preferJpg ? ISImg.toRGBForJpgSafe(a1) : a1, extension, pageFile); int finalWidth = a1.getWidth(); int finalHeight = a1.getHeight(); a1.flush(); a1 = null; PDPage page = new PDPage(new PDRectangle(finalWidth, finalHeight)); PDImageXObject pdImage = PDImageXObject.createFromFileByContent(f, document); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { contentStream.drawImage(pdImage, 0, 0); } document.addPage(page); } document.save(fPdf); document.close(); } catch (IOException ex) { c.criticalError(ex); } } }
UTF-8
Java
13,561
java
BBPDF.java
Java
[ { "context": "fbox.tools.imageio.ImageIOUtil;\n\n/**\n *\n * @author borisborgobello\n */\npublic class BBPDF {\n \n private static ", "end": 978, "score": 0.9979910254478455, "start": 963, "tag": "USERNAME", "value": "borisborgobello" }, { "context": " {\n \n private static final String PASSWORD = \"-password\";\n private static final String START_PAGE = \"-", "end": 1062, "score": 0.9359573125839233, "start": 1052, "tag": "PASSWORD", "value": "\"-password" }, { "context": " + \"\\nOptions:\\n\"\n + \" -password <password> : Password to decrypt document\\n\"\n ", "end": 9447, "score": 0.9321946501731873, "start": 9439, "tag": "PASSWORD", "value": "password" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.borisborgobello.jfx.utils; import com.borisborgobello.jfx.io.BBFileInout; import com.borisborgobello.jfx.ui.controllers.BBSuperController; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; /** * * @author borisborgobello */ public class BBPDF { private static final String PASSWORD = <PASSWORD>"; private static final String START_PAGE = "-startPage"; private static final String END_PAGE = "-endPage"; private static final String END_PAGE_FROM_LAST = "-endPageFromLast"; private static final String PAGE = "-page"; private static final String IMAGE_TYPE = "-imageType"; private static final String FORMAT = "-format"; private static final String OUTPUT_PREFIX = "-outputPrefix"; private static final String PREFIX = "-prefix"; private static final String COLOR = "-color"; private static final String RESOLUTION = "-resolution"; private static final String DPI = "-dpi"; private static final String CROPBOX = "-cropbox"; private static final String TIME = "-time"; /** * private constructor. */ private BBPDF() { //static class } /** * Infamous main method. * * @param args Command line arguments, should be one and a reference to a file. * * @throws IOException If there is an error parsing the document. */ public static ArrayList<String> main(BBSuperController c, String... args ) throws IOException { // suppress the Dock icon on OS X //System.setProperty("apple.awt.UIElement", "true"); String password = ""; String pdfFile = null; String outputPrefix = null; String imageFormat = "jpg"; int startPage = 1; int endPage = Integer.MAX_VALUE; int endPageFromLastPage = Integer.MAX_VALUE; String color = "rgb"; int dpi; float cropBoxLowerLeftX = 0; float cropBoxLowerLeftY = 0; float cropBoxUpperRightX = 0; float cropBoxUpperRightY = 0; boolean showTime = false; try { dpi = Toolkit.getDefaultToolkit().getScreenResolution(); } catch( HeadlessException e ) { dpi = 96; } for( int i = 0; i < args.length; i++ ) { if( args[i].equals( PASSWORD ) ) { i++; if( i >= args.length ) { usage(); } password = args[i]; } else if( args[i].equals( START_PAGE ) ) { i++; if( i >= args.length ) { usage(); } startPage = Integer.parseInt( args[i] ); } else if( args[i].equals( END_PAGE ) ) { i++; if( i >= args.length ) { usage(); } endPage = Integer.parseInt( args[i] ); } else if( args[i].equals( END_PAGE_FROM_LAST ) ) { i++; if( i >= args.length ) { usage(); } endPageFromLastPage = Integer.parseInt( args[i] ); } else if( args[i].equals( PAGE ) ) { i++; if( i >= args.length ) { usage(); } startPage = Integer.parseInt( args[i] ); endPage = Integer.parseInt( args[i] ); } else if( args[i].equals(IMAGE_TYPE) || args[i].equals(FORMAT) ) { i++; imageFormat = args[i]; } else if( args[i].equals( OUTPUT_PREFIX ) || args[i].equals( PREFIX ) ) { i++; outputPrefix = args[i]; } else if( args[i].equals( COLOR ) ) { i++; color = args[i]; } else if( args[i].equals( RESOLUTION ) || args[i].equals( DPI ) ) { i++; dpi = Integer.parseInt(args[i]); } else if( args[i].equals( CROPBOX ) ) { i++; cropBoxLowerLeftX = Float.valueOf(args[i]); i++; cropBoxLowerLeftY = Float.valueOf(args[i]); i++; cropBoxUpperRightX = Float.valueOf(args[i]); i++; cropBoxUpperRightY = Float.valueOf(args[i]); } else if( args[i].equals( TIME ) ) { showTime = true; } else { if( pdfFile == null ) { pdfFile = args[i]; } } } if( pdfFile == null ) { usage(); } else { if(outputPrefix == null) { outputPrefix = pdfFile.substring( 0, pdfFile.lastIndexOf( '.' )); } PDDocument document = null; try { document = PDDocument.load(new File(pdfFile), password); ImageType imageType = null; if ("bilevel".equalsIgnoreCase(color)) { imageType = ImageType.BINARY; } else if ("gray".equalsIgnoreCase(color)) { imageType = ImageType.GRAY; } else if ("rgb".equalsIgnoreCase(color)) { imageType = ImageType.RGB; } else if ("rgba".equalsIgnoreCase(color)) { imageType = ImageType.ARGB; } if (imageType == null) { throw new RuntimeException("Error: Invalid color." ); } //if a CropBox has been specified, update the CropBox: //changeCropBoxes(PDDocument document,float a, float b, float c,float d) if ( cropBoxLowerLeftX!=0 || cropBoxLowerLeftY!=0 || cropBoxUpperRightX!=0 || cropBoxUpperRightY!=0 ) { changeCropBox(document, cropBoxLowerLeftX, cropBoxLowerLeftY, cropBoxUpperRightX, cropBoxUpperRightY); } long startTime = System.nanoTime(); ArrayList<String> files = new ArrayList<>(); // render the pages boolean success = true; if (endPageFromLastPage != Integer.MAX_VALUE) { endPage = document.getNumberOfPages()-endPageFromLastPage; } endPage = Math.min(endPage, document.getNumberOfPages()); PDFRenderer renderer = new PDFRenderer(document); for (int i = startPage - 1; i < endPage; i++) { BufferedImage image = renderer.renderImageWithDPI(i, dpi, imageType); String fileName = outputPrefix + (i + 1) + "." + imageFormat; success &= ImageIOUtil.writeImage(image, fileName, dpi); files.add(fileName); } // performance stats long endTime = System.nanoTime(); long duration = endTime - startTime; int count = 1 + endPage - startPage; if (showTime) { System.err.printf("Rendered %d page%s in %dms\n", count, count == 1 ? "" : "s", duration / 1000000); } if (!success) { throw new RuntimeException( "Error: no writer found for image format '" + imageFormat + "'" ); } return files; } finally { if( document != null ) { document.close(); } } } return null; } /** * This will print the usage requirements and exit. */ private static void usage() { String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFToImage [options] <inputfile>\n" + "\nOptions:\n" + " -password <<PASSWORD>> : Password to decrypt document\n" + " -format <string> : Image format: " + getImageFormats() + "\n" + " -prefix <string> : Filename prefix for image files\n" + " -page <number> : The only page to extract (1-based)\n" + " -startPage <int> : The first page to start extraction (1-based)\n" + " -endPage <int> : The last page to extract(inclusive)\n" + " -color <int> : The color depth (valid: bilevel, gray, rgb, rgba)\n" + " -dpi <int> : The DPI of the output image\n" + " -cropbox <int> <int> <int> <int> : The page area to export\n" + " -time : Prints timing information to stdout\n" + " <inputfile> : The PDF document to use\n"; System.out.println(message); throw new RuntimeException("Wrong PDF to images params"); } private static String getImageFormats() { StringBuilder retval = new StringBuilder(); String[] formats = ImageIO.getReaderFormatNames(); for( int i = 0; i < formats.length; i++ ) { if (formats[i].equalsIgnoreCase(formats[i])) { retval.append( formats[i] ); if( i + 1 < formats.length ) { retval.append( ", " ); } } } return retval.toString(); } private static void changeCropBox(PDDocument document, float a, float b, float c, float d) { for (PDPage page : document.getPages()) { System.out.println("resizing page"); PDRectangle rectangle = new PDRectangle(); rectangle.setLowerLeftX(a); rectangle.setLowerLeftY(b); rectangle.setUpperRightX(c); rectangle.setUpperRightY(d); page.setCropBox(rectangle); } } public static void generatePDF(BBSuperController c, File dir, ArrayList<File> files) { generatePDF(c, dir, files, true); } public static void generatePDF(BBSuperController c, File dir, ArrayList<File> files, boolean sort) { // Export PDF if (sort) { files.sort((File o1, File o2) -> BBFileInout.extractFilename(o1.getAbsolutePath(), false).compareToIgnoreCase(BBFileInout.extractFilename(o2.getAbsolutePath(), false))); } File fPdf = new File(dir, "out.pdf"); PDDocument document = new PDDocument(); //int pageNb = 0; try { for (File f : files) { //WritableImage p = ISUIHelper.getImageFromNode(bpl.load()); //bpl.unload(); BufferedImage a1 = ImageIO.read(f); //p = null; //a1 = Scalr.resize(a1, Scalr.Method.QUALITY, Scalr.Mode.BEST_FIT_BOTH, finalWidth, finalHeight); //String extension = bpl.preferJpg ? "jpg" : "png"; //File pageFile = new File(dir, String.format("%s_%d.%s", fp.prodcode.getAsS(), ++pageNb, extension)); //ImageIO.write(bpl.preferJpg ? ISImg.toRGBForJpgSafe(a1) : a1, extension, pageFile); int finalWidth = a1.getWidth(); int finalHeight = a1.getHeight(); a1.flush(); a1 = null; PDPage page = new PDPage(new PDRectangle(finalWidth, finalHeight)); PDImageXObject pdImage = PDImageXObject.createFromFileByContent(f, document); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { contentStream.drawImage(pdImage, 0, 0); } document.addPage(page); } document.save(fPdf); document.close(); } catch (IOException ex) { c.criticalError(ex); } } }
13,563
0.485141
0.481897
379
34.781002
26.887964
181
false
false
0
0
0
0
0
0
0.604222
false
false
4
8d4b225e0d1298a9165a4f851ec40a41eee575c8
747,324,313,232
4e5ba241f940511f8debe4ccaee0c6a91a248246
/rexster-server/src/test/java/com/tinkerpop/rexster/VertexResourceTest.java
2ed904dd21e032f547f3df29e2078124fe69118b
[ "BSD-3-Clause" ]
permissive
ibrahimcesar/rexster
https://github.com/ibrahimcesar/rexster
985e4fa47dec702a10777b2698b82ab20a7ca757
4353ca99c0de475eac8efdf11e48908616619b37
refs/heads/master
2020-02-24T17:41:32.704000
2012-08-17T10:38:14
2012-08-17T10:38:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tinkerpop.rexster; import com.tinkerpop.rexster.server.RexsterApplication; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.commons.configuration.XMLConfiguration; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Variant; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Set; /** * Tests vertex resource. Should not need to test any specific returns values as they are * covered under other unit tests. The format of the results themselves should be covered * under the ElementJSONObject. */ public class VertexResourceTest { protected Mockery mockery = new JUnit4Mockery(); protected final String baseUri = "http://localhost/mock"; protected final URI requestUriPath = URI.create("http://localhost/graphs/mock/vertices"); @Before public void init() { this.mockery = new JUnit4Mockery(); } @Test public void getVerticesAll() { final int numberOfVertices = 100; VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(numberOfVertices, numberOfVertices, response); } @Test public void getVerticesKeyIndexed() { KeyIndexableGraph graph = TinkerGraphFactory.createTinkerGraph(); graph.createKeyIndex("name", Vertex.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.KEY, "name"); parameters.put(Tokens.VALUE, "marko"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); assertVerticesOkResponseJsonStructure(1, 1, resource.getVertices("graph")); } @Test public void getVerticesNoResults() { final int numberOfVertices = 0; VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(numberOfVertices, numberOfVertices, response); } @Test public void getVerticesWithValidOffset() { final int numberOfVertices = 100; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(10, numberOfVertices, response); JSONObject json = (JSONObject) response.getEntity(); JSONArray jsonResults = json.optJSONArray(Tokens.RESULTS); // should return ids 10 through 19 from the random generated data for (int ix = 0; ix < jsonResults.length(); ix++) { Assert.assertEquals(ix + 10, jsonResults.optJSONObject(ix).optInt(Tokens._ID)); } } @Test public void getVerticesWithInvalidOffsetNotEnoughResults() { final int numberOfVertices = 5; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(0, numberOfVertices, response); } @Test public void getVerticesWithInvalidOffsetStartAfterEnd() { final int numberOfVertices = 5; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "100"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(0, numberOfVertices, response); } @Test(expected = WebApplicationException.class) public void getSingleVertexNotFound() { VertexResource resource = this.constructMockGetSingleVertexScenario(null, new HashMap<String, String>()); resource.getSingleVertex("graph", "id-does-not-match-any"); } @Test public void getSingleVertexFound() { Vertex v = new MockVertex("1"); VertexResource resource = this.constructMockGetSingleVertexScenario(v, new HashMap<String, String>()); Response response = resource.getSingleVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONObject jsonResult = (JSONObject) json.optJSONObject(Tokens.RESULTS); Assert.assertNotNull(jsonResult); } @Test(expected = WebApplicationException.class) public void getVertexEdgesNotFound() { VertexResource resource = this.constructMockGetSingleVertexScenario(null, new HashMap<String, String>()); resource.getSingleVertex("graph", "id-does-not-match-any"); } @Test public void getVertexEdgesFoundVertexReturnInEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.IN_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("1-2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnOutEdgesNoOffsetWithLabel() { HashMap<String, String> map = new HashMap<String, String>() {{ put(Tokens._LABEL, "label31"); }}; VertexResource resource = this.constructMockSimpleGraphScenario(map); Response response = resource.getVertexEdges("graph", "3", Tokens.OUT_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3-1", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnInVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.IN); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnInVerticesNoOffsetWithLabel() { HashMap<String, String> map = new HashMap<String, String>() {{ put(Tokens._LABEL, "label12"); }}; VertexResource resource = this.constructMockSimpleGraphScenario(map); Response response = resource.getVertexEdges("graph", "1", Tokens.IN); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexOutEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.OUT_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3-1", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexOutVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.OUT); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexBothEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 2); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(2, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH); JSONObject json = assertEdgesOkResponseJsonStructure(response, 2); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(2, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithValidOffset() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(100, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 100); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(10, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithOffsetNotEnoughResults() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(5, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 5); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(0, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithOffsetStartAfterEnd() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "30"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(100, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 100); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(0, jsonResultArray.length()); } @Test public void postNullVertexOnUriAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexRexsterConsumesJsonAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexOnUriAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexRexsterConsumesJsonAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexOnUriAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, true, true); } @Test public void postNullVertexRexsterConsumesJsonAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, true); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, true); } @Test(expected = WebApplicationException.class) public void postVertexOnUriButHasElementProperties() { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens._ID, "300"); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.postVertexOnUri(jsr311Request, "graph", "1"); } @Test public void putVertexConsumesUriValid() { final HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("some-property", "300a"); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); v.setProperty("property-to-remove", "bye"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.putVertexConsumesUri(jsr311Request, "graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); Assert.assertEquals("300a", v.getProperty("some-property")); Assert.assertFalse(v.getPropertyKeys().contains("property-to-remove")); } @Test(expected = WebApplicationException.class) public void putVertexConsumesUriNoVertexFound() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(null)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.putVertexConsumesUri(jsr311Request, "graph", "1"); } @Test public void deleteVertexValid() { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(new HashMap<String, String>())); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(graph).removeVertex(v); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.deleteVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); } @Test(expected = WebApplicationException.class) public void deleteVertexNoVertexFound() { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(new HashMap<String, String>())); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(null)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.deleteVertex("graph", "1"); } @Test public void deleteVertexPropertiesValid() { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("some-property", ""); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); v.setProperty("some-property", "to-delete"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.deleteVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Set<String> keys = v.getPropertyKeys(); Assert.assertEquals(0, keys.size()); } private static void initializeExtensionConfigurations(RexsterApplicationGraph rag) { String xmlString = "<extension><namespace>tp</namespace><name>extensionname</name><configuration><test>1</test></configuration></extension>"; XMLConfiguration xmlConfig = new XMLConfiguration(); try { xmlConfig.load(new StringReader(xmlString)); } catch (ConfigurationException ex) { Assert.fail(ex.getMessage()); } List<HierarchicalConfiguration> list = new ArrayList<HierarchicalConfiguration>(); list.add(xmlConfig); List allowables = new ArrayList(); allowables.add("tp:*"); rag.loadAllowableExtensions(allowables); rag.loadExtensionsConfigurations(list); } private static HashMap<String, Object> generateVertexParametersToPost(boolean rexsterTyped) { final HashMap<String, Object> parameters = new HashMap<String, Object>(); if (rexsterTyped) { parameters.put("some-property", "(s,300a)"); parameters.put("int-property", "(i,300)"); } else { parameters.put("some-property", "300a"); parameters.put("int-property", 300); } return parameters; } private static void assertPostVertexProducesJson(Response response, boolean hasHypermedia, boolean hasTypes) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONObject postedVertex = json.optJSONObject(Tokens.RESULTS); if (hasTypes) { JSONObject somePropertyJson = postedVertex.optJSONObject("some-property"); Assert.assertEquals("string", somePropertyJson.optString("type")); Assert.assertEquals("300a", somePropertyJson.optString("value")); JSONObject intPropertyJson = postedVertex.optJSONObject("int-property"); Assert.assertEquals("integer", intPropertyJson.optString("type")); Assert.assertEquals(300, intPropertyJson.optInt("value")); } else { Assert.assertEquals("300a", postedVertex.optString("some-property")); Assert.assertEquals(300, postedVertex.optInt("int-property")); } if (hasHypermedia) { Assert.assertTrue(json.has(Tokens.EXTENSIONS)); } } private JSONObject assertEdgesOkResponseJsonStructure(Response response, int expectedTotalSize) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.TOTAL_SIZE)); Assert.assertEquals(expectedTotalSize, json.optInt(Tokens.TOTAL_SIZE)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); return json; } private VertexResource constructMockMultiEdgedGraphScenario(int numberOfEdgesToGenerate, HashMap<String, String> parameters) { MockVertex v1 = new MockVertex("1"); MockVertex v2 = new MockVertex("2"); ArrayList<Edge> v1InEdges = new ArrayList<Edge>(); ArrayList<Edge> v2OutEdges = new ArrayList<Edge>(); for (int ix = 0; ix < numberOfEdgesToGenerate; ix++) { MockEdge edge = new MockEdge(new Integer(ix).toString(), "label" + new Integer(ix).toString(), new Hashtable<String, Object>(), v1, v2); v1InEdges.add(edge); v2OutEdges.add(edge); } v1.setInEdges(v1InEdges); v2.setOutEdges(v2OutEdges); VertexResource resource = this.constructMockGetSingleVertexScenario(v1, parameters); return resource; } private VertexResource constructMockSimpleGraphScenario() { return constructMockSimpleGraphScenario(new HashMap<String, String>()); } /** * Creates a simple graph with two vertices and an edge between them. * * @return */ private VertexResource constructMockSimpleGraphScenario(HashMap parameters) { MockVertex v1 = new MockVertex("1"); MockVertex v2 = new MockVertex("2"); MockVertex v3 = new MockVertex("3"); MockEdge edge1 = new MockEdge("1-2", "label12", new Hashtable<String, Object>(), v1, v2); MockEdge edge2 = new MockEdge("3-1", "label31", new Hashtable<String, Object>(), v3, v1); ArrayList<Edge> v1InEdges = new ArrayList<Edge>(); v1InEdges.add(edge1); ArrayList<Edge> v3InEdges = new ArrayList<Edge>(); v3InEdges.add(edge2); ArrayList<Edge> v1OutEdges = new ArrayList<Edge>(); v1OutEdges.add(edge2); ArrayList<Edge> v2OutEdges = new ArrayList<Edge>(); v2OutEdges.add(edge1); v1.setInEdges(v1InEdges); v1.setOutEdges(v1OutEdges); v2.setOutEdges(v2OutEdges); v3.setInEdges(v3InEdges); VertexResource resource = this.constructMockGetSingleVertexScenario(v1, parameters); return resource; } private void assertVerticesOkResponseJsonStructure(int numberOfVerticesReturned, int numberOfVerticesTotal, Response response) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.TOTAL_SIZE)); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONArray jsonResults = json.optJSONArray(Tokens.RESULTS); Assert.assertEquals(numberOfVerticesReturned, jsonResults.length()); } private VertexResource constructMockGetSingleVertexScenario(final Vertex vertex, final HashMap<String, String> parameters) { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); List<String> namespaces = new ArrayList<String>(); namespaces.add("*:*"); rag.loadAllowableExtensions(namespaces); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(vertex)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); return resource; } private VertexResource constructMockGetVerticesScenario(final int numberOfVertices) { return this.constructMockGetVerticesScenario(numberOfVertices, new HashMap<String, String>()); } private VertexResource constructMockGetVerticesScenario(final int numberOfVertices, final HashMap<String, String> parameters) { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertices(); will(returnValue(generateMockedVertices(numberOfVertices))); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); return resource; } private static Iterable<Vertex> generateMockedVertices(int numberOfVertices) { ArrayList<Vertex> vertices = new ArrayList<Vertex>(); for (int ix = 0; ix < numberOfVertices; ix++) { MockVertex v = new MockVertex(new Integer(ix).toString()); vertices.add(v); } return vertices; } }
UTF-8
Java
51,716
java
VertexResourceTest.java
Java
[]
null
[]
package com.tinkerpop.rexster; import com.tinkerpop.rexster.server.RexsterApplication; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.commons.configuration.XMLConfiguration; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Variant; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Set; /** * Tests vertex resource. Should not need to test any specific returns values as they are * covered under other unit tests. The format of the results themselves should be covered * under the ElementJSONObject. */ public class VertexResourceTest { protected Mockery mockery = new JUnit4Mockery(); protected final String baseUri = "http://localhost/mock"; protected final URI requestUriPath = URI.create("http://localhost/graphs/mock/vertices"); @Before public void init() { this.mockery = new JUnit4Mockery(); } @Test public void getVerticesAll() { final int numberOfVertices = 100; VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(numberOfVertices, numberOfVertices, response); } @Test public void getVerticesKeyIndexed() { KeyIndexableGraph graph = TinkerGraphFactory.createTinkerGraph(); graph.createKeyIndex("name", Vertex.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.KEY, "name"); parameters.put(Tokens.VALUE, "marko"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); assertVerticesOkResponseJsonStructure(1, 1, resource.getVertices("graph")); } @Test public void getVerticesNoResults() { final int numberOfVertices = 0; VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(numberOfVertices, numberOfVertices, response); } @Test public void getVerticesWithValidOffset() { final int numberOfVertices = 100; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(10, numberOfVertices, response); JSONObject json = (JSONObject) response.getEntity(); JSONArray jsonResults = json.optJSONArray(Tokens.RESULTS); // should return ids 10 through 19 from the random generated data for (int ix = 0; ix < jsonResults.length(); ix++) { Assert.assertEquals(ix + 10, jsonResults.optJSONObject(ix).optInt(Tokens._ID)); } } @Test public void getVerticesWithInvalidOffsetNotEnoughResults() { final int numberOfVertices = 5; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(0, numberOfVertices, response); } @Test public void getVerticesWithInvalidOffsetStartAfterEnd() { final int numberOfVertices = 5; HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "100"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockGetVerticesScenario(numberOfVertices, parameters); Response response = resource.getVertices("graph"); this.assertVerticesOkResponseJsonStructure(0, numberOfVertices, response); } @Test(expected = WebApplicationException.class) public void getSingleVertexNotFound() { VertexResource resource = this.constructMockGetSingleVertexScenario(null, new HashMap<String, String>()); resource.getSingleVertex("graph", "id-does-not-match-any"); } @Test public void getSingleVertexFound() { Vertex v = new MockVertex("1"); VertexResource resource = this.constructMockGetSingleVertexScenario(v, new HashMap<String, String>()); Response response = resource.getSingleVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONObject jsonResult = (JSONObject) json.optJSONObject(Tokens.RESULTS); Assert.assertNotNull(jsonResult); } @Test(expected = WebApplicationException.class) public void getVertexEdgesNotFound() { VertexResource resource = this.constructMockGetSingleVertexScenario(null, new HashMap<String, String>()); resource.getSingleVertex("graph", "id-does-not-match-any"); } @Test public void getVertexEdgesFoundVertexReturnInEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.IN_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("1-2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnOutEdgesNoOffsetWithLabel() { HashMap<String, String> map = new HashMap<String, String>() {{ put(Tokens._LABEL, "label31"); }}; VertexResource resource = this.constructMockSimpleGraphScenario(map); Response response = resource.getVertexEdges("graph", "3", Tokens.OUT_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3-1", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnInVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.IN); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexReturnInVerticesNoOffsetWithLabel() { HashMap<String, String> map = new HashMap<String, String>() {{ put(Tokens._LABEL, "label12"); }}; VertexResource resource = this.constructMockSimpleGraphScenario(map); Response response = resource.getVertexEdges("graph", "1", Tokens.IN); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("2", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexOutEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.OUT_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3-1", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexOutVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.OUT); JSONObject json = assertEdgesOkResponseJsonStructure(response, 1); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(1, jsonResultArray.length()); JSONObject jsonResult = jsonResultArray.optJSONObject(0); Assert.assertNotNull(jsonResult); Assert.assertTrue(jsonResult.has(Tokens._ID)); Assert.assertEquals("3", jsonResult.optString(Tokens._ID)); } @Test public void getVertexEdgesFoundVertexBothEdgesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 2); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(2, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothVerticesNoOffset() { VertexResource resource = this.constructMockSimpleGraphScenario(); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH); JSONObject json = assertEdgesOkResponseJsonStructure(response, 2); JSONArray jsonResultArray = json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(2, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithValidOffset() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(100, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 100); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(10, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithOffsetNotEnoughResults() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "10"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(5, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 5); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(0, jsonResultArray.length()); } @Test public void getVertexEdgesFoundVertexBothEdgesWithOffsetStartAfterEnd() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_START, "30"); parameters.put(Tokens.REXSTER + "." + Tokens.OFFSET_END, "20"); VertexResource resource = this.constructMockMultiEdgedGraphScenario(100, parameters); Response response = resource.getVertexEdges("graph", "1", Tokens.BOTH_E); JSONObject json = assertEdgesOkResponseJsonStructure(response, 100); JSONArray jsonResultArray = (JSONArray) json.optJSONArray(Tokens.RESULTS); Assert.assertNotNull(jsonResultArray); Assert.assertEquals(0, jsonResultArray.length()); } @Test public void postNullVertexOnUriAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexRexsterConsumesJsonAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, false, false); } @Test public void postNullVertexOnUriAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexRexsterConsumesJsonAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptRexsterJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, false); } @Test public void postNullVertexOnUriAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexOnUri(jsr311Request, "graph"); assertPostVertexProducesJson(response, true, true); } @Test public void postNullVertexRexsterConsumesJsonAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, true); } @Test public void postNullVertexRexsterConsumesTypedJsonAcceptRexsterTypedJsonValid() { final HashMap<String, Object> parameters = generateVertexParametersToPost(true); final JSONObject jsonToPost = new JSONObject(parameters); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); initializeExtensionConfigurations(rag); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(RexsterMediaType.APPLICATION_REXSTER_TYPED_JSON_TYPE, null, null); final Sequence graphSequence = mockery.sequence("graph"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); oneOf(graph).addVertex(with(aNull(Object.class))); inSequence(graphSequence); will(returnValue(v)); oneOf(graph).getVertex(with(v.getId())); inSequence(graphSequence); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.postNullVertexRexsterConsumesTypedJson(jsr311Request, "graph", jsonToPost); assertPostVertexProducesJson(response, true, true); } @Test(expected = WebApplicationException.class) public void postVertexOnUriButHasElementProperties() { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(Tokens._ID, "300"); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.postVertexOnUri(jsr311Request, "graph", "1"); } @Test public void putVertexConsumesUriValid() { final HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("some-property", "300a"); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); v.setProperty("property-to-remove", "bye"); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.putVertexConsumesUri(jsr311Request, "graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); Assert.assertEquals("300a", v.getProperty("some-property")); Assert.assertFalse(v.getPropertyKeys().contains("property-to-remove")); } @Test(expected = WebApplicationException.class) public void putVertexConsumesUriNoVertexFound() { final HashMap<String, Object> parameters = generateVertexParametersToPost(false); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Request jsr311Request = this.mockery.mock(Request.class); final Variant variantJson = new Variant(MediaType.APPLICATION_JSON_TYPE, null, null); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(null)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(jsr311Request).selectVariant(with(any(List.class))); will(returnValue(variantJson)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.putVertexConsumesUri(jsr311Request, "graph", "1"); } @Test public void deleteVertexValid() { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(new HashMap<String, String>())); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(graph).removeVertex(v); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.deleteVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); } @Test(expected = WebApplicationException.class) public void deleteVertexNoVertexFound() { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(new HashMap<String, String>())); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(null)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); resource.deleteVertex("graph", "1"); } @Test public void deleteVertexPropertiesValid() { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("some-property", ""); final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); final Vertex v = new MockVertex("1"); v.setProperty("some-property", "to-delete"); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(v)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); Response response = resource.deleteVertex("graph", "1"); Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Set<String> keys = v.getPropertyKeys(); Assert.assertEquals(0, keys.size()); } private static void initializeExtensionConfigurations(RexsterApplicationGraph rag) { String xmlString = "<extension><namespace>tp</namespace><name>extensionname</name><configuration><test>1</test></configuration></extension>"; XMLConfiguration xmlConfig = new XMLConfiguration(); try { xmlConfig.load(new StringReader(xmlString)); } catch (ConfigurationException ex) { Assert.fail(ex.getMessage()); } List<HierarchicalConfiguration> list = new ArrayList<HierarchicalConfiguration>(); list.add(xmlConfig); List allowables = new ArrayList(); allowables.add("tp:*"); rag.loadAllowableExtensions(allowables); rag.loadExtensionsConfigurations(list); } private static HashMap<String, Object> generateVertexParametersToPost(boolean rexsterTyped) { final HashMap<String, Object> parameters = new HashMap<String, Object>(); if (rexsterTyped) { parameters.put("some-property", "(s,300a)"); parameters.put("int-property", "(i,300)"); } else { parameters.put("some-property", "300a"); parameters.put("int-property", 300); } return parameters; } private static void assertPostVertexProducesJson(Response response, boolean hasHypermedia, boolean hasTypes) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONObject postedVertex = json.optJSONObject(Tokens.RESULTS); if (hasTypes) { JSONObject somePropertyJson = postedVertex.optJSONObject("some-property"); Assert.assertEquals("string", somePropertyJson.optString("type")); Assert.assertEquals("300a", somePropertyJson.optString("value")); JSONObject intPropertyJson = postedVertex.optJSONObject("int-property"); Assert.assertEquals("integer", intPropertyJson.optString("type")); Assert.assertEquals(300, intPropertyJson.optInt("value")); } else { Assert.assertEquals("300a", postedVertex.optString("some-property")); Assert.assertEquals(300, postedVertex.optInt("int-property")); } if (hasHypermedia) { Assert.assertTrue(json.has(Tokens.EXTENSIONS)); } } private JSONObject assertEdgesOkResponseJsonStructure(Response response, int expectedTotalSize) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.TOTAL_SIZE)); Assert.assertEquals(expectedTotalSize, json.optInt(Tokens.TOTAL_SIZE)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); return json; } private VertexResource constructMockMultiEdgedGraphScenario(int numberOfEdgesToGenerate, HashMap<String, String> parameters) { MockVertex v1 = new MockVertex("1"); MockVertex v2 = new MockVertex("2"); ArrayList<Edge> v1InEdges = new ArrayList<Edge>(); ArrayList<Edge> v2OutEdges = new ArrayList<Edge>(); for (int ix = 0; ix < numberOfEdgesToGenerate; ix++) { MockEdge edge = new MockEdge(new Integer(ix).toString(), "label" + new Integer(ix).toString(), new Hashtable<String, Object>(), v1, v2); v1InEdges.add(edge); v2OutEdges.add(edge); } v1.setInEdges(v1InEdges); v2.setOutEdges(v2OutEdges); VertexResource resource = this.constructMockGetSingleVertexScenario(v1, parameters); return resource; } private VertexResource constructMockSimpleGraphScenario() { return constructMockSimpleGraphScenario(new HashMap<String, String>()); } /** * Creates a simple graph with two vertices and an edge between them. * * @return */ private VertexResource constructMockSimpleGraphScenario(HashMap parameters) { MockVertex v1 = new MockVertex("1"); MockVertex v2 = new MockVertex("2"); MockVertex v3 = new MockVertex("3"); MockEdge edge1 = new MockEdge("1-2", "label12", new Hashtable<String, Object>(), v1, v2); MockEdge edge2 = new MockEdge("3-1", "label31", new Hashtable<String, Object>(), v3, v1); ArrayList<Edge> v1InEdges = new ArrayList<Edge>(); v1InEdges.add(edge1); ArrayList<Edge> v3InEdges = new ArrayList<Edge>(); v3InEdges.add(edge2); ArrayList<Edge> v1OutEdges = new ArrayList<Edge>(); v1OutEdges.add(edge2); ArrayList<Edge> v2OutEdges = new ArrayList<Edge>(); v2OutEdges.add(edge1); v1.setInEdges(v1InEdges); v1.setOutEdges(v1OutEdges); v2.setOutEdges(v2OutEdges); v3.setInEdges(v3InEdges); VertexResource resource = this.constructMockGetSingleVertexScenario(v1, parameters); return resource; } private void assertVerticesOkResponseJsonStructure(int numberOfVerticesReturned, int numberOfVerticesTotal, Response response) { Assert.assertNotNull(response); Assert.assertEquals(Status.OK.getStatusCode(), response.getStatus()); Assert.assertNotNull(response.getEntity()); Assert.assertTrue(response.getEntity() instanceof JSONObject); JSONObject json = (JSONObject) response.getEntity(); Assert.assertTrue(json.has(Tokens.TOTAL_SIZE)); Assert.assertTrue(json.has(Tokens.QUERY_TIME)); Assert.assertTrue(json.has(Tokens.RESULTS)); Assert.assertFalse(json.isNull(Tokens.RESULTS)); JSONArray jsonResults = json.optJSONArray(Tokens.RESULTS); Assert.assertEquals(numberOfVerticesReturned, jsonResults.length()); } private VertexResource constructMockGetSingleVertexScenario(final Vertex vertex, final HashMap<String, String> parameters) { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); List<String> namespaces = new ArrayList<String>(); namespaces.add("*:*"); rag.loadAllowableExtensions(namespaces); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertex(with(any(Object.class))); will(returnValue(vertex)); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); return resource; } private VertexResource constructMockGetVerticesScenario(final int numberOfVertices) { return this.constructMockGetVerticesScenario(numberOfVertices, new HashMap<String, String>()); } private VertexResource constructMockGetVerticesScenario(final int numberOfVertices, final HashMap<String, String> parameters) { final Graph graph = this.mockery.mock(Graph.class); final RexsterApplicationGraph rag = new RexsterApplicationGraph("graph", graph); final RexsterApplication ra = this.mockery.mock(RexsterApplication.class); final UriInfo uri = this.mockery.mock(UriInfo.class); final HttpServletRequest httpServletRequest = this.mockery.mock(HttpServletRequest.class); this.mockery.checking(new Expectations() {{ allowing(httpServletRequest).getParameterMap(); will(returnValue(parameters)); allowing(graph).getVertices(); will(returnValue(generateMockedVertices(numberOfVertices))); allowing(ra).getApplicationGraph(with(any(String.class))); will(returnValue(rag)); allowing(uri).getAbsolutePath(); will(returnValue(requestUriPath)); }}); VertexResource resource = new VertexResource(uri, httpServletRequest, ra); return resource; } private static Iterable<Vertex> generateMockedVertices(int numberOfVertices) { ArrayList<Vertex> vertices = new ArrayList<Vertex>(); for (int ix = 0; ix < numberOfVertices; ix++) { MockVertex v = new MockVertex(new Integer(ix).toString()); vertices.add(v); } return vertices; } }
51,716
0.684817
0.678301
1,173
43.088661
32.215717
149
false
false
0
0
0
0
65
0.001257
0.907076
false
false
4
a793b7280abdfe3f1e24dd6fd460865bee038ddd
18,562,848,680,040
817ac68872165babda4d9d6c8a1190fd0bee370f
/src/main/java/com/hanlong/controller/TestController.java
d06d2f6670e07a9e5d029514ebc94f0c6ca773f8
[]
no_license
lthaccount/springSecurityDemo
https://github.com/lthaccount/springSecurityDemo
b3ba556a8940dfe7a93f4504fd4c89d6d293fc4c
83bc20cdcba1fd8f85a7c62b2c55c95e3d84cd16
refs/heads/master
2020-04-04T00:31:53.627000
2018-11-01T02:57:00
2018-11-01T02:57:00
155,653,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hanlong.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/admin") public class TestController { @PreAuthorize(value = "@premissionBean.pre()") @RequestMapping("/login") public void login(){ System.out.println("登陆!"); } }
UTF-8
Java
433
java
TestController.java
Java
[]
null
[]
package com.hanlong.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/admin") public class TestController { @PreAuthorize(value = "@premissionBean.pre()") @RequestMapping("/login") public void login(){ System.out.println("登陆!"); } }
433
0.752914
0.752914
15
27.6
20.915066
64
false
false
0
0
0
0
0
0
0.333333
false
false
4
b9c552fe5a9411c2132e7eeb09a4deff37027b75
3,693,671,901,807
213accade99af56d457da12a2e74ef3cb4923c73
/src/main/java/kr/or/connect/reserverproject/dto/DetailInitDTO.java
5e0f33c267b1af1d806826d889f3fb9150f9746f
[]
no_license
Kwonsoonmin13/reserverproject
https://github.com/Kwonsoonmin13/reserverproject
20d0044806d4b6290aac66bc1dbcb7c45f4078be
d54f2a5a0c48660caeb7a8ef1af7980c95a30952
refs/heads/master
2022-12-25T04:15:21.414000
2019-11-22T07:57:19
2019-11-22T07:57:19
219,444,236
0
0
null
false
2019-11-04T07:53:16
2019-11-04T07:42:04
2019-11-04T07:52:16
2019-11-04T07:53:15
0
0
0
1
Java
false
false
package kr.or.connect.reserverproject.dto; import java.util.ArrayList; public class DetailInitDTO { private ArrayList<String> topImage; private ArrayList<String> icon; private String title; private String summary; private String event; private ArrayList<String> event_Img; private String score_avg; private String score_Count; private ArrayList<String> comments; private ArrayList<String> comments_Img; public ArrayList<String> getEvent_Img() { return event_Img; } public void setEvent_Img(ArrayList<String> event_Img) { this.event_Img = event_Img; } public ArrayList<String> getTopImage() { return topImage; } public void setTopImage(ArrayList<String> topImage) { this.topImage = topImage; } public ArrayList<String> getIcon() { return icon; } public void setIcon(ArrayList<String> icon) { this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public String getScore_avg() { return score_avg; } public void setScore_avg(String score_avg) { this.score_avg = score_avg; } public String getScore_Count() { return score_Count; } public void setScore_Count(String score_Count) { this.score_Count = score_Count; } public ArrayList<String> getComments() { return comments; } public void setComments(ArrayList<String> comments) { this.comments = comments; } public ArrayList<String> getComments_Img() { return comments_Img; } public void setComments_Img(ArrayList<String> comments_Img) { this.comments_Img = comments_Img; } }
UTF-8
Java
1,803
java
DetailInitDTO.java
Java
[]
null
[]
package kr.or.connect.reserverproject.dto; import java.util.ArrayList; public class DetailInitDTO { private ArrayList<String> topImage; private ArrayList<String> icon; private String title; private String summary; private String event; private ArrayList<String> event_Img; private String score_avg; private String score_Count; private ArrayList<String> comments; private ArrayList<String> comments_Img; public ArrayList<String> getEvent_Img() { return event_Img; } public void setEvent_Img(ArrayList<String> event_Img) { this.event_Img = event_Img; } public ArrayList<String> getTopImage() { return topImage; } public void setTopImage(ArrayList<String> topImage) { this.topImage = topImage; } public ArrayList<String> getIcon() { return icon; } public void setIcon(ArrayList<String> icon) { this.icon = icon; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } public String getScore_avg() { return score_avg; } public void setScore_avg(String score_avg) { this.score_avg = score_avg; } public String getScore_Count() { return score_Count; } public void setScore_Count(String score_Count) { this.score_Count = score_Count; } public ArrayList<String> getComments() { return comments; } public void setComments(ArrayList<String> comments) { this.comments = comments; } public ArrayList<String> getComments_Img() { return comments_Img; } public void setComments_Img(ArrayList<String> comments_Img) { this.comments_Img = comments_Img; } }
1,803
0.724348
0.724348
80
21.5375
16.969048
62
false
false
0
0
0
0
0
0
1.575
false
false
4
3996af95bd858064fa70929fd93917058c2dd70f
14,654,428,448,248
00d15e86345c315f020a5551c9b9f29b46dc7b5b
/oilmachine-webapp/src/main/java/com/pcitc/oilmachine/controller/BaseAction.java
f20125aa8f2fde81e45a1729c2c811ca5d2bf270
[]
no_license
liuwenqi9/iot
https://github.com/liuwenqi9/iot
f043f8ede0d9123dad0eefbe7e4cf68e8656d4cf
1cb25e6c7d205880e0eda20029afa3fc32de043a
refs/heads/master
2020-04-30T09:01:30.240000
2018-08-23T10:18:34
2018-08-23T10:18:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pcitc.oilmachine.controller; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.pcitc.oilmachine.commons.constant.Constant; import com.pcitc.oilmachine.form.UserInfo; import com.pcitc.oilmachine.view.GridData; public class BaseAction { /** * 返回JSON格式,并格式化时间 * @author 王少亭 * @param obj * @return * 2017年4月12日下午4:16:00 */ protected String toJSONFormat(Object obj){ JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; return JSON.toJSONString(obj,SerializerFeature.WriteDateUseDateFormat); } protected String writeGridData(GridData gridData){ if(gridData.getRecordsTotal() == 0) gridData.setData(new ArrayList<>()); return toJSONFormat(gridData); } protected UserInfo getUserInfo() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); return (UserInfo) request.getSession().getAttribute(Constant.SESSION_KEY); } }
UTF-8
Java
1,281
java
BaseAction.java
Java
[ { "context": "eAction {\r\n\t/**\r\n\t * 返回JSON格式,并格式化时间\r\n\t * @author 王少亭\r\n\t * @param obj\r\n\t * @return\r\n\t * 2017年4月12日下午4:1", "end": 579, "score": 0.9977962970733643, "start": 576, "tag": "NAME", "value": "王少亭" } ]
null
[]
package com.pcitc.oilmachine.controller; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.pcitc.oilmachine.commons.constant.Constant; import com.pcitc.oilmachine.form.UserInfo; import com.pcitc.oilmachine.view.GridData; public class BaseAction { /** * 返回JSON格式,并格式化时间 * @author 王少亭 * @param obj * @return * 2017年4月12日下午4:16:00 */ protected String toJSONFormat(Object obj){ JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; return JSON.toJSONString(obj,SerializerFeature.WriteDateUseDateFormat); } protected String writeGridData(GridData gridData){ if(gridData.getRecordsTotal() == 0) gridData.setData(new ArrayList<>()); return toJSONFormat(gridData); } protected UserInfo getUserInfo() { HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); return (UserInfo) request.getSession().getAttribute(Constant.SESSION_KEY); } }
1,281
0.759453
0.748994
41
28.317074
27.612686
117
false
false
0
0
0
0
0
0
1.195122
false
false
4
817859fa7215319ffc56dac438f1d2d7e7116ea2
14,654,428,449,565
fc7958adac3d5995bc5d935a6e53e4be8abb0585
/src/main/java/com/assignment/exception/NotFoundException.java
24f94bcdcdc8d847111ff9bea0eb96b9754e0092
[]
no_license
ebwranj/sample-project
https://github.com/ebwranj/sample-project
d241fe95e205ddcb4562e9f511edabe3c82acca9
5ef7908bcffb09d089c341a0dbd8416f6afe3331
refs/heads/master
2020-04-19T21:58:51.185000
2019-02-15T06:00:10
2019-02-15T06:00:10
168,456,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.assignment.exception; public class NotFoundException extends Exception { }
UTF-8
Java
88
java
NotFoundException.java
Java
[]
null
[]
package com.assignment.exception; public class NotFoundException extends Exception { }
88
0.829545
0.829545
4
21
21.36586
50
false
false
0
0
0
0
0
0
0.25
false
false
4
c36a10caa81c02b61a1f408153dd32e3da665337
19,645,180,448,225
8513787f9666b3edd7c230a6699ae0200f9bce76
/app/src/main/java/com/psi/easymanager/adapter/MemberAdapter.java
af9b4cf30be5e9498c4cb97c925f68ed90e39824
[]
no_license
474843468/em
https://github.com/474843468/em
c0296da454bbb7b4ff28fd25b83d0e53c5463123
3fdc191c8809528358401f2fc7f9e41ca84fea7f
refs/heads/master
2021-01-23T16:35:16.647000
2017-06-04T09:18:59
2017-06-04T09:18:59
93,302,779
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.psi.easymanager.adapter; import android.content.Context; import android.graphics.Color; 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 butterknife.Bind; import butterknife.ButterKnife; import com.psi.easymanager.R; import com.psi.easymanager.module.PxVipInfo; import com.psi.easymanager.utils.NumberFormatUtils; import java.util.ArrayList; import java.util.List; /** * Created by psi on 2016/5/17. * 会员列表适配器 */ public class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder> { private Context mContext; private List<PxVipInfo> mVipInfoList; private int mPrePos = -1;//选择前pos public int mCurrentPos = -1;//当前选择Pos public void setSelected(int position) { if (mCurrentPos == position) return; mCurrentPos = position; if (mPrePos != -1) { notifyItemChanged(mPrePos); } notifyItemChanged(mCurrentPos); mPrePos = mCurrentPos; } public MemberAdapter(Context context, List<PxVipInfo> vipInfoList) { mContext = context; if (vipInfoList == null) { this.mVipInfoList = new ArrayList<>(); } else { this.mVipInfoList = vipInfoList; } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_vip, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { PxVipInfo vipInfo = mVipInfoList.get(position); switch (Integer.valueOf(vipInfo.getLevel())) { case PxVipInfo.VIP_ONE: holder.ivItemIcon.setImageResource(R.mipmap.ic_member_level_two); break; } holder.tvItemMemberName.setText(vipInfo.getName()); if (vipInfo.getAccountBalance() >= 5000) { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.green)); } else if (vipInfo.getAccountBalance() < 5000 && vipInfo.getAccountBalance() >= 1000) { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.colorAccent)); } else if (vipInfo.getAccountBalance() < 1000 && vipInfo.getAccountBalance() > 100) { holder.tvItemMemberMoney.setTextColor( mContext.getResources().getColor(R.color.material_blue)); } else { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.red)); } holder.tvItemMemberMoney.setText( "余额:" + NumberFormatUtils.formatFloatNumber(vipInfo.getAccountBalance()) + "(元)"); holder.tvItemMemberMobile.setText(vipInfo.getMobile()); if (mCurrentPos == position) { holder.cvItemMember.setCardBackgroundColor(Color.parseColor("#bbffbb")); } else { holder.cvItemMember.setCardBackgroundColor(Color.TRANSPARENT); } holder.cvItemMember.setTag(holder.getAdapterPosition()); if (listener != null) { holder.cvItemMember.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = (Integer) v.getTag(); listener.onMemberItemClick(pos); mPrePos = mCurrentPos; } }); } } @Override public int getItemCount() { return mVipInfoList.size(); } class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.iv_item_icon) ImageView ivItemIcon; @Bind(R.id.tv_item_member_name) TextView tvItemMemberName; @Bind(R.id.tv_item_member_money) TextView tvItemMemberMoney; @Bind(R.id.tv_item_member_mobile) TextView tvItemMemberMobile; @Bind(R.id.cv_item_member) CardView cvItemMember; // Boolean isChoice; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } /** * 添加数据 */ public void setData(List<PxVipInfo> vipInfoList) { if (vipInfoList == null) return; mPrePos = -1; mCurrentPos = -1; mVipInfoList.clear(); mVipInfoList.addAll(vipInfoList); this.notifyDataSetChanged(); } /** * 清除数据 */ public void clearData() { mVipInfoList.clear(); this.notifyDataSetChanged(); } /** * 点击事件 */ public interface onMemberItemClickListener { void onMemberItemClick(int pos); } private onMemberItemClickListener listener; public void setListener(onMemberItemClickListener listener) { this.listener = listener; } /** * 修改 会员余额 */ public void ChangeVipInfoMoney(Double money, int pos) { mVipInfoList.get(pos).setAccountBalance(mVipInfoList.get(pos).getAccountBalance() - money); notifyItemChanged(pos); } /** * 恢复未选中状态 */ public void RecoverNotChoiceStatus() { int size = mVipInfoList.size(); if (mPrePos >= 0 && mPrePos < (size - 1)) { notifyItemChanged(mPrePos); } if (mCurrentPos >= 0 && mCurrentPos < (size - 1)) { notifyItemChanged(mCurrentPos); } mPrePos = -1; mCurrentPos = -1; } /** * 修改选中会员的信息(名字,电话,级别,金额--金额只有 “充值”时或者“冲销”时修改) * * type : 修改项 * 0: null * 1 :name * 2 :mobile * 3 :level * 4 :money * pos: 修改位置 * str: 更新信息 */ public void ChangeVipInforation(int type, int pos, String str) { PxVipInfo vipInfo = mVipInfoList.get(pos); switch (type) { case 1: vipInfo.setName(str); break; case 2: vipInfo.setMobile(str); break; case 3: vipInfo.setLevel(str); break; case 4: vipInfo.setAccountBalance(Double.parseDouble(str)); break; } notifyItemChanged(pos); } }
UTF-8
Java
5,882
java
MemberAdapter.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by psi on 2016/5/17.\n * 会员列表适配器\n */\npublic class MemberA", "end": 606, "score": 0.9980056881904602, "start": 603, "tag": "USERNAME", "value": "psi" } ]
null
[]
package com.psi.easymanager.adapter; import android.content.Context; import android.graphics.Color; 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 butterknife.Bind; import butterknife.ButterKnife; import com.psi.easymanager.R; import com.psi.easymanager.module.PxVipInfo; import com.psi.easymanager.utils.NumberFormatUtils; import java.util.ArrayList; import java.util.List; /** * Created by psi on 2016/5/17. * 会员列表适配器 */ public class MemberAdapter extends RecyclerView.Adapter<MemberAdapter.ViewHolder> { private Context mContext; private List<PxVipInfo> mVipInfoList; private int mPrePos = -1;//选择前pos public int mCurrentPos = -1;//当前选择Pos public void setSelected(int position) { if (mCurrentPos == position) return; mCurrentPos = position; if (mPrePos != -1) { notifyItemChanged(mPrePos); } notifyItemChanged(mCurrentPos); mPrePos = mCurrentPos; } public MemberAdapter(Context context, List<PxVipInfo> vipInfoList) { mContext = context; if (vipInfoList == null) { this.mVipInfoList = new ArrayList<>(); } else { this.mVipInfoList = vipInfoList; } } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_vip, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { PxVipInfo vipInfo = mVipInfoList.get(position); switch (Integer.valueOf(vipInfo.getLevel())) { case PxVipInfo.VIP_ONE: holder.ivItemIcon.setImageResource(R.mipmap.ic_member_level_two); break; } holder.tvItemMemberName.setText(vipInfo.getName()); if (vipInfo.getAccountBalance() >= 5000) { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.green)); } else if (vipInfo.getAccountBalance() < 5000 && vipInfo.getAccountBalance() >= 1000) { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.colorAccent)); } else if (vipInfo.getAccountBalance() < 1000 && vipInfo.getAccountBalance() > 100) { holder.tvItemMemberMoney.setTextColor( mContext.getResources().getColor(R.color.material_blue)); } else { holder.tvItemMemberMoney.setTextColor(mContext.getResources().getColor(R.color.red)); } holder.tvItemMemberMoney.setText( "余额:" + NumberFormatUtils.formatFloatNumber(vipInfo.getAccountBalance()) + "(元)"); holder.tvItemMemberMobile.setText(vipInfo.getMobile()); if (mCurrentPos == position) { holder.cvItemMember.setCardBackgroundColor(Color.parseColor("#bbffbb")); } else { holder.cvItemMember.setCardBackgroundColor(Color.TRANSPARENT); } holder.cvItemMember.setTag(holder.getAdapterPosition()); if (listener != null) { holder.cvItemMember.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = (Integer) v.getTag(); listener.onMemberItemClick(pos); mPrePos = mCurrentPos; } }); } } @Override public int getItemCount() { return mVipInfoList.size(); } class ViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.iv_item_icon) ImageView ivItemIcon; @Bind(R.id.tv_item_member_name) TextView tvItemMemberName; @Bind(R.id.tv_item_member_money) TextView tvItemMemberMoney; @Bind(R.id.tv_item_member_mobile) TextView tvItemMemberMobile; @Bind(R.id.cv_item_member) CardView cvItemMember; // Boolean isChoice; public ViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } /** * 添加数据 */ public void setData(List<PxVipInfo> vipInfoList) { if (vipInfoList == null) return; mPrePos = -1; mCurrentPos = -1; mVipInfoList.clear(); mVipInfoList.addAll(vipInfoList); this.notifyDataSetChanged(); } /** * 清除数据 */ public void clearData() { mVipInfoList.clear(); this.notifyDataSetChanged(); } /** * 点击事件 */ public interface onMemberItemClickListener { void onMemberItemClick(int pos); } private onMemberItemClickListener listener; public void setListener(onMemberItemClickListener listener) { this.listener = listener; } /** * 修改 会员余额 */ public void ChangeVipInfoMoney(Double money, int pos) { mVipInfoList.get(pos).setAccountBalance(mVipInfoList.get(pos).getAccountBalance() - money); notifyItemChanged(pos); } /** * 恢复未选中状态 */ public void RecoverNotChoiceStatus() { int size = mVipInfoList.size(); if (mPrePos >= 0 && mPrePos < (size - 1)) { notifyItemChanged(mPrePos); } if (mCurrentPos >= 0 && mCurrentPos < (size - 1)) { notifyItemChanged(mCurrentPos); } mPrePos = -1; mCurrentPos = -1; } /** * 修改选中会员的信息(名字,电话,级别,金额--金额只有 “充值”时或者“冲销”时修改) * * type : 修改项 * 0: null * 1 :name * 2 :mobile * 3 :level * 4 :money * pos: 修改位置 * str: 更新信息 */ public void ChangeVipInforation(int type, int pos, String str) { PxVipInfo vipInfo = mVipInfoList.get(pos); switch (type) { case 1: vipInfo.setName(str); break; case 2: vipInfo.setMobile(str); break; case 3: vipInfo.setLevel(str); break; case 4: vipInfo.setAccountBalance(Double.parseDouble(str)); break; } notifyItemChanged(pos); } }
5,882
0.677431
0.669007
203
27.068966
24.708252
99
false
false
0
0
0
0
0
0
0.46798
false
false
4
55e62aad65710008081cab9541792589f46bc83f
22,419,729,314,942
d02ffd7a20f16b3402ac2f965f3271bbdfbb8c69
/chapter-10/src/main/java/com/lujiatao/c10/Timer.java
cb3915cd534e7c9a49e765f8cb2ae620f4607879
[]
no_license
goodlucky68/automated-testing-advanced
https://github.com/goodlucky68/automated-testing-advanced
5a05d3835a050523d5722487929a041677d11d2e
4d7dcea6f9fdf2f39fa1f3742686a4d83d815ce1
refs/heads/master
2023-01-14T12:19:17.754000
2020-11-26T15:12:28
2020-11-26T15:12:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lujiatao.c10; public class Timer { public static final Timer TIMER = new Timer(); private long startTime; private Timer() { } public void setStartTime() { this.startTime = System.currentTimeMillis(); } public long getElapsedTime() { return System.currentTimeMillis() - startTime; } }
UTF-8
Java
350
java
Timer.java
Java
[]
null
[]
package com.lujiatao.c10; public class Timer { public static final Timer TIMER = new Timer(); private long startTime; private Timer() { } public void setStartTime() { this.startTime = System.currentTimeMillis(); } public long getElapsedTime() { return System.currentTimeMillis() - startTime; } }
350
0.64
0.634286
19
17.421053
18.924547
54
false
false
0
0
0
0
0
0
0.263158
false
false
4
6a7d3720d6c9f4f1bd5e2cf880eceb14dfaf225f
5,179,730,614,003
d97527c4ba38df7e3b8f13b619b13526ba1a4ba1
/springboot-starter/src/main/java/com/learn/springbootstarter/EnableAutoFromSpi/SPIDemo.java
acf1e2bbd1b27a5f6985cf29be9f2b49e2e3170b
[]
no_license
liman657/learn2019
https://github.com/liman657/learn2019
472d2713b53e0fd73fb9617279c73b7a06ca4732
8e65320752b742463f2a43a41df75b15c0452477
refs/heads/master
2023-06-10T05:26:05.929000
2023-06-04T08:10:18
2023-06-04T08:10:18
174,538,097
2
0
null
false
2022-06-21T04:20:15
2019-03-08T12:58:17
2021-09-18T02:14:18
2022-06-21T04:20:15
5,464
2
0
18
JavaScript
false
false
package com.learn.springbootstarter.EnableAutoFromSpi; import com.learn.service.SPIDemoService; import com.learn.springbootstarter.configuration.ConfigurationDemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import java.util.stream.Stream; /** * autor:liman * createtime:2019/8/25 * comment: */ @SpringBootApplication public class SPIDemo { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(SPIDemo.class); SPIDemoService sp = applicationContext.getBean(SPIDemoService.class); // String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); // Stream.of(beanDefinitionNames).forEach(System.out::println); String test = sp.SPISayHello("test"); System.out.println(test); } }
UTF-8
Java
959
java
SPIDemo.java
Java
[ { "context": "t;\n\nimport java.util.stream.Stream;\n\n/**\n * autor:liman\n * createtime:2019/8/25\n * comment:\n */\n@SpringBo", "end": 404, "score": 0.9995326995849609, "start": 399, "tag": "USERNAME", "value": "liman" } ]
null
[]
package com.learn.springbootstarter.EnableAutoFromSpi; import com.learn.service.SPIDemoService; import com.learn.springbootstarter.configuration.ConfigurationDemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import java.util.stream.Stream; /** * autor:liman * createtime:2019/8/25 * comment: */ @SpringBootApplication public class SPIDemo { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = SpringApplication.run(SPIDemo.class); SPIDemoService sp = applicationContext.getBean(SPIDemoService.class); // String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); // Stream.of(beanDefinitionNames).forEach(System.out::println); String test = sp.SPISayHello("test"); System.out.println(test); } }
959
0.775808
0.768509
28
33.25
29.797682
97
false
false
0
0
0
0
0
0
0.464286
false
false
4
fb513a2449ce62ecbf7e134b358746822061c7f3
26,371,099,211,699
f53b7172453f7690561a379e2400d03494c8516a
/src/main/java/kr/hotba/util/Crawler.java
8dcbaf4f9cda55d93d11c4f5957f93a5031d612b
[]
no_license
SilverNine/Hotba-API
https://github.com/SilverNine/Hotba-API
e6110dd7cc47c9a839f35864e189dcfcf55ac607
118e72671e69e5a809c45e0550b0c4f062a5276a
refs/heads/master
2018-01-15T04:21:38.758000
2016-12-03T02:44:46
2016-12-03T02:44:46
29,803,970
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.hotba.util; import kr.hotba.v1.domain.Gym; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Crawler { private static final Logger logger = LoggerFactory.getLogger(Crawler.class); public List<Gym> locationSearchCrawler(Gym paramGym) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; try { String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U"; String lat, lon; if(paramGym.getLat() < 1 && paramGym.getLon() < 1) { return new ArrayList<Gym>(); } else { lat = String.valueOf(paramGym.getLat()); lon = String.valueOf(paramGym.getLon()); } String param = "&location=" + lat + "," + lon + "&radius=1000000&types=gym&sensor=false"; String crawlUrl; String nextPageToken = null; JSONParser parser; do { parser = new JSONParser(); if(!StringUtils.isEmpty(nextPageToken)) { crawlUrl = url + "&pagetoken=" + nextPageToken; } else { crawlUrl = url + param; } JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); try { nextPageToken = object.get("next_page_token").toString(); } catch(NullPointerException e) { nextPageToken = ""; } JSONArray array = (JSONArray) object.get("results"); Iterator i = array.iterator(); while (i.hasNext()) { gym = new Gym(); JSONObject innerObj = (JSONObject) i.next(); logger.debug("name : " + innerObj.get("name")); gym.setTitle(innerObj.get("name").toString()); logger.debug("vicinity : " + innerObj.get("vicinity")); gym.setAddress(innerObj.get("vicinity").toString()); JSONObject geometryObj = (JSONObject) parser.parse(innerObj.get("geometry").toString()); JSONObject locationObj = (JSONObject) parser.parse(geometryObj.get("location").toString()); logger.debug("location lat, lng : " + locationObj.get("lat") + ", " + locationObj.get("lng")); gym.setLat((Double) locationObj.get("lat")); gym.setLon((Double) locationObj.get("lng")); logger.debug("reference : " + innerObj.get("reference")); gym.setGoogleReference(innerObj.get("reference").toString()); gymList.add(gym); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (!StringUtils.isEmpty(nextPageToken)); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gymList; } public List<Gym> citySearchCrawler(String query) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; try { if(StringUtils.isEmpty(query)) { return new ArrayList<Gym>(); } String url = "https://maps.googleapis.com/maps/api/place/textsearch/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U"; String param = "&query=피트니스+in+" + query; String crawlUrl; String nextPageToken = null; JSONParser parser; do { parser = new JSONParser(); if(!StringUtils.isEmpty(nextPageToken)) { crawlUrl = url + "&pagetoken=" + nextPageToken; } else { crawlUrl = url + param; } JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); try { nextPageToken = object.get("next_page_token").toString(); } catch(NullPointerException e) { nextPageToken = ""; } JSONArray array = (JSONArray) object.get("results"); Iterator i = array.iterator(); while (i.hasNext()) { gym = new Gym(); JSONObject innerObj = (JSONObject) i.next(); logger.debug("name : " + innerObj.get("name")); gym.setTitle(innerObj.get("name").toString()); logger.debug("formatted_address : " + innerObj.get("formatted_address")); gym.setAddress(innerObj.get("formatted_address").toString()); JSONObject geometryObj = (JSONObject) parser.parse(innerObj.get("geometry").toString()); JSONObject locationObj = (JSONObject) parser.parse(geometryObj.get("location").toString()); logger.debug("location lat, lng : " + locationObj.get("lat") + ", " + locationObj.get("lng")); gym.setLat((Double) locationObj.get("lat")); gym.setLon((Double) locationObj.get("lng")); logger.debug("reference : " + innerObj.get("reference")); gym.setGoogleReference(innerObj.get("reference").toString()); gymList.add(gym); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (!StringUtils.isEmpty(nextPageToken)); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gymList; } public Gym detailCrawler(Gym gym) { String url = "https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U&reference=" + gym.getGoogleReference(); JSONParser parser; Gym returnGym = new Gym(); try { parser = new JSONParser(); JSONObject object; JSONObject detailObj; try { object = (JSONObject) parser.parse(Jsoup.connect(url).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); detailObj = (JSONObject) parser.parse(object.get("result").toString()); } catch ( NullPointerException e ) { e.printStackTrace(); return returnGym; } if(detailObj.get("formatted_phone_number") == null || detailObj.get("formatted_address") == null) { return returnGym; } returnGym.setTelno(detailObj.get("formatted_phone_number").toString()); returnGym.setAddress(detailObj.get("formatted_address").toString()); returnGym.setGoogleReference(gym.getGoogleReference()); } catch ( NullPointerException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } return returnGym; } public List<Gym> naverSearchCrawler(String query) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; if(StringUtils.isEmpty(query)) { return new ArrayList<Gym>(); } String[] crawlUrls = {"피트니스", "퍼스널트레이닝", "필라테스"}; for (String crawlType : crawlUrls) { String crawlUrl = "http://openapi.naver.com/search?key=c9321d1b172c92e845b4d148120fb18a&sort=random&display=100&target=local&query=" + crawlType + "+" + query; try { URLEncoder.encode(crawlUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(crawlUrl); Element root = doc.getDocumentElement(); NodeList list = root.getElementsByTagName("item"); for (int i = 0; i < list.getLength(); i++) { gym = new Gym(); Element element = (Element) list.item(i); gym.setTitle(getContent(element, "title")); gym.setUrl(getContent(element, "link")); gym.setContent(getContent(element, "description")); gym.setTelno(getContent(element, "telephone")); gym.setAddress(getContent(element, "address")); gym.setStreetAddress(getContent(element, "roadAddress")); gym.setMapx(getContent(element, "mapx")); gym.setMapy(getContent(element, "mapy")); gymList.add(gym); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return gymList; } public static String removeHtmlCode(String html) { return Jsoup.parse(html).text(); } public static String getContent(Element element, String tagName) { NodeList list = element.getElementsByTagName(tagName); Element cElement = (Element)list.item(0); if(cElement.getFirstChild()!=null){ return removeHtmlCode(cElement.getFirstChild().getNodeValue()); }else{ return ""; } } public synchronized static Gym transCoord(Gym gym) throws ParseException, IOException { JSONParser parser = new JSONParser(); String crawlUrl = "http://apis.daum.net/maps/transcoord?apikey=cbbb70de1073dce4a48175ac1b52fa3a&x="+gym.getMapx()+"&y="+gym.getMapy()+"&fromCoord=KTM&toCoord=WGS84&output=json"; try { JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); gym.setLat((Double) object.get("y")); gym.setLon((Double) object.get("x")); } catch (ParseException e) { throw new ParseException(e.getErrorType()); } catch (HttpStatusException e) { throw new HttpStatusException(e.getMessage(), e.getStatusCode(), crawlUrl); } catch (IOException e) { throw new IOException(); } return gym; } public synchronized static String crawlTargetUrl(String url) throws IOException { if(StringUtils.isEmpty(url)) { return ""; } URL obj = null; String returnUrl = null; try { obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setInstanceFollowRedirects(false); returnUrl = conn.getHeaderField("Location"); //TODO www. .com 으로 넘어오는 것들이 있다. 한글이슈 인지 확인하자 if(returnUrl.indexOf(" ") > -1) { return ""; } } catch (MalformedURLException e) { throw new MalformedURLException(e.getMessage()); } catch (IOException e) { throw new IOException(e.getMessage()); } return returnUrl; } }
UTF-8
Java
12,881
java
Crawler.java
Java
[ { "context": "ogleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U\";\n String lat, lon;\n\n if(pa", "end": 1293, "score": 0.9996374845504761, "start": 1254, "tag": "KEY", "value": "AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U" }, { "context": "googleapis.com/maps/api/place/textsearch/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U\";\n String param = \"&query=피트니스+in+\" + ", "end": 4455, "score": 0.9996699094772339, "start": 4416, "tag": "KEY", "value": "AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U" }, { "context": "ps.googleapis.com/maps/api/place/details/json?key=AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U&reference=\" + gym.getGoogleReference();\n J", "end": 7095, "score": 0.9994434714317322, "start": 7056, "tag": "KEY", "value": "AIzaSyAtL9LVedV1Bye1nJ77SCkUxX2q7QToN4U" }, { "context": "g crawlUrl = \"http://openapi.naver.com/search?key=c9321d1b172c92e845b4d148120fb18a&sort=random&display=100&target=local&query=\" + cr", "end": 8916, "score": 0.9997454285621643, "start": 8884, "tag": "KEY", "value": "c9321d1b172c92e845b4d148120fb18a" }, { "context": "rl = \"http://apis.daum.net/maps/transcoord?apikey=cbbb70de1073dce4a48175ac1b52fa3a&x=\"+gym.getMapx()+\"&y=\"+gym.getMapy()+\"&fromCoord", "end": 11277, "score": 0.999431848526001, "start": 11245, "tag": "KEY", "value": "cbbb70de1073dce4a48175ac1b52fa3a" } ]
null
[]
package kr.hotba.util; import kr.hotba.v1.domain.Gym; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Crawler { private static final Logger logger = LoggerFactory.getLogger(Crawler.class); public List<Gym> locationSearchCrawler(Gym paramGym) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; try { String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=<KEY>"; String lat, lon; if(paramGym.getLat() < 1 && paramGym.getLon() < 1) { return new ArrayList<Gym>(); } else { lat = String.valueOf(paramGym.getLat()); lon = String.valueOf(paramGym.getLon()); } String param = "&location=" + lat + "," + lon + "&radius=1000000&types=gym&sensor=false"; String crawlUrl; String nextPageToken = null; JSONParser parser; do { parser = new JSONParser(); if(!StringUtils.isEmpty(nextPageToken)) { crawlUrl = url + "&pagetoken=" + nextPageToken; } else { crawlUrl = url + param; } JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); try { nextPageToken = object.get("next_page_token").toString(); } catch(NullPointerException e) { nextPageToken = ""; } JSONArray array = (JSONArray) object.get("results"); Iterator i = array.iterator(); while (i.hasNext()) { gym = new Gym(); JSONObject innerObj = (JSONObject) i.next(); logger.debug("name : " + innerObj.get("name")); gym.setTitle(innerObj.get("name").toString()); logger.debug("vicinity : " + innerObj.get("vicinity")); gym.setAddress(innerObj.get("vicinity").toString()); JSONObject geometryObj = (JSONObject) parser.parse(innerObj.get("geometry").toString()); JSONObject locationObj = (JSONObject) parser.parse(geometryObj.get("location").toString()); logger.debug("location lat, lng : " + locationObj.get("lat") + ", " + locationObj.get("lng")); gym.setLat((Double) locationObj.get("lat")); gym.setLon((Double) locationObj.get("lng")); logger.debug("reference : " + innerObj.get("reference")); gym.setGoogleReference(innerObj.get("reference").toString()); gymList.add(gym); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (!StringUtils.isEmpty(nextPageToken)); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gymList; } public List<Gym> citySearchCrawler(String query) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; try { if(StringUtils.isEmpty(query)) { return new ArrayList<Gym>(); } String url = "https://maps.googleapis.com/maps/api/place/textsearch/json?key=<KEY>"; String param = "&query=피트니스+in+" + query; String crawlUrl; String nextPageToken = null; JSONParser parser; do { parser = new JSONParser(); if(!StringUtils.isEmpty(nextPageToken)) { crawlUrl = url + "&pagetoken=" + nextPageToken; } else { crawlUrl = url + param; } JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); try { nextPageToken = object.get("next_page_token").toString(); } catch(NullPointerException e) { nextPageToken = ""; } JSONArray array = (JSONArray) object.get("results"); Iterator i = array.iterator(); while (i.hasNext()) { gym = new Gym(); JSONObject innerObj = (JSONObject) i.next(); logger.debug("name : " + innerObj.get("name")); gym.setTitle(innerObj.get("name").toString()); logger.debug("formatted_address : " + innerObj.get("formatted_address")); gym.setAddress(innerObj.get("formatted_address").toString()); JSONObject geometryObj = (JSONObject) parser.parse(innerObj.get("geometry").toString()); JSONObject locationObj = (JSONObject) parser.parse(geometryObj.get("location").toString()); logger.debug("location lat, lng : " + locationObj.get("lat") + ", " + locationObj.get("lng")); gym.setLat((Double) locationObj.get("lat")); gym.setLon((Double) locationObj.get("lng")); logger.debug("reference : " + innerObj.get("reference")); gym.setGoogleReference(innerObj.get("reference").toString()); gymList.add(gym); } try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (!StringUtils.isEmpty(nextPageToken)); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return gymList; } public Gym detailCrawler(Gym gym) { String url = "https://maps.googleapis.com/maps/api/place/details/json?key=<KEY>&reference=" + gym.getGoogleReference(); JSONParser parser; Gym returnGym = new Gym(); try { parser = new JSONParser(); JSONObject object; JSONObject detailObj; try { object = (JSONObject) parser.parse(Jsoup.connect(url).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); detailObj = (JSONObject) parser.parse(object.get("result").toString()); } catch ( NullPointerException e ) { e.printStackTrace(); return returnGym; } if(detailObj.get("formatted_phone_number") == null || detailObj.get("formatted_address") == null) { return returnGym; } returnGym.setTelno(detailObj.get("formatted_phone_number").toString()); returnGym.setAddress(detailObj.get("formatted_address").toString()); returnGym.setGoogleReference(gym.getGoogleReference()); } catch ( NullPointerException e ) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } return returnGym; } public List<Gym> naverSearchCrawler(String query) { List<Gym> gymList = new ArrayList<Gym>(); Gym gym; if(StringUtils.isEmpty(query)) { return new ArrayList<Gym>(); } String[] crawlUrls = {"피트니스", "퍼스널트레이닝", "필라테스"}; for (String crawlType : crawlUrls) { String crawlUrl = "http://openapi.naver.com/search?key=<KEY>&sort=random&display=100&target=local&query=" + crawlType + "+" + query; try { URLEncoder.encode(crawlUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(crawlUrl); Element root = doc.getDocumentElement(); NodeList list = root.getElementsByTagName("item"); for (int i = 0; i < list.getLength(); i++) { gym = new Gym(); Element element = (Element) list.item(i); gym.setTitle(getContent(element, "title")); gym.setUrl(getContent(element, "link")); gym.setContent(getContent(element, "description")); gym.setTelno(getContent(element, "telephone")); gym.setAddress(getContent(element, "address")); gym.setStreetAddress(getContent(element, "roadAddress")); gym.setMapx(getContent(element, "mapx")); gym.setMapy(getContent(element, "mapy")); gymList.add(gym); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return gymList; } public static String removeHtmlCode(String html) { return Jsoup.parse(html).text(); } public static String getContent(Element element, String tagName) { NodeList list = element.getElementsByTagName(tagName); Element cElement = (Element)list.item(0); if(cElement.getFirstChild()!=null){ return removeHtmlCode(cElement.getFirstChild().getNodeValue()); }else{ return ""; } } public synchronized static Gym transCoord(Gym gym) throws ParseException, IOException { JSONParser parser = new JSONParser(); String crawlUrl = "http://apis.daum.net/maps/transcoord?apikey=<KEY>&x="+gym.getMapx()+"&y="+gym.getMapy()+"&fromCoord=KTM&toCoord=WGS84&output=json"; try { JSONObject object = (JSONObject) parser.parse(Jsoup.connect(crawlUrl).ignoreContentType(true).header("Accept-Language", "ko").execute().body()); gym.setLat((Double) object.get("y")); gym.setLon((Double) object.get("x")); } catch (ParseException e) { throw new ParseException(e.getErrorType()); } catch (HttpStatusException e) { throw new HttpStatusException(e.getMessage(), e.getStatusCode(), crawlUrl); } catch (IOException e) { throw new IOException(); } return gym; } public synchronized static String crawlTargetUrl(String url) throws IOException { if(StringUtils.isEmpty(url)) { return ""; } URL obj = null; String returnUrl = null; try { obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setInstanceFollowRedirects(false); returnUrl = conn.getHeaderField("Location"); //TODO www. .com 으로 넘어오는 것들이 있다. 한글이슈 인지 확인하자 if(returnUrl.indexOf(" ") > -1) { return ""; } } catch (MalformedURLException e) { throw new MalformedURLException(e.getMessage()); } catch (IOException e) { throw new IOException(e.getMessage()); } return returnUrl; } }
12,725
0.555269
0.547379
355
35.059155
33.319275
185
false
false
0
0
0
0
0
0
0.574648
false
false
4
edc3d9fb0dd4e9a493f4b80f1731911973d4be0c
5,274,219,882,003
c402e8a34bc2ee8fffb399bd5869e9bb1f9b3f1d
/multiverse-alpha-unborn/src/test/java/org/multiverse/transactional/collections/TransactionalArrayList_addAll2Test.java
6fe44e87a890a1bc01f81b8237ccdce12d041501
[]
no_license
cckmit/multiverse
https://github.com/cckmit/multiverse
c0cf533ce17c3229084de668d17502741e7b4016
94889f9c72bb0be5391685d0fd61e66d74afe842
refs/heads/master
2023-03-17T15:00:58.958000
2011-02-15T21:16:22
2011-02-15T21:16:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.multiverse.transactional.collections; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.multiverse.api.Stm; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.*; import static org.multiverse.api.GlobalStmInstance.getGlobalStmInstance; import static org.multiverse.api.ThreadLocalTransaction.clearThreadLocalTransaction; public class TransactionalArrayList_addAll2Test { private Stm stm; @Before public void setUp() { stm = getGlobalStmInstance(); clearThreadLocalTransaction(); } @Test public void whenCollectionEmpty_thenReturnFalse() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("a", "b"); long version = stm.getVersion(); boolean changed = list.addAll(0, new HashSet<String>()); assertFalse(changed); assertEquals(version, stm.getVersion()); assertEquals(2, list.size()); assertEquals("[a, b]", list.toString()); } @Test public void whenCollectionNull_thenNullPointerException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>(); long version = stm.getVersion(); try { list.addAll(0, null); fail(); } catch (NullPointerException expected) { } assertEquals(version, stm.getVersion()); } @Test public void whenIndexTooSmall_thenIndexOutOfBoundsException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>(); long version = stm.getVersion(); try { list.addAll(-1, new HashSet<String>()); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(version, stm.getVersion()); } @Test public void whenIndexTooBig_thenIndexOutOfBoundsException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("a", "b"); long version = stm.getVersion(); try { list.addAll(3, new HashSet<String>()); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(version, stm.getVersion()); } @Test @Ignore public void whenAddedInFront() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("c", "d"); List<String> items = new LinkedList<String>(); items.add("a"); items.add("b"); list.addAll(0, items); assertEquals("[a, b, c, d]", list.toString()); } @Test @Ignore public void whenAddedToEnd() { } @Test @Ignore public void whenAddedInBetween() { } }
UTF-8
Java
2,760
java
TransactionalArrayList_addAll2Test.java
Java
[]
null
[]
package org.multiverse.transactional.collections; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.multiverse.api.Stm; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.*; import static org.multiverse.api.GlobalStmInstance.getGlobalStmInstance; import static org.multiverse.api.ThreadLocalTransaction.clearThreadLocalTransaction; public class TransactionalArrayList_addAll2Test { private Stm stm; @Before public void setUp() { stm = getGlobalStmInstance(); clearThreadLocalTransaction(); } @Test public void whenCollectionEmpty_thenReturnFalse() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("a", "b"); long version = stm.getVersion(); boolean changed = list.addAll(0, new HashSet<String>()); assertFalse(changed); assertEquals(version, stm.getVersion()); assertEquals(2, list.size()); assertEquals("[a, b]", list.toString()); } @Test public void whenCollectionNull_thenNullPointerException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>(); long version = stm.getVersion(); try { list.addAll(0, null); fail(); } catch (NullPointerException expected) { } assertEquals(version, stm.getVersion()); } @Test public void whenIndexTooSmall_thenIndexOutOfBoundsException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>(); long version = stm.getVersion(); try { list.addAll(-1, new HashSet<String>()); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(version, stm.getVersion()); } @Test public void whenIndexTooBig_thenIndexOutOfBoundsException() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("a", "b"); long version = stm.getVersion(); try { list.addAll(3, new HashSet<String>()); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(version, stm.getVersion()); } @Test @Ignore public void whenAddedInFront() { TransactionalArrayList<String> list = new TransactionalArrayList<String>("c", "d"); List<String> items = new LinkedList<String>(); items.add("a"); items.add("b"); list.addAll(0, items); assertEquals("[a, b, c, d]", list.toString()); } @Test @Ignore public void whenAddedToEnd() { } @Test @Ignore public void whenAddedInBetween() { } }
2,760
0.638406
0.63587
105
25.285715
25.263079
91
false
false
0
0
0
0
0
0
0.580952
false
false
7
981c187bd297b48286648d7a43ff0b0320c33432
11,647,951,342,584
e93322cc5e344686d70126891ed59f591e942770
/src/main/java/com/amp/tms/websocket/SetAgentOfflineJob.java
fac859d3782894575530fc8bb78b3cd780d21b35
[]
no_license
hsleiman/tms2
https://github.com/hsleiman/tms2
ca4a7604d647425072f397081a3337cf2c479491
42c646744a5d913a9aa04261eff3d486e3852ff4
refs/heads/master
2023-01-08T07:07:42.504000
2018-01-18T02:06:41
2018-01-18T02:06:41
116,081,526
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.amp.tms.websocket; import com.objectbrains.scheduler.annotation.QuartzJob; import com.amp.tms.enumerated.SetAgentState; import com.amp.tms.service.TMSAgentService; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; /** * * */ @Deprecated @QuartzJob(name = SetAgentOfflineJob.NAME, durable = false) public class SetAgentOfflineJob extends QuartzJobBean { public static final String NAME = "SetAgentOffline"; @Autowired private TMSAgentService agentService; private Integer ext; public Integer getExt() { return ext; } public void setExt(Integer ext) { this.ext = ext; } public static JobDataMap buildDataMap(Integer ext) { JobDataMap jobData = new JobDataMap(); jobData.putAsString("ext", ext); return jobData; } @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { agentService.setAgentState(ext, SetAgentState.LOGOFF); } }
UTF-8
Java
1,365
java
SetAgentOfflineJob.java
Java
[]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.amp.tms.websocket; import com.objectbrains.scheduler.annotation.QuartzJob; import com.amp.tms.enumerated.SetAgentState; import com.amp.tms.service.TMSAgentService; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; /** * * */ @Deprecated @QuartzJob(name = SetAgentOfflineJob.NAME, durable = false) public class SetAgentOfflineJob extends QuartzJobBean { public static final String NAME = "SetAgentOffline"; @Autowired private TMSAgentService agentService; private Integer ext; public Integer getExt() { return ext; } public void setExt(Integer ext) { this.ext = ext; } public static JobDataMap buildDataMap(Integer ext) { JobDataMap jobData = new JobDataMap(); jobData.putAsString("ext", ext); return jobData; } @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { agentService.setAgentState(ext, SetAgentState.LOGOFF); } }
1,365
0.738462
0.738462
51
25.764706
24.95768
94
false
false
0
0
0
0
0
0
0.470588
false
false
7
4a2de0c12c49be83f7618c7cc443b0cf5140b075
11,647,951,341,106
218850f69459f2cbc4e98eb866948b7815f1b850
/web_analysis/src/main/java/cn/com/pallasli/web/WebProjectConfigInitializer.java
88ff222feb3a8e4c3bc6300782026a41f1cc4f75
[]
no_license
PallasLi/cn.com.pallasli
https://github.com/PallasLi/cn.com.pallasli
fb69ab320aea54a8fc797b853986763e2aa84f09
98c9c7738a04e05021dd14c5695b8956611890b1
refs/heads/master
2019-07-31T20:48:08.442000
2018-05-08T01:38:58
2018-05-08T01:38:58
75,526,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.com.pallasli.web; import cn.com.pallasli.web.config.SpringConfig; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import javax.servlet.ServletContext; /** * Created by lyt1987 on 16/12/7. */ public class WebProjectConfigInitializer{} //public class WebProjectConfigInitializer implements WebApplicationInitializer { // // public void onStartup(ServletContext container) { // // initializeSpringConfig(container); // //// initializeLog4jConfig(container); //// //// initializeSpringMVCConfig(container); //// //// registerServlet(container); //// //// registerListener(container); //// //// registerFilter(container); // } // // private void initializeSpringConfig(ServletContext container) { // // Create the 'root' Spring application context // AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); // rootContext.register(SpringConfig.class); //// ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(rootContext)); //// //配置映射路径 //// servlet.addMapping("/"); //// //启动顺序 //// servlet.setLoadOnStartup(1); // // Manage the life cycle of the root application context // container.addListener(new ContextLoaderListener(rootContext)); // } //// //// private void initializeSpringMVCConfig(ServletContext container) { //// // Create the spring rest servlet's Spring application context //// AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); //// dispatcherContext.register(RestServiceConfiguration.class); //// //// // Register and map the spring rest servlet //// ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc", //// new DispatcherServlet(dispatcherContext)); //// dispatcher.setLoadOnStartup(2); //// dispatcher.setAsyncSupported(true); //// dispatcher.addMapping("/springmvc/*"); //// } //// //// private void initializeLog4jConfig(ServletContext container) { //// // Log4jConfigListener //// container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties"); //// container.addListener(Log4jConfigListener.class); //// PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60); //// } //// //// private void registerServlet(ServletContext container) { //// //// initializeStaggingServlet(container); //// } //// //// private void registerFilter(ServletContext container) { //// initializeSAMLFilter(container); //// } //// //// private void registerListener(ServletContext container) { //// container.addListener(RequestContextListener.class); //// } //// //// private void initializeSAMLFilter(ServletContext container) { //// FilterRegistration.Dynamic filterRegistration = container.addFilter("SAMLFilter", DelegatingFilterProxy.class); //// filterRegistration.addMappingForUrlPatterns(null, false, "/*"); //// filterRegistration.setAsyncSupported(true); //// } //// //// private void initializeStaggingServlet(ServletContext container) { //// StaggingServlet staggingServlet = new StaggingServlet(); //// ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet); //// dynamic.setLoadOnStartup(3); //// dynamic.addMapping("*.stagging"); //// } // //}
UTF-8
Java
3,748
java
WebProjectConfigInitializer.java
Java
[ { "context": "t javax.servlet.ServletContext;\n\n/**\n * Created by lyt1987 on 16/12/7.\n */\npublic class WebProjectConfigInit", "end": 348, "score": 0.9994944930076599, "start": 341, "tag": "USERNAME", "value": "lyt1987" } ]
null
[]
package cn.com.pallasli.web; import cn.com.pallasli.web.config.SpringConfig; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import javax.servlet.ServletContext; /** * Created by lyt1987 on 16/12/7. */ public class WebProjectConfigInitializer{} //public class WebProjectConfigInitializer implements WebApplicationInitializer { // // public void onStartup(ServletContext container) { // // initializeSpringConfig(container); // //// initializeLog4jConfig(container); //// //// initializeSpringMVCConfig(container); //// //// registerServlet(container); //// //// registerListener(container); //// //// registerFilter(container); // } // // private void initializeSpringConfig(ServletContext container) { // // Create the 'root' Spring application context // AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); // rootContext.register(SpringConfig.class); //// ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(rootContext)); //// //配置映射路径 //// servlet.addMapping("/"); //// //启动顺序 //// servlet.setLoadOnStartup(1); // // Manage the life cycle of the root application context // container.addListener(new ContextLoaderListener(rootContext)); // } //// //// private void initializeSpringMVCConfig(ServletContext container) { //// // Create the spring rest servlet's Spring application context //// AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); //// dispatcherContext.register(RestServiceConfiguration.class); //// //// // Register and map the spring rest servlet //// ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc", //// new DispatcherServlet(dispatcherContext)); //// dispatcher.setLoadOnStartup(2); //// dispatcher.setAsyncSupported(true); //// dispatcher.addMapping("/springmvc/*"); //// } //// //// private void initializeLog4jConfig(ServletContext container) { //// // Log4jConfigListener //// container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties"); //// container.addListener(Log4jConfigListener.class); //// PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60); //// } //// //// private void registerServlet(ServletContext container) { //// //// initializeStaggingServlet(container); //// } //// //// private void registerFilter(ServletContext container) { //// initializeSAMLFilter(container); //// } //// //// private void registerListener(ServletContext container) { //// container.addListener(RequestContextListener.class); //// } //// //// private void initializeSAMLFilter(ServletContext container) { //// FilterRegistration.Dynamic filterRegistration = container.addFilter("SAMLFilter", DelegatingFilterProxy.class); //// filterRegistration.addMappingForUrlPatterns(null, false, "/*"); //// filterRegistration.setAsyncSupported(true); //// } //// //// private void initializeStaggingServlet(ServletContext container) { //// StaggingServlet staggingServlet = new StaggingServlet(); //// ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet); //// dynamic.setLoadOnStartup(3); //// dynamic.addMapping("*.stagging"); //// } // //}
3,748
0.688305
0.682672
90
40.422222
33.511185
123
false
false
0
0
0
0
0
0
0.5
false
false
7
6c17298bbec6a3230b4c9e160c300cc14d6ab245
10,118,943,006,818
1a414e46400cd6bf5d0573cff344f934cd757761
/src/main/java/com/silinkeji/mm/exception/PermissionInUseException.java
ba462a49c1dd58bfd9049d6eec2d644bc369c94e
[]
no_license
zinave/merchant
https://github.com/zinave/merchant
dbab54b6086eee2156b1dda27b494be8cb63edbf
ef0b35f372ebbfd17a0e6017514bcee1e98a6269
refs/heads/master
2016-06-03T02:10:28.794000
2015-11-16T08:13:25
2015-11-16T08:13:25
46,173,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.silinkeji.mm.exception; import java.util.Map; public class PermissionInUseException extends BaseException { public static final String code = "406"; private static final long serialVersionUID = 5163941578529215667L; public PermissionInUseException(String identity, Map<String, Object> attrs) { super(code, "权限正在使用中:" + identity, attrs); } public PermissionInUseException(String identity) { super(code, "权限正在使用中:" + identity); } public PermissionInUseException() { super(code, "权限正在使用中"); } }
UTF-8
Java
608
java
PermissionInUseException.java
Java
[]
null
[]
package com.silinkeji.mm.exception; import java.util.Map; public class PermissionInUseException extends BaseException { public static final String code = "406"; private static final long serialVersionUID = 5163941578529215667L; public PermissionInUseException(String identity, Map<String, Object> attrs) { super(code, "权限正在使用中:" + identity, attrs); } public PermissionInUseException(String identity) { super(code, "权限正在使用中:" + identity); } public PermissionInUseException() { super(code, "权限正在使用中"); } }
608
0.701413
0.662544
21
25.952381
26.243322
81
false
false
0
0
0
0
0
0
0.619048
false
false
7
a6629d8a7ff259c27471718c9dc255a02ee0dc84
21,620,865,376,523
9b38e7849f9db885ffc3fce8d1682cb87c01c6ef
/BlackSheep/src/main/java/com/blacksheep/domain/CategoryGender.java
a4238d2e287fd0dfef45b66e1ba63f5d9b1a39aa
[]
no_license
Darwish-md/BlackSheep
https://github.com/Darwish-md/BlackSheep
5312e557008baf9ab853856f869b3de7bd10431e
fa1e9c5de59a1d30cfb66694912699450bbd3da2
refs/heads/main
2023-04-27T23:21:00.978000
2021-05-16T09:07:28
2021-05-16T09:07:28
343,193,620
3
12
null
false
2021-05-11T09:51:19
2021-02-28T19:22:07
2021-05-11T09:17:34
2021-05-11T09:51:19
96,214
1
0
0
Java
false
false
package com.blacksheep.domain; public enum CategoryGender { MEN, WOMEN, KIDS, UNISEX; }
UTF-8
Java
93
java
CategoryGender.java
Java
[]
null
[]
package com.blacksheep.domain; public enum CategoryGender { MEN, WOMEN, KIDS, UNISEX; }
93
0.731183
0.731183
6
14.5
13.865424
30
false
false
0
0
0
0
0
0
1.333333
false
false
7
57b01b9f1380654de12897f6591a0b25403729fd
11,304,353,955,542
49511822fd6e8b20bd8c407cbfafa76ecfb27d63
/src/main/java/config/ConfigUtils.java
9cd9f904dc948bdff03fc447dc7558440c0a5ae3
[]
no_license
bbappyuanyuan/ZKConfig
https://github.com/bbappyuanyuan/ZKConfig
d8a453a2930db90a7835a1ed7859a589b8618438
ee84c40d92bc68efb69549e3b0538fd70ab974b7
refs/heads/master
2016-08-08T07:10:15.031000
2015-05-15T05:15:50
2015-05-15T05:33:01
35,470,532
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package config; import org.apache.commons.lang.WordUtils; /** * @author Zifeng Yuan */ public class ConfigUtils { public static String capitalize(String word) { return WordUtils.capitalize(word); } public static String toVariable(String param) { param = WordUtils.capitalizeFully(param, new char[] {'_'}); param = param.replaceAll("_", ""); return param.substring(0, 1).toLowerCase() + param.substring(1); } }
UTF-8
Java
441
java
ConfigUtils.java
Java
[ { "context": "org.apache.commons.lang.WordUtils;\n\n/**\n * @author Zifeng Yuan\n */\npublic class ConfigUtils {\n\n public static S", "end": 86, "score": 0.9998369216918945, "start": 75, "tag": "NAME", "value": "Zifeng Yuan" } ]
null
[]
package config; import org.apache.commons.lang.WordUtils; /** * @author <NAME> */ public class ConfigUtils { public static String capitalize(String word) { return WordUtils.capitalize(word); } public static String toVariable(String param) { param = WordUtils.capitalizeFully(param, new char[] {'_'}); param = param.replaceAll("_", ""); return param.substring(0, 1).toLowerCase() + param.substring(1); } }
436
0.68254
0.675737
20
21.049999
22.833035
68
false
false
0
0
0
0
0
0
0.45
false
false
7
f2a557c1ff14fafadde49bec89d027910e79d615
4,681,514,393,171
e9a763f7f3a528c40adcd89b214420c46972ce03
/src/main/java/com/browne/spring/configuration/AritConfiguration.java
028dbea09ee3c4d6d5275388c083d00e7a078d16
[]
no_license
Roveros/ARIT-ToBeDeployed
https://github.com/Roveros/ARIT-ToBeDeployed
7899252ebf285e044eb79ab4344f90cee4a80ea2
add004ab2fcb6f01541f1aaed7439d499e2211c2
refs/heads/master
2021-08-30T15:09:23.570000
2017-12-18T11:41:02
2017-12-18T11:41:02
114,634,497
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.browne.spring.configuration; import java.io.IOException; import java.util.Properties; import javax.sql.DataSource; import org.springframework.core.env.Environment; import org.springframework.context.annotation.PropertySource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; /** * This configuration class can be treated as a replacement for * spring-servlet.xml as it contains all the information required for component-scanning and view resolver. * * @Configuration indicates the class contains one or more bean methods annotated * with @Bean producing bean manageable by spring container as an alternative to XML. * * @EnableWebMvc is equivalent to mvc:annotation-driven in XML. * It enables support for @Controller-annotated classes that * use @RequestMapping to map incoming requests to specific method. * * @ComponentScan is equivalent to context:component-scan base-package="..." * providing with where to look for spring managed beans/classes. * * @author Roveros * */ @PropertySource(value = { "classpath:application.properties" }) @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.browne.spring") @Import(value = { LoginSecurityConfig.class }) public class AritConfiguration extends WebMvcConfigurerAdapter { //Used to access values stored in src/main/resources/application.properites @Autowired private Environment environment; //Used to supply the database connection configuration @Autowired DataSource dataSource; /* * UserDetailSevice used to connect to the database to query username and passwords * Sets users authority/role based on query results */ @Bean(name="userDetailsService") public UserDetailsService userDetailsService() { JdbcDaoImpl jdbcImpl = new JdbcDaoImpl(); jdbcImpl.setDataSource(dataSource); jdbcImpl.setUsersByUsernameQuery("select username,password, enabled from users where username=?"); jdbcImpl.setAuthoritiesByUsernameQuery("select username, role from user_roles where username=?"); return jdbcImpl; } //configuration for uploading files @Bean(name="multipartResolver") public CommonsMultipartResolver getResolver() throws IOException{ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); //Set the maximum allowed size (in bytes) for each individual file. resolver.setMaxUploadSize(Integer.valueOf(environment.getRequiredProperty("multipartresolver.maxuploadsize"))); // -1 = No limit return resolver; } //Configuration for a java mail sender @Bean public JavaMailSender getMailSender(){ JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(environment.getRequiredProperty("javamailsender.host")); mailSender.setPort(Integer.valueOf(environment.getRequiredProperty("javamailsender.port"))); mailSender.setUsername(environment.getRequiredProperty("javamailsender.username")); mailSender.setPassword(environment.getRequiredProperty("javamailsender.password")); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.starttls.enable", environment.getRequiredProperty("mail.smtp.starttls.enable")); javaMailProperties.put("mail.smtp.auth", environment.getRequiredProperty("mail.smtp.auth")); javaMailProperties.put("mail.transport.protocol", environment.getRequiredProperty("mail.transport.protocol")); javaMailProperties.put("mail.debug", environment.getRequiredProperty("mail.debug")); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; } /** * This bean acts as an alternative to an XML defined view resolver. * String values for page requests will have the prefix and suffix added * @return viewResolver */ @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } //Will allow for access to messages.properties for validation messages @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } /* * Configure ResourceHandlers to serve static resources like CSS, JS, images etc... */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } }
UTF-8
Java
5,883
java
AritConfiguration.java
Java
[ { "context": "k for spring managed beans/classes.\n * \n * @author Roveros\n *\n */\n@PropertySource(value = { \"classpath:appli", "end": 2125, "score": 0.9967159628868103, "start": 2118, "tag": "NAME", "value": "Roveros" } ]
null
[]
package com.browne.spring.configuration; import java.io.IOException; import java.util.Properties; import javax.sql.DataSource; import org.springframework.core.env.Environment; import org.springframework.context.annotation.PropertySource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; /** * This configuration class can be treated as a replacement for * spring-servlet.xml as it contains all the information required for component-scanning and view resolver. * * @Configuration indicates the class contains one or more bean methods annotated * with @Bean producing bean manageable by spring container as an alternative to XML. * * @EnableWebMvc is equivalent to mvc:annotation-driven in XML. * It enables support for @Controller-annotated classes that * use @RequestMapping to map incoming requests to specific method. * * @ComponentScan is equivalent to context:component-scan base-package="..." * providing with where to look for spring managed beans/classes. * * @author Roveros * */ @PropertySource(value = { "classpath:application.properties" }) @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.browne.spring") @Import(value = { LoginSecurityConfig.class }) public class AritConfiguration extends WebMvcConfigurerAdapter { //Used to access values stored in src/main/resources/application.properites @Autowired private Environment environment; //Used to supply the database connection configuration @Autowired DataSource dataSource; /* * UserDetailSevice used to connect to the database to query username and passwords * Sets users authority/role based on query results */ @Bean(name="userDetailsService") public UserDetailsService userDetailsService() { JdbcDaoImpl jdbcImpl = new JdbcDaoImpl(); jdbcImpl.setDataSource(dataSource); jdbcImpl.setUsersByUsernameQuery("select username,password, enabled from users where username=?"); jdbcImpl.setAuthoritiesByUsernameQuery("select username, role from user_roles where username=?"); return jdbcImpl; } //configuration for uploading files @Bean(name="multipartResolver") public CommonsMultipartResolver getResolver() throws IOException{ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); //Set the maximum allowed size (in bytes) for each individual file. resolver.setMaxUploadSize(Integer.valueOf(environment.getRequiredProperty("multipartresolver.maxuploadsize"))); // -1 = No limit return resolver; } //Configuration for a java mail sender @Bean public JavaMailSender getMailSender(){ JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(environment.getRequiredProperty("javamailsender.host")); mailSender.setPort(Integer.valueOf(environment.getRequiredProperty("javamailsender.port"))); mailSender.setUsername(environment.getRequiredProperty("javamailsender.username")); mailSender.setPassword(environment.getRequiredProperty("javamailsender.password")); Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.starttls.enable", environment.getRequiredProperty("mail.smtp.starttls.enable")); javaMailProperties.put("mail.smtp.auth", environment.getRequiredProperty("mail.smtp.auth")); javaMailProperties.put("mail.transport.protocol", environment.getRequiredProperty("mail.transport.protocol")); javaMailProperties.put("mail.debug", environment.getRequiredProperty("mail.debug")); mailSender.setJavaMailProperties(javaMailProperties); return mailSender; } /** * This bean acts as an alternative to an XML defined view resolver. * String values for page requests will have the prefix and suffix added * @return viewResolver */ @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } //Will allow for access to messages.properties for validation messages @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } /* * Configure ResourceHandlers to serve static resources like CSS, JS, images etc... */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } }
5,883
0.770015
0.769845
136
42.257355
33.808933
136
false
false
0
0
0
0
0
0
0.772059
false
false
7
a1cd70f9f7300e5eabbfdcfe5e0174a0d5adba2b
1,297,080,176,335
f923ab9350a358ecaacfd7b63c86b9aa77c25c42
/src/test/java/models/TVsTest 2.java
082c4431738ccc39805b3be8407f145619b50b87
[]
no_license
apphow/Product-Inventory-Lab
https://github.com/apphow/Product-Inventory-Lab
e8c1f55f5b2472b21a7bfd6adadfedf238ff6457
6e3d35a3eb9afed27befd60d5e76673b6ff6faf4
refs/heads/master
2021-01-08T01:43:47.623000
2020-02-23T05:38:49
2020-02-23T05:38:49
241,876,513
0
0
null
true
2020-02-23T06:01:15
2020-02-20T12:18:21
2020-02-20T12:18:23
2020-02-23T06:01:14
34
0
0
0
null
false
false
package models; //public class TVsTest { //}
UTF-8
Java
46
java
TVsTest 2.java
Java
[]
null
[]
package models; //public class TVsTest { //}
46
0.673913
0.673913
4
10.5
9.604687
24
false
false
0
0
0
0
0
0
0.25
false
false
7
1ecc6df33be20b72d1870e67ba23ed1833a908ca
10,299,331,609,290
ee7a3ec227e182c0ef2ab9b849a6f81247f11732
/lywsj/src/BackGroundPane.java
ae89f25dce264107a810ab2861556a8c42dbfb71
[]
no_license
wxshaodw/lyw
https://github.com/wxshaodw/lyw
b20cf6905125a15caeb044baf4292a869713a07a
9b39167f80fccd8e1ebc52f483060bb29bb357d4
refs/heads/master
2021-04-28T23:48:24.517000
2017-08-12T07:59:55
2017-08-12T07:59:55
77,725,708
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JPanel; public class BackGroundPane extends JPanel { BufferedImage img = null; protected void paintComponent(Graphics g) { try { img = ImageIO.read(new File("./img/±³¾°.jpg")); if(img != null) g.drawImage(img, 0, 0, null); } catch (Exception e) { e.printStackTrace(); } } }
WINDOWS-1252
Java
459
java
BackGroundPane.java
Java
[]
null
[]
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JPanel; public class BackGroundPane extends JPanel { BufferedImage img = null; protected void paintComponent(Graphics g) { try { img = ImageIO.read(new File("./img/±³¾°.jpg")); if(img != null) g.drawImage(img, 0, 0, null); } catch (Exception e) { e.printStackTrace(); } } }
459
0.659341
0.650549
20
20.65
15.793274
50
false
false
0
0
0
0
0
0
1.75
false
false
7
8ee2ef964d9f6ff5697bbfdec85cd409c55f6acc
25,288,767,441,500
468c1ffe8fa8bc8aaa546d3343885dbd801bf58f
/src/constants/ApplicationConstants.java
f07bb56536ffe6fc60d4ff2df2a9b9b14be13658
[]
no_license
MariusDurbala/Hangman
https://github.com/MariusDurbala/Hangman
c191173e817cbdc991a9e88184474fd7a7beedd0
9ac7d7ab0a304f4e50c80abc9c897125a174d66b
refs/heads/master
2020-05-09T13:31:36.527000
2019-04-14T13:01:23
2019-04-14T13:01:23
181,155,465
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package constants; public class ApplicationConstants { public static final String BTN_LOGIN_TEXT = "Login"; public static final String BTN_LOGOUT_TEXT = "Logout"; public static final String USERNAME = "admin"; public static final String PASSWORD = "admin"; public static final String APP_FOLDER_DATA_PATH = "C:\\Users\\Public\\Documents\\hangman"; public static final String CATEGORIES_FOLDER_NAME = "categories"; public static final String CATEGORY_FILE_EXTENSION = ".txt"; public static final String WORD_SEPARATOR_IN_CATEGORY_ENTRY=";"; }
UTF-8
Java
576
java
ApplicationConstants.java
Java
[ { "context": "gout\";\n public static final String USERNAME = \"admin\";\n public static final String PASSWORD = \"admi", "end": 220, "score": 0.9989728331565857, "start": 215, "tag": "USERNAME", "value": "admin" }, { "context": "dmin\";\n public static final String PASSWORD = \"admin\";\n\n public static final String APP_FOLDER_DATA", "end": 271, "score": 0.9990018010139465, "start": 266, "tag": "PASSWORD", "value": "admin" } ]
null
[]
package constants; public class ApplicationConstants { public static final String BTN_LOGIN_TEXT = "Login"; public static final String BTN_LOGOUT_TEXT = "Logout"; public static final String USERNAME = "admin"; public static final String PASSWORD = "<PASSWORD>"; public static final String APP_FOLDER_DATA_PATH = "C:\\Users\\Public\\Documents\\hangman"; public static final String CATEGORIES_FOLDER_NAME = "categories"; public static final String CATEGORY_FILE_EXTENSION = ".txt"; public static final String WORD_SEPARATOR_IN_CATEGORY_ENTRY=";"; }
581
0.729167
0.729167
13
43.307693
29.068579
94
false
false
0
0
0
0
0
0
0.769231
false
false
7
3e8d64da9f868e0763f48ff9795c800aacdef36c
14,620,068,723,946
be42c5b37a5875663d5b86cee0ee94026d4be3bd
/review/src/main/java/com/udacity/jwdnd/c1/review/controller/ChatController.java
81a078c93fc251327e7bc1a5feff3d260b2bc20a
[]
no_license
kevinmanuellee/udacity
https://github.com/kevinmanuellee/udacity
3bbe9bf6fe3b9fb5ed893a5137215e93797b36a4
31fa1cb6f97c1e1074d1554e09b85d9ccfe92d63
refs/heads/master
2023-02-26T23:48:25.380000
2021-02-04T15:58:48
2021-02-04T15:58:48
320,531,972
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.udacity.jwdnd.c1.review.controller; import com.udacity.jwdnd.c1.review.model.ChatForm; import com.udacity.jwdnd.c1.review.model.ChatMessage; import com.udacity.jwdnd.c1.review.model.User; import com.udacity.jwdnd.c1.review.service.MessageService; import com.udacity.jwdnd.c1.review.service.UserService; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.PostConstruct; import java.util.List; @Controller @RequestMapping("/chat") public class ChatController { private MessageService messageService; public ChatController(MessageService messageService, UserService userService) { this.messageService = messageService; } @GetMapping public String getMessageList(Model model, ChatForm chatForm){ model.addAttribute("chatMessages", this.messageService.getChatMessages()); return "chat"; } @PostMapping public String postChatMessage(Model model, ChatForm chatForm, Authentication authentication){ chatForm.setUsername(authentication.getPrincipal().toString()); System.out.println("CHAT FORM = " + chatForm.getUsername()); this.messageService.addMessage(chatForm); chatForm.setMessageText(""); model.addAttribute("chatMessages", this.messageService.getChatMessages()); return "chat"; } @ModelAttribute("allMessageTypes") public String[] allMessageTypes(){ return new String[] {"Say", "Shout", "Whisper"}; } }
UTF-8
Java
1,813
java
ChatController.java
Java
[]
null
[]
package com.udacity.jwdnd.c1.review.controller; import com.udacity.jwdnd.c1.review.model.ChatForm; import com.udacity.jwdnd.c1.review.model.ChatMessage; import com.udacity.jwdnd.c1.review.model.User; import com.udacity.jwdnd.c1.review.service.MessageService; import com.udacity.jwdnd.c1.review.service.UserService; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.PostConstruct; import java.util.List; @Controller @RequestMapping("/chat") public class ChatController { private MessageService messageService; public ChatController(MessageService messageService, UserService userService) { this.messageService = messageService; } @GetMapping public String getMessageList(Model model, ChatForm chatForm){ model.addAttribute("chatMessages", this.messageService.getChatMessages()); return "chat"; } @PostMapping public String postChatMessage(Model model, ChatForm chatForm, Authentication authentication){ chatForm.setUsername(authentication.getPrincipal().toString()); System.out.println("CHAT FORM = " + chatForm.getUsername()); this.messageService.addMessage(chatForm); chatForm.setMessageText(""); model.addAttribute("chatMessages", this.messageService.getChatMessages()); return "chat"; } @ModelAttribute("allMessageTypes") public String[] allMessageTypes(){ return new String[] {"Say", "Shout", "Whisper"}; } }
1,813
0.761169
0.75786
50
35.259998
27.345062
97
false
false
0
0
0
0
0
0
0.68
false
false
7
7ab4a36c35923246dd156b476ab6995c21f071de
20,126,216,798,701
4115d8855e3bba4d2fa8ed7393211b5501bccad8
/ejb/src/main/java/com/progenso/desma/entities/mdata/MachineSql.java
00671d73e9805f471874f7baf226f0eef38547ba
[]
no_license
7orcas/desma
https://github.com/7orcas/desma
ac672ce7563cad3b01e660ace6ffb80e08d8f60d
870d752e7b3b38968a06344595a54ffb2a08911a
refs/heads/master
2015-08-12T22:23:44.952000
2015-08-06T16:01:20
2015-08-06T16:01:20
22,788,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.progenso.desma.entities.mdata; import org.codehaus.jackson.annotate.JsonIgnore; import com.progenso.desma.app.entities.sql.BaseSql; import com.progenso.desma.entities.app.UserParam; import com.progenso.desma.interfaces.rest.BaseRest; /** * Machine sql search object * * [License] * @author John Stewart */ @SuppressWarnings("serial") public class MachineSql extends BaseSql{ @JsonIgnore private String ttMachine; @JsonIgnore private String ttMachineShift; @JsonIgnore private String ttMachineAttribute; @JsonIgnore private String ttShift; /** * JSON string constructor * @param String JSON object */ public MachineSql(String json) throws Exception{ BaseRest.deserializeJson(this, json); } /** * Constructor for user params */ public MachineSql(UserParam params) { super(params); } /** * Constructor for another sql object * @param BaseSql sql */ public MachineSql(BaseSql sql) { super(sql); } //////////////////////// Methods ////////////////////////////////////////////////// /** * Convenience method to set active only flag * @return this object */ @JsonIgnore public MachineSql setActiveOnly() { this.activeOnly = true; return this; } //////////////////////// Getters / Setters ////////////////////////////////////////////////// @JsonIgnore public String getTempTableMachine() { return ttMachine; } public void setTempTableMachine(String ttMachine) { this.ttMachine = ttMachine; } @JsonIgnore public String getTempTableMachineShift() { return ttMachineShift; } public void setTempTableMachineShift(String ttMachineShift) { this.ttMachineShift = ttMachineShift; } @JsonIgnore public String getTempTableMachineAttribute() { return ttMachineAttribute; } public void setTempTableMachineAttribute(String ttMachineAttribute) { this.ttMachineAttribute = ttMachineAttribute; } @JsonIgnore public String getTempTableShift() { return ttShift; } public void setTempTableShift(String ttShift) { this.ttShift = ttShift; } }
UTF-8
Java
2,160
java
MachineSql.java
Java
[ { "context": "ine sql search object\n * \n * [License] \n * @author John Stewart\n */\n@SuppressWarnings(\"serial\")\npublic class Mach", "end": 323, "score": 0.9998217225074768, "start": 311, "tag": "NAME", "value": "John Stewart" } ]
null
[]
package com.progenso.desma.entities.mdata; import org.codehaus.jackson.annotate.JsonIgnore; import com.progenso.desma.app.entities.sql.BaseSql; import com.progenso.desma.entities.app.UserParam; import com.progenso.desma.interfaces.rest.BaseRest; /** * Machine sql search object * * [License] * @author <NAME> */ @SuppressWarnings("serial") public class MachineSql extends BaseSql{ @JsonIgnore private String ttMachine; @JsonIgnore private String ttMachineShift; @JsonIgnore private String ttMachineAttribute; @JsonIgnore private String ttShift; /** * JSON string constructor * @param String JSON object */ public MachineSql(String json) throws Exception{ BaseRest.deserializeJson(this, json); } /** * Constructor for user params */ public MachineSql(UserParam params) { super(params); } /** * Constructor for another sql object * @param BaseSql sql */ public MachineSql(BaseSql sql) { super(sql); } //////////////////////// Methods ////////////////////////////////////////////////// /** * Convenience method to set active only flag * @return this object */ @JsonIgnore public MachineSql setActiveOnly() { this.activeOnly = true; return this; } //////////////////////// Getters / Setters ////////////////////////////////////////////////// @JsonIgnore public String getTempTableMachine() { return ttMachine; } public void setTempTableMachine(String ttMachine) { this.ttMachine = ttMachine; } @JsonIgnore public String getTempTableMachineShift() { return ttMachineShift; } public void setTempTableMachineShift(String ttMachineShift) { this.ttMachineShift = ttMachineShift; } @JsonIgnore public String getTempTableMachineAttribute() { return ttMachineAttribute; } public void setTempTableMachineAttribute(String ttMachineAttribute) { this.ttMachineAttribute = ttMachineAttribute; } @JsonIgnore public String getTempTableShift() { return ttShift; } public void setTempTableShift(String ttShift) { this.ttShift = ttShift; } }
2,154
0.652315
0.652315
97
21.268042
21.439686
94
false
false
0
0
0
0
0
0
0.814433
false
false
7
45ad7852bab08192ceb8afaa18c7b571309e5323
30,193,620,134,572
0d1538a2b5ab33be922a9b20c3a9534ec6dfe9ba
/src/main/java/com/mycompany/utils/ConfigurationLookUp.java
39374692306023eef585e92505bf81a5717f9d95
[]
no_license
BlueJRepo/mulesoft-api
https://github.com/BlueJRepo/mulesoft-api
0dfd07f6b4669899658b6222b2d7f542ea4606ef
c6fe300199bd2cfc93c4dc4b4ca1f0a90ceee07c
refs/heads/master
2020-06-07T05:14:57.989000
2019-07-14T13:33:14
2019-07-14T13:33:14
192,933,272
0
0
null
false
2020-10-13T14:05:55
2019-06-20T14:19:21
2019-07-14T13:33:24
2020-10-13T14:05:53
111
0
0
1
RAML
false
false
package com.mycompany.utils; import java.util.ArrayList; import java.util.List; import com.mycompany.model.Address; public class ConfigurationLookUp { public static List<Address> retrieve(String configName) { List<Address> addresses = new ArrayList<Address>(); for(int i=0; i <= 100000; i++) { Address address = new Address(); address.setAddressId(i); address.setStreetAddress("some_streetAddress_" + i); address.setCity("some_city_" + i); address.setState("some_state_" + i); address.setZipCode("some_zipCode_" + i); address.setAddressType("some_billing_" + i); addresses.add(address); } return addresses; } }
UTF-8
Java
659
java
ConfigurationLookUp.java
Java
[]
null
[]
package com.mycompany.utils; import java.util.ArrayList; import java.util.List; import com.mycompany.model.Address; public class ConfigurationLookUp { public static List<Address> retrieve(String configName) { List<Address> addresses = new ArrayList<Address>(); for(int i=0; i <= 100000; i++) { Address address = new Address(); address.setAddressId(i); address.setStreetAddress("some_streetAddress_" + i); address.setCity("some_city_" + i); address.setState("some_state_" + i); address.setZipCode("some_zipCode_" + i); address.setAddressType("some_billing_" + i); addresses.add(address); } return addresses; } }
659
0.691958
0.681335
28
22.535715
19.343662
58
false
false
0
0
0
0
0
0
2
false
false
7
ad0d0c51f89b774992849e1980180ede8dbd232b
12,850,542,195,236
8cfbc97c64e6f423f5b0052d1b9c84fdc4217755
/src/main/java/com/fsy/po/SysSession.java
e0668675c46170696ef0ead2a39cc33b0560ae6e
[]
no_license
nengbowan/mybatisEntity2Sql
https://github.com/nengbowan/mybatisEntity2Sql
f4f7344471420071bf41772df14a0aafdbdee368
6b215258e3e55f4535ee9d6446aff726325ed26f
refs/heads/master
2021-06-24T21:36:25.642000
2019-12-02T03:55:31
2019-12-02T03:55:31
225,281,234
0
0
null
false
2021-04-22T18:47:57
2019-12-02T03:55:19
2020-09-08T20:32:53
2021-04-22T18:47:56
27
0
0
1
Java
false
false
package com.fsy.po; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; /** * <p> * * </p> * * @author haha * @since 2018-11-01 */ @TableName("sys_session") @SuppressWarnings("serial") public class SysSession extends BaseModel { @TableField("session_id") private String sessionId; private String account; private String ip; @TableField("start_time") private Date startTime; private Integer enable; private String remark; public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
UTF-8
Java
1,419
java
SysSession.java
Java
[ { "context": "a.util.Date;\n\n\n/**\n * <p>\n *\n * </p>\n *\n * @author haha\n * @since 2018-11-01\n */\n@TableName(\"sys_session\"", "end": 199, "score": 0.999512791633606, "start": 195, "tag": "USERNAME", "value": "haha" } ]
null
[]
package com.fsy.po; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.annotations.TableName; import java.util.Date; /** * <p> * * </p> * * @author haha * @since 2018-11-01 */ @TableName("sys_session") @SuppressWarnings("serial") public class SysSession extends BaseModel { @TableField("session_id") private String sessionId; private String account; private String ip; @TableField("start_time") private Date startTime; private Integer enable; private String remark; public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
1,419
0.622269
0.616631
80
16.75
15.850473
55
false
false
0
0
0
0
0
0
0.275
false
false
7
a1b956170020128ed952099a9f16776e6a454a04
14,817,637,216,361
443a711eb159441ec2a95c5088453225e8c85c91
/jdoa/src/main/java/com/study/model/mdao/ILoginMapper.java
1226e8489da0ecae52d581709291d514d2bb3c8a
[ "LicenseRef-scancode-mulanpsl-1.0-en", "MulanPSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wsw1254961594/zsyjdxm
https://github.com/wsw1254961594/zsyjdxm
cf970221f20818ddb4e35dceb1cfd8961124af50
72bd852f2a147a8f443b1766a3f4ed3ed48a8c46
refs/heads/master
2023-02-06T18:07:00.680000
2020-12-24T14:06:01
2020-12-24T14:06:01
323,257,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.study.model.mdao; import com.study.pojo.Emp; import org.springframework.stereotype.Repository; /** * @author: pengjia * @date: 2020/12/21 * @description: */ @Repository public interface ILoginMapper { Emp login(String ename); }
UTF-8
Java
250
java
ILoginMapper.java
Java
[ { "context": "gframework.stereotype.Repository;\n\n/**\n * @author: pengjia\n * @date: 2020/12/21\n * @description:\n */\n@Reposi", "end": 132, "score": 0.993479311466217, "start": 125, "tag": "USERNAME", "value": "pengjia" } ]
null
[]
package com.study.model.mdao; import com.study.pojo.Emp; import org.springframework.stereotype.Repository; /** * @author: pengjia * @date: 2020/12/21 * @description: */ @Repository public interface ILoginMapper { Emp login(String ename); }
250
0.724
0.692
14
16.857143
14.24709
49
false
false
0
0
0
0
0
0
0.285714
false
false
7
e21e95dcb03d0b4879aeadb68fd2c20a678f5124
1,219,770,767,810
f6899a2cf1c10a724632bbb2ccffb7283c77a5ff
/hibernate-core/5.2.15/src/main/java/org/hibernate/mapping/Set.java
1bb5a4dd6a55c77c77040440e7f8ce452b736371
[]
no_license
Appdynamics/OSS
https://github.com/Appdynamics/OSS
a8903058e29f4783e34119a4d87639f508a63692
1e112f8854a25b3ecf337cad6eccf7c85e732525
refs/heads/master
2023-07-22T03:34:54.770000
2021-10-28T07:01:57
2021-10-28T07:01:57
19,390,624
2
13
null
false
2023-07-08T02:26:33
2014-05-02T22:42:20
2021-10-28T07:02:10
2023-07-08T02:26:26
629,110
1
4
222
null
false
false
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.mapping; import java.util.Iterator; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.engine.spi.Mapping; import org.hibernate.type.CollectionType; /** * A set with no nullable element columns. It will have a primary key * consisting of all table columns (ie. key columns + element columns). * @author Gavin King */ public class Set extends Collection { public Set(MetadataImplementor metadata, PersistentClass owner) { super( metadata, owner ); } public void validate(Mapping mapping) throws MappingException { super.validate( mapping ); //for backward compatibility, disable this: /*Iterator iter = getElement().getColumnIterator(); while ( iter.hasNext() ) { Column col = (Column) iter.next(); if ( !col.isNullable() ) { return; } } throw new MappingException("set element mappings must have at least one non-nullable column: " + getRole() );*/ } public boolean isSet() { return true; } public CollectionType getDefaultCollectionType() { if ( isSorted() ) { return getMetadata().getTypeResolver() .getTypeFactory() .sortedSet( getRole(), getReferencedPropertyName(), getComparator() ); } else if ( hasOrder() ) { return getMetadata().getTypeResolver() .getTypeFactory() .orderedSet( getRole(), getReferencedPropertyName() ); } else { return getMetadata().getTypeResolver() .getTypeFactory() .set( getRole(), getReferencedPropertyName() ); } } void createPrimaryKey() { if ( !isOneToMany() ) { PrimaryKey pk = new PrimaryKey( getCollectionTable() ); pk.addColumns( getKey().getColumnIterator() ); Iterator iter = getElement().getColumnIterator(); while ( iter.hasNext() ) { Object selectable = iter.next(); if ( selectable instanceof Column ) { Column col = (Column) selectable; if ( !col.isNullable() ) { pk.addColumn( col ); } else { return; } } } if ( pk.getColumnSpan() == getKey().getColumnSpan() ) { //for backward compatibility, allow a set with no not-null //element columns, using all columns in the row locater SQL //TODO: create an implicit not null constraint on all cols? } else { getCollectionTable().setPrimaryKey( pk ); } } else { //create an index on the key columns?? } } public Object accept(ValueVisitor visitor) { return visitor.accept(this); } }
UTF-8
Java
2,699
java
Set.java
Java
[ { "context": "ns (ie. key columns + element columns).\n * @author Gavin King\n */\npublic class Set extends Collection {\n\tpublic", "end": 638, "score": 0.9996326565742493, "start": 628, "tag": "NAME", "value": "Gavin King" } ]
null
[]
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.mapping; import java.util.Iterator; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.engine.spi.Mapping; import org.hibernate.type.CollectionType; /** * A set with no nullable element columns. It will have a primary key * consisting of all table columns (ie. key columns + element columns). * @author <NAME> */ public class Set extends Collection { public Set(MetadataImplementor metadata, PersistentClass owner) { super( metadata, owner ); } public void validate(Mapping mapping) throws MappingException { super.validate( mapping ); //for backward compatibility, disable this: /*Iterator iter = getElement().getColumnIterator(); while ( iter.hasNext() ) { Column col = (Column) iter.next(); if ( !col.isNullable() ) { return; } } throw new MappingException("set element mappings must have at least one non-nullable column: " + getRole() );*/ } public boolean isSet() { return true; } public CollectionType getDefaultCollectionType() { if ( isSorted() ) { return getMetadata().getTypeResolver() .getTypeFactory() .sortedSet( getRole(), getReferencedPropertyName(), getComparator() ); } else if ( hasOrder() ) { return getMetadata().getTypeResolver() .getTypeFactory() .orderedSet( getRole(), getReferencedPropertyName() ); } else { return getMetadata().getTypeResolver() .getTypeFactory() .set( getRole(), getReferencedPropertyName() ); } } void createPrimaryKey() { if ( !isOneToMany() ) { PrimaryKey pk = new PrimaryKey( getCollectionTable() ); pk.addColumns( getKey().getColumnIterator() ); Iterator iter = getElement().getColumnIterator(); while ( iter.hasNext() ) { Object selectable = iter.next(); if ( selectable instanceof Column ) { Column col = (Column) selectable; if ( !col.isNullable() ) { pk.addColumn( col ); } else { return; } } } if ( pk.getColumnSpan() == getKey().getColumnSpan() ) { //for backward compatibility, allow a set with no not-null //element columns, using all columns in the row locater SQL //TODO: create an implicit not null constraint on all cols? } else { getCollectionTable().setPrimaryKey( pk ); } } else { //create an index on the key columns?? } } public Object accept(ValueVisitor visitor) { return visitor.accept(this); } }
2,695
0.681363
0.679881
95
27.410526
24.977673
113
false
false
0
0
0
0
0
0
2.452631
false
false
7
8b20deb2191ac77468df6a5d3766f40888d13d19
2,491,081,081,274
bad44a3b672dd0386778ca2564bc5d8146c66edf
/src/main/java/com/leaf/sevice/TInfoService.java
0bfce6c96be33ebf3d8c638cf783ff4c0a866d37
[]
no_license
1234sfg/idea-demo
https://github.com/1234sfg/idea-demo
b949980559bad93c36c69ebaffdf00be3bdf2fe6
83a1fce584453bc6d8f917a49c96e035ce1b775c
refs/heads/master
2022-12-28T17:42:21.923000
2020-10-12T05:43:02
2020-10-12T05:43:02
303,293,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leaf.sevice; import com.github.pagehelper.Page; import com.leaf.model.TInfo; import java.util.List; import java.util.Map; public interface TInfoService { Integer saveTInfo(TInfo tInfo); Integer updateTInfo(TInfo tInfo); Integer deleteTInfo(Integer id); List<TInfo> getTInfoList(); List<TInfo> getTInfosBySome(String some); List<TInfo> getTInfosLimit(Integer currPage, Integer pageSize); Page<Map<String, Object>> getTInfoAndProductLimit(Integer currPage, Integer pageSize); }
UTF-8
Java
528
java
TInfoService.java
Java
[]
null
[]
package com.leaf.sevice; import com.github.pagehelper.Page; import com.leaf.model.TInfo; import java.util.List; import java.util.Map; public interface TInfoService { Integer saveTInfo(TInfo tInfo); Integer updateTInfo(TInfo tInfo); Integer deleteTInfo(Integer id); List<TInfo> getTInfoList(); List<TInfo> getTInfosBySome(String some); List<TInfo> getTInfosLimit(Integer currPage, Integer pageSize); Page<Map<String, Object>> getTInfoAndProductLimit(Integer currPage, Integer pageSize); }
528
0.748106
0.748106
26
19.307692
23.349796
90
false
false
0
0
0
0
0
0
0.576923
false
false
7
4262e1466c0046bea869548757ca1070989b0921
17,231,408,840,187
037c400eeba54fb6bda1509afe18b9402f362724
/app/controllers/SuggestionsController.java
40e58408eb648062bb27f6cc3312e6896c256ce4
[ "Apache-2.0" ]
permissive
ebar0n/SC-Routes-AppWeb
https://github.com/ebar0n/SC-Routes-AppWeb
e436444e63149260967e44348226f4c4b3b27329
f2916444dbf6b0ec493dde922373d1fb074a1ce1
refs/heads/master
2021-01-01T04:19:54.555000
2016-05-11T16:58:37
2016-05-11T16:58:37
58,412,532
0
0
null
false
2016-05-10T16:18:30
2016-05-09T22:37:21
2016-05-09T23:29:15
2016-05-10T16:18:30
7,051
0
0
0
Java
null
null
package controllers; import be.objectify.deadbolt.java.actions.Group; import be.objectify.deadbolt.java.actions.Restrict; import com.feth.play.module.pa.PlayAuthenticate; import models.User; import models.Suggestions; import models.Company; import play.Routes; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import providers.MyUsernamePasswordAuthProvider; import providers.MyUsernamePasswordAuthProvider.MyLogin; import providers.MyUsernamePasswordAuthProvider.MySignup; import service.UserProvider; import views.html.*; import views.formdata.SuggestionsFormData; import javax.inject.Inject; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class SuggestionsController extends Controller { public static final String FLASH_MESSAGE_KEY = "message"; public static final String FLASH_ERROR_KEY = "error"; public static final String USER_ROLE = "user"; private final PlayAuthenticate auth; private final MyUsernamePasswordAuthProvider provider; private final UserProvider userProvider; public static String formatTimestamp(final long t) { return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t)); } @Inject public SuggestionsController(final PlayAuthenticate auth, final MyUsernamePasswordAuthProvider provider, final UserProvider userProvider) { this.auth = auth; this.provider = provider; this.userProvider = userProvider; } public Result index() { SuggestionsFormData suggestionsData = new SuggestionsFormData(); Form<SuggestionsFormData> formData = Form.form(SuggestionsFormData.class).fill(suggestionsData); List<Company> companies = Company.find.all(); companies.add(0, new Company()); return ok(suggestions_index.render(this.userProvider, formData, companies)); } public Result submit() { Form<SuggestionsFormData> filledForm = Form.form(SuggestionsFormData.class).bindFromRequest(); if (filledForm.hasErrors()) { List<Company> companies = Company.find.all(); companies.add(0, new Company()); flash("error", "Please correct errors above."); return badRequest(suggestions_index.render(this.userProvider, filledForm, companies)); } else { Suggestions suggestions = Suggestions.makeInstance(filledForm.get()); flash("success", "Suggestions instance created: " + suggestions); return redirect(routes.Application.index()); } } @Restrict(@Group(SuggestionsController.USER_ROLE)) public Result list() { List<Suggestions> suggestionss = Suggestions.find.all(); return ok(suggestions_list.render(this.userProvider, suggestionss)); } }
UTF-8
Java
2,614
java
SuggestionsController.java
Java
[]
null
[]
package controllers; import be.objectify.deadbolt.java.actions.Group; import be.objectify.deadbolt.java.actions.Restrict; import com.feth.play.module.pa.PlayAuthenticate; import models.User; import models.Suggestions; import models.Company; import play.Routes; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import providers.MyUsernamePasswordAuthProvider; import providers.MyUsernamePasswordAuthProvider.MyLogin; import providers.MyUsernamePasswordAuthProvider.MySignup; import service.UserProvider; import views.html.*; import views.formdata.SuggestionsFormData; import javax.inject.Inject; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class SuggestionsController extends Controller { public static final String FLASH_MESSAGE_KEY = "message"; public static final String FLASH_ERROR_KEY = "error"; public static final String USER_ROLE = "user"; private final PlayAuthenticate auth; private final MyUsernamePasswordAuthProvider provider; private final UserProvider userProvider; public static String formatTimestamp(final long t) { return new SimpleDateFormat("yyyy-dd-MM HH:mm:ss").format(new Date(t)); } @Inject public SuggestionsController(final PlayAuthenticate auth, final MyUsernamePasswordAuthProvider provider, final UserProvider userProvider) { this.auth = auth; this.provider = provider; this.userProvider = userProvider; } public Result index() { SuggestionsFormData suggestionsData = new SuggestionsFormData(); Form<SuggestionsFormData> formData = Form.form(SuggestionsFormData.class).fill(suggestionsData); List<Company> companies = Company.find.all(); companies.add(0, new Company()); return ok(suggestions_index.render(this.userProvider, formData, companies)); } public Result submit() { Form<SuggestionsFormData> filledForm = Form.form(SuggestionsFormData.class).bindFromRequest(); if (filledForm.hasErrors()) { List<Company> companies = Company.find.all(); companies.add(0, new Company()); flash("error", "Please correct errors above."); return badRequest(suggestions_index.render(this.userProvider, filledForm, companies)); } else { Suggestions suggestions = Suggestions.makeInstance(filledForm.get()); flash("success", "Suggestions instance created: " + suggestions); return redirect(routes.Application.index()); } } @Restrict(@Group(SuggestionsController.USER_ROLE)) public Result list() { List<Suggestions> suggestionss = Suggestions.find.all(); return ok(suggestions_list.render(this.userProvider, suggestionss)); } }
2,614
0.778118
0.777353
77
32.96104
27.218903
105
false
false
0
0
0
0
0
0
1.649351
false
false
7
a400bc4dae6dec1bde4f754307589432bf405354
22,479,858,830,325
79dde9dd471aae1e4cfb6379d4c8f71ff629c10f
/bkup/goaamigo/Traveller/trip/view/component/TripResultsFragment.java
19ee9e235c48d7e24421892053a19393f11c6e28
[]
no_license
shreyas-paranjape/android
https://github.com/shreyas-paranjape/android
e384abe5169b8a09c86e4c61c2549a5f41339e81
8b131ce9a439667cdb468c917cc95bab0b2ef6a8
refs/heads/master
2021-01-10T03:17:29.540000
2016-01-04T08:47:46
2016-01-04T08:47:46
44,361,470
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.goaamigo.traveller.module.trip.view.component; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import model.trip.Trip; import com.goaamigo.traveller.R; import com.goaamigo.traveller.module.trip.view.adapter.TripRVAdapter; import java.util.ArrayList; import java.util.List; public class TripResultsFragment extends Fragment { List<Trip> list; TripRVAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getActivity().setTitle("Trip results"); View v = inflater.inflate(R.layout.fragment_trip_result, container, false); initView(v); return v; } private void initView(View v) { list = new ArrayList<>(); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv); rv.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); rv.setLayoutManager(llm); adapter = new TripRVAdapter(list, getActivity()); rv.setAdapter(adapter); } }
UTF-8
Java
1,544
java
TripResultsFragment.java
Java
[]
null
[]
package com.goaamigo.traveller.module.trip.view.component; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import model.trip.Trip; import com.goaamigo.traveller.R; import com.goaamigo.traveller.module.trip.view.adapter.TripRVAdapter; import java.util.ArrayList; import java.util.List; public class TripResultsFragment extends Fragment { List<Trip> list; TripRVAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getActivity().setTitle("Trip results"); View v = inflater.inflate(R.layout.fragment_trip_result, container, false); initView(v); return v; } private void initView(View v) { list = new ArrayList<>(); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); list.add(new Trip(R.drawable.image4,"trip 1","this is trip 1")); RecyclerView rv = (RecyclerView) v.findViewById(R.id.rv); rv.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); rv.setLayoutManager(llm); adapter = new TripRVAdapter(list, getActivity()); rv.setAdapter(adapter); } }
1,544
0.713731
0.706606
48
31.166666
26.405754
103
false
false
0
0
0
0
0
0
0.854167
false
false
7
b61820de1029537500e378545e32903637a2f6dc
28,613,072,129,326
b067d5061e4ae5e3e7f010175694bf2802706485
/American/ravv-service/src/main/java/cn/farwalker/ravv/service/web/webmodel/biz/IWebModelBiz.java
40ed8ded06fab86c7e9c7e6215e8a1f7a368ac38
[]
no_license
lizhenghong20/web
https://github.com/lizhenghong20/web
7cf5a610ec19a0b8f7ba662131e56171fffabf9b
8941e68a2cf426b831e8219aeea8555568f95256
refs/heads/master
2022-11-05T18:02:47.842000
2019-06-10T02:22:32
2019-06-10T02:22:32
190,309,917
0
0
null
false
2022-10-12T20:27:42
2019-06-05T02:09:30
2019-06-10T06:11:13
2022-10-12T20:27:39
5,438
0
0
19
Java
false
false
package cn.farwalker.ravv.service.web.webmodel.biz; import com.baomidou.mybatisplus.service.IService; import cn.farwalker.ravv.service.web.webmodel.model.WebModelBo; /** * 首页模块<br/> * <br/> * //手写的注释:以"//"开始 <br/> * @author generateModel.java */ public interface IWebModelBiz extends IService<WebModelBo>{ }
UTF-8
Java
337
java
IWebModelBiz.java
Java
[]
null
[]
package cn.farwalker.ravv.service.web.webmodel.biz; import com.baomidou.mybatisplus.service.IService; import cn.farwalker.ravv.service.web.webmodel.model.WebModelBo; /** * 首页模块<br/> * <br/> * //手写的注释:以"//"开始 <br/> * @author generateModel.java */ public interface IWebModelBiz extends IService<WebModelBo>{ }
337
0.744409
0.744409
12
25.166666
23.265974
63
false
false
0
0
0
0
0
0
0.25
false
false
7
36e2e9cd93b8ee5908ffff7e206a5cf9a1264a6f
29,420,526,012,513
6ba9a3b3bccdb2cbb63dc3ad45f4341284062120
/HeadFirstDesign/src/main/java/com/design/model/observer/demo3/ObserverClient2.java
34575959e99928476bc4270f66f75c152907558d
[]
no_license
os-technology/books
https://github.com/os-technology/books
408c66cb76ba955189ff0478996b7c5e854fe109
aeb7267fdc186b84a740007284ad144c49b36e99
refs/heads/master
2022-12-21T20:41:41.934000
2019-04-17T02:58:36
2019-04-17T02:58:36
60,183,947
0
1
null
false
2022-12-16T07:54:00
2016-06-01T14:27:13
2019-04-17T03:02:53
2022-12-16T07:53:57
24,195
1
1
34
Java
false
false
package com.design.model.observer.demo3; import com.design.model.observer.demo1weather.DisplayElement; public class ObserverClient2 implements DisplayElement, Client{ private String info; private Server server; public ObserverClient2(Server server){ this.server = server; server.addClient(this); } @Override public void setInfo(String info) { this.info = info; display(); } @Override public void display() { System.out.println("ObserverClient2 : "+info); } }
UTF-8
Java
490
java
ObserverClient2.java
Java
[]
null
[]
package com.design.model.observer.demo3; import com.design.model.observer.demo1weather.DisplayElement; public class ObserverClient2 implements DisplayElement, Client{ private String info; private Server server; public ObserverClient2(Server server){ this.server = server; server.addClient(this); } @Override public void setInfo(String info) { this.info = info; display(); } @Override public void display() { System.out.println("ObserverClient2 : "+info); } }
490
0.738775
0.728571
26
17.846153
19.100327
63
false
false
0
0
0
0
0
0
1.307692
false
false
7
f8a0339679bd639cc3c0d85d4cd4800525ccb2d7
9,079,560,874,177
9becb47acead0bc908482a00f0f1d6857e6e6db3
/java_server/walkInProgress/src/main/java/group75/walkInProgress/bookmarks/BookmarkController.java
3764eaa1850d8f659440f0fbaf89726737c86d9e
[]
no_license
robengrobban/PVT-Grupp-75
https://github.com/robengrobban/PVT-Grupp-75
cb9a80a428acb93ed1960085b6dbd7990e309838
28d83d29ae497b14c6192da8302ddfa3d85600dd
refs/heads/main
2023-05-09T07:22:23.821000
2021-05-31T09:58:27
2021-05-31T09:58:27
352,948,919
4
0
null
false
2021-05-11T14:58:42
2021-03-30T09:45:55
2021-05-11T10:39:41
2021-05-11T14:58:30
287
2
0
1
Java
false
false
package group75.walkInProgress.bookmarks; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import group75.walkInProgress.Server; @Controller @RequestMapping(path = "/bookmarks") public class BookmarkController { @Autowired private BookmarkRepository bookmarkRepository; @PostMapping(path="/add",consumes="application/json",produces="application/json") public @ResponseBody ResponseEntity<Bookmark> saveBookmark(@RequestBody BookmarkBody bookmarkBody) { if(bookmarkBody==null || bookmarkBody.getRouteInfo() == null || bookmarkBody.getRouteInfo().getStartPoint()== null || bookmarkBody.getRouteInfo().getWaypoints()==null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } final String target = Server.NAME + "/account/userFromToken?token="+bookmarkBody.getToken(); final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int id = response.getId(); Stream<Bookmark> stream = bookmarkRepository.findByUserId(id).stream(); List<Bookmark> existing = stream.filter(b -> b.getRouteInfo().equals(bookmarkBody.getRouteInfo())).collect(Collectors.toList()); if(!existing.isEmpty()) { return new ResponseEntity<>(existing.get(0), HttpStatus.CONFLICT); } Bookmark bookmark = bookmarkRepository.save(new Bookmark(id, bookmarkBody.getRouteInfo())); return new ResponseEntity<>(bookmark, HttpStatus.OK); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } @DeleteMapping(path="/remove") public @ResponseBody ResponseEntity<Bookmark> deleteBookmark(@RequestParam String token, @RequestParam int bookmarkId) { final String target = Server.NAME + "/account/userFromToken?token="+token; final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int userId = response.getId(); Optional<Bookmark> bookmark = bookmarkRepository.findById(bookmarkId); if(bookmark.isPresent() && bookmark.get().getUserId() != userId) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } bookmarkRepository.deleteById(bookmarkId); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } catch (EmptyResultDataAccessException e) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @GetMapping(path="") public @ResponseBody ResponseEntity<Iterable<Bookmark>> getAllBookmarks(@RequestParam String token) { final String target = Server.NAME + "/account/userFromToken?token="+token; final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int id = response.getId(); return new ResponseEntity<>(bookmarkRepository.findByUserId(id), HttpStatus.OK); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } }
UTF-8
Java
4,331
java
BookmarkController.java
Java
[]
null
[]
package group75.walkInProgress.bookmarks; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import group75.walkInProgress.Server; @Controller @RequestMapping(path = "/bookmarks") public class BookmarkController { @Autowired private BookmarkRepository bookmarkRepository; @PostMapping(path="/add",consumes="application/json",produces="application/json") public @ResponseBody ResponseEntity<Bookmark> saveBookmark(@RequestBody BookmarkBody bookmarkBody) { if(bookmarkBody==null || bookmarkBody.getRouteInfo() == null || bookmarkBody.getRouteInfo().getStartPoint()== null || bookmarkBody.getRouteInfo().getWaypoints()==null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } final String target = Server.NAME + "/account/userFromToken?token="+bookmarkBody.getToken(); final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int id = response.getId(); Stream<Bookmark> stream = bookmarkRepository.findByUserId(id).stream(); List<Bookmark> existing = stream.filter(b -> b.getRouteInfo().equals(bookmarkBody.getRouteInfo())).collect(Collectors.toList()); if(!existing.isEmpty()) { return new ResponseEntity<>(existing.get(0), HttpStatus.CONFLICT); } Bookmark bookmark = bookmarkRepository.save(new Bookmark(id, bookmarkBody.getRouteInfo())); return new ResponseEntity<>(bookmark, HttpStatus.OK); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } @DeleteMapping(path="/remove") public @ResponseBody ResponseEntity<Bookmark> deleteBookmark(@RequestParam String token, @RequestParam int bookmarkId) { final String target = Server.NAME + "/account/userFromToken?token="+token; final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int userId = response.getId(); Optional<Bookmark> bookmark = bookmarkRepository.findById(bookmarkId); if(bookmark.isPresent() && bookmark.get().getUserId() != userId) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } bookmarkRepository.deleteById(bookmarkId); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } catch (EmptyResultDataAccessException e) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @GetMapping(path="") public @ResponseBody ResponseEntity<Iterable<Bookmark>> getAllBookmarks(@RequestParam String token) { final String target = Server.NAME + "/account/userFromToken?token="+token; final RestTemplate restTemplate = new RestTemplate(); try { UserInfo response = restTemplate.getForObject(target, UserInfo.class); int id = response.getId(); return new ResponseEntity<>(bookmarkRepository.findByUserId(id), HttpStatus.OK); } catch (RestClientException e) { System.out.println(e); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } }
4,331
0.710229
0.709074
93
45.569893
34.784248
174
false
false
0
0
0
0
0
0
0.83871
false
false
7
02ff3c381905abbcf32fec6f8e94d94dd760a472
28,200,755,275,676
fc5e04bd942cda0f3c9e130dd2940f63cc9de42b
/src/ru/ncedu/timurnav/old/Car.java
56e1c7afaa5b5b1e4d1c7dd2b496ec9685359414
[]
no_license
timurnav/jaxp
https://github.com/timurnav/jaxp
140f7c81d71905e5acc741e49d593eeaa5938c9c
ecfd2251676e357fb36bd4a04317d2dc4601aaaf
refs/heads/master
2015-07-21T23:55:41
2015-05-26T21:02:14
2015-05-26T21:02:14
36,323,622
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.ncedu.timurnav.old; public class Car { public long id; public String manufacturer; public String model; public long cost; // getters/ setters/ ... }
UTF-8
Java
172
java
Car.java
Java
[]
null
[]
package ru.ncedu.timurnav.old; public class Car { public long id; public String manufacturer; public String model; public long cost; // getters/ setters/ ... }
172
0.697674
0.697674
13
12.230769
11.476758
30
false
false
0
0
0
0
0
0
0.923077
false
false
7
c9279bcfe43c1631dad119aacbaece1dc90304f3
14,577,119,011,324
d705ce134ad4c9e3852d70d2fdfd1c96478e9c70
/persistence/src/test/java/com/jakubmacoun/shcontrol/persistence/dao/impl/WeatherDaoImplTest.java
f1a74f97e3efcd4f97d35b1b37e03e072d5368de
[ "Apache-2.0" ]
permissive
JakubMacoun/Smarthome-UI-Controller
https://github.com/JakubMacoun/Smarthome-UI-Controller
3055db8cd2ac56787d27412314d625c3fe70d0cf
1200d011a2b291e3f61a1448ae918ed6ae6c4d7d
refs/heads/master
2020-03-29T19:37:13.347000
2018-11-01T13:42:26
2018-11-01T13:42:26
150,272,950
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jakubmacoun.shcontrol.persistence.dao.impl; import com.jakubmacoun.shcontrol.persistence.dao.WeatherDao; import com.jakubmacoun.shcontrol.persistence.data.Location; import com.jakubmacoun.shcontrol.persistence.data.Weather; import com.jakubmacoun.shcontrol.persistence.data.type.WeatherType; import com.jakubmacoun.shcontrol.persistence.fixtures.FLocation; import com.jakubmacoun.shcontrol.test.DatabaseTest; import org.apache.commons.collections4.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; import java.util.List; import static org.junit.Assert.*; /** * {@link WeatherDaoImpl} test * * @author Jakub Macoun <info@jakubmacoun.com> */ public class WeatherDaoImplTest extends DatabaseTest { @Autowired private WeatherDao dao; @Override @Before public void setUp() throws Exception { loadFixture(LocationDaoImplTest.class); super.setUp(); } @Test public void clear() throws Exception { dao.clear(FLocation.ID); try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("SELECT type FROM weather WHERE id_location = ?")) { ps.setLong(1, FLocation.ID); try (ResultSet rs = ps.executeQuery()) { assertFalse("Data not deleted", rs.next()); } } } @Test public void createRecord() throws Exception { // Prepare try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("DELETE FROM weather")) { ps.execute(); } // Data final WeatherType TYPE = WeatherType.DAILY; final Date TIME = new Date(); final double APPARENT_TEMPERATURE = 38.7; final Location location = new Location(); location.setId(FLocation.ID); final Weather weather = new Weather(); weather.setType(TYPE); weather.setLocation(location); weather.setTime(TIME); weather.setTemperature(39d); weather.setApparentTemperature(APPARENT_TEMPERATURE); weather.setDewPoint(5.1); weather.setIcon("sunny"); weather.setSummary("Horko jako prase"); weather.setWindSpeed(0.1); // Run dao.createRecord(weather); // Check double dbApparentTemperature; try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("SELECT apparent_temperature FROM weather WHERE type = ?")) { ps.setString(1, TYPE.name()); try (ResultSet rs = ps.executeQuery()) { assertTrue("Data not inserted", rs.next()); dbApparentTemperature = rs.getDouble(1); } } assertEquals("Invalid apparent temperature inserted", APPARENT_TEMPERATURE, dbApparentTemperature, 0); } @Test public void getDataForLocation() { List<Weather> result = dao.getDataForLocation(FLocation.ID); assertFalse("No data retrieved", CollectionUtils.isEmpty(result)); } }
UTF-8
Java
3,148
java
WeatherDaoImplTest.java
Java
[ { "context": "\n\n/**\n * {@link WeatherDaoImpl} test\n *\n * @author Jakub Macoun <info@jakubmacoun.com>\n */\npublic class WeatherDa", "end": 795, "score": 0.9998762607574463, "start": 783, "tag": "NAME", "value": "Jakub Macoun" }, { "context": " WeatherDaoImpl} test\n *\n * @author Jakub Macoun <info@jakubmacoun.com>\n */\npublic class WeatherDaoImplTest extends Data", "end": 817, "score": 0.9999285936355591, "start": 797, "tag": "EMAIL", "value": "info@jakubmacoun.com" } ]
null
[]
package com.jakubmacoun.shcontrol.persistence.dao.impl; import com.jakubmacoun.shcontrol.persistence.dao.WeatherDao; import com.jakubmacoun.shcontrol.persistence.data.Location; import com.jakubmacoun.shcontrol.persistence.data.Weather; import com.jakubmacoun.shcontrol.persistence.data.type.WeatherType; import com.jakubmacoun.shcontrol.persistence.fixtures.FLocation; import com.jakubmacoun.shcontrol.test.DatabaseTest; import org.apache.commons.collections4.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; import java.util.List; import static org.junit.Assert.*; /** * {@link WeatherDaoImpl} test * * @author <NAME> <<EMAIL>> */ public class WeatherDaoImplTest extends DatabaseTest { @Autowired private WeatherDao dao; @Override @Before public void setUp() throws Exception { loadFixture(LocationDaoImplTest.class); super.setUp(); } @Test public void clear() throws Exception { dao.clear(FLocation.ID); try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("SELECT type FROM weather WHERE id_location = ?")) { ps.setLong(1, FLocation.ID); try (ResultSet rs = ps.executeQuery()) { assertFalse("Data not deleted", rs.next()); } } } @Test public void createRecord() throws Exception { // Prepare try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("DELETE FROM weather")) { ps.execute(); } // Data final WeatherType TYPE = WeatherType.DAILY; final Date TIME = new Date(); final double APPARENT_TEMPERATURE = 38.7; final Location location = new Location(); location.setId(FLocation.ID); final Weather weather = new Weather(); weather.setType(TYPE); weather.setLocation(location); weather.setTime(TIME); weather.setTemperature(39d); weather.setApparentTemperature(APPARENT_TEMPERATURE); weather.setDewPoint(5.1); weather.setIcon("sunny"); weather.setSummary("Horko jako prase"); weather.setWindSpeed(0.1); // Run dao.createRecord(weather); // Check double dbApparentTemperature; try (PreparedStatement ps = sqlSession.getConnection().prepareStatement("SELECT apparent_temperature FROM weather WHERE type = ?")) { ps.setString(1, TYPE.name()); try (ResultSet rs = ps.executeQuery()) { assertTrue("Data not inserted", rs.next()); dbApparentTemperature = rs.getDouble(1); } } assertEquals("Invalid apparent temperature inserted", APPARENT_TEMPERATURE, dbApparentTemperature, 0); } @Test public void getDataForLocation() { List<Weather> result = dao.getDataForLocation(FLocation.ID); assertFalse("No data retrieved", CollectionUtils.isEmpty(result)); } }
3,129
0.669949
0.665502
100
30.49
28.674551
141
false
false
0
0
0
0
0
0
0.54
false
false
7
106cc5820c263eafe2cb1d9d527bedf14ea52223
5,059,471,536,437
502c1fc7167f869daa6451ff688e211063c737f1
/src/com/futurice/tantalum2/net/XMLModel.java
8cc42f1ed423e9d922c503cd92e5df08fda0da97
[]
no_license
oyebc/CoopCUG
https://github.com/oyebc/CoopCUG
70d406f17627c59fd006d1d2cec32fa00fc39788
9b53589335897686d0d8cdfff8dae994017144e7
refs/heads/master
2021-01-10T05:19:47.012000
2015-06-04T02:44:30
2015-06-04T02:44:30
36,843,623
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.futurice.tantalum2.net; import com.futurice.tantalum2.log.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import javax.xml.parsers.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * XML Value Object is a data structure extracted from XML text. The simplified * parsing and integration to utility methods allows these to work online and * offline (using RMS) transparent to the application developer using the * caching classes. * * @author pahought */ public abstract class XMLModel extends DefaultHandler { final private Vector qnameStack = new Vector(); final private Vector charStack = new Vector(); final private Vector attributeStack = new Vector(); /** * Null constructor is an empty placeholder */ public XMLModel() { } public synchronized void setXML(final String xml) throws ParserConfigurationException, SAXException, IOException { final InputStream in = new ByteArrayInputStream(xml.getBytes()); try { SAXParserFactory.newInstance().newSAXParser().parse(in, this); } catch (Throwable t) { Log.logThrowable(t, "parser error: " + xml); } finally { in.close(); } } /** * Implement this method to store fields of interest in your value object * * @param chars * @param qnameStack * @param attributeStack */ abstract protected void element(Vector charStack, Vector qnameStack, Vector attributeStack); public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { qnameStack.addElement(qName); attributeStack.addElement(new XMLAttributes(attributes)); charStack.addElement(""); } public void characters(final char[] ch, final int start, final int length) throws SAXException { final String chars = new String(ch, start, length); charStack.setElementAt(chars, charStack.size() - 1); } public void endElement(final String uri, final String localName, final String qName) throws SAXException { element(charStack, qnameStack, attributeStack); qnameStack.removeElementAt(qnameStack.size() - 1); attributeStack.removeElementAt(attributeStack.size() - 1); charStack.removeElementAt(charStack.size() - 1); } }
UTF-8
Java
2,605
java
XMLModel.java
Java
[ { "context": "loper using the\n * caching classes.\n * \n * @author pahought\n */\npublic abstract class XMLModel extends Defaul", "end": 709, "score": 0.9994704127311707, "start": 701, "tag": "USERNAME", "value": "pahought" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.futurice.tantalum2.net; import com.futurice.tantalum2.log.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import javax.xml.parsers.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * XML Value Object is a data structure extracted from XML text. The simplified * parsing and integration to utility methods allows these to work online and * offline (using RMS) transparent to the application developer using the * caching classes. * * @author pahought */ public abstract class XMLModel extends DefaultHandler { final private Vector qnameStack = new Vector(); final private Vector charStack = new Vector(); final private Vector attributeStack = new Vector(); /** * Null constructor is an empty placeholder */ public XMLModel() { } public synchronized void setXML(final String xml) throws ParserConfigurationException, SAXException, IOException { final InputStream in = new ByteArrayInputStream(xml.getBytes()); try { SAXParserFactory.newInstance().newSAXParser().parse(in, this); } catch (Throwable t) { Log.logThrowable(t, "parser error: " + xml); } finally { in.close(); } } /** * Implement this method to store fields of interest in your value object * * @param chars * @param qnameStack * @param attributeStack */ abstract protected void element(Vector charStack, Vector qnameStack, Vector attributeStack); public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { qnameStack.addElement(qName); attributeStack.addElement(new XMLAttributes(attributes)); charStack.addElement(""); } public void characters(final char[] ch, final int start, final int length) throws SAXException { final String chars = new String(ch, start, length); charStack.setElementAt(chars, charStack.size() - 1); } public void endElement(final String uri, final String localName, final String qName) throws SAXException { element(charStack, qnameStack, attributeStack); qnameStack.removeElementAt(qnameStack.size() - 1); attributeStack.removeElementAt(attributeStack.size() - 1); charStack.removeElementAt(charStack.size() - 1); } }
2,605
0.700192
0.697889
74
34.202702
32.258659
141
false
false
0
0
0
0
0
0
0.635135
false
false
7
1e3d4bc364a9924564f4176459b6648e7952d398
28,501,402,987,650
933e2e6e840a7bc57c8a3a58b550e15f4f700ceb
/src/main/java/jp/co/orangeright/crossheadofficesample2/entity/Nextdayschedule.java
375ddea738537e7689a88e22e79d241c9ebc9312
[]
no_license
yoshkur/CrossHeadOfficeSample2
https://github.com/yoshkur/CrossHeadOfficeSample2
e2e19c1e6510a2d164f2aab5566dd69037f001dc
dd4d587ae25d0b3b48e7273499227180b4e753db
refs/heads/master
2021-01-17T21:11:05.007000
2018-05-31T06:11:11
2018-05-31T06:11:11
29,096,447
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jp.co.orangeright.crossheadofficesample2.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author yosh */ @Entity @XmlRootElement @NamedQueries({ @NamedQuery(name = "Nextdayschedule.findAll", query = "SELECT n FROM Nextdayschedule n"), @NamedQuery(name = "Nextdayschedule.findById", query = "SELECT n FROM Nextdayschedule n WHERE n.id = :id"), @NamedQuery(name = "Nextdayschedule.findBySendto", query = "SELECT n FROM Nextdayschedule n WHERE n.sendto = :sendto"), @NamedQuery(name = "Nextdayschedule.findBySendmessagetitle", query = "SELECT n FROM Nextdayschedule n WHERE n.sendmessagetitle = :sendmessagetitle"), @NamedQuery(name = "Nextdayschedule.findBySendmessage", query = "SELECT n FROM Nextdayschedule n WHERE n.sendmessage = :sendmessage"), @NamedQuery(name = "Nextdayschedule.findByReturnflg", query = "SELECT n FROM Nextdayschedule n WHERE n.returnflg = :returnflg"), @NamedQuery(name = "Nextdayschedule.findByReturnmessage", query = "SELECT n FROM Nextdayschedule n WHERE n.returnmessage = :returnmessage"), @NamedQuery(name = "Nextdayschedule.findByAdddate", query = "SELECT n FROM Nextdayschedule n WHERE n.adddate = :adddate"), @NamedQuery(name = "Nextdayschedule.findByAddprogram", query = "SELECT n FROM Nextdayschedule n WHERE n.addprogram = :addprogram"), @NamedQuery(name = "Nextdayschedule.findByAddcode", query = "SELECT n FROM Nextdayschedule n WHERE n.addcode = :addcode"), @NamedQuery(name = "Nextdayschedule.findByUpdatedate", query = "SELECT n FROM Nextdayschedule n WHERE n.updatedate = :updatedate"), @NamedQuery(name = "Nextdayschedule.findByUpdateprogram", query = "SELECT n FROM Nextdayschedule n WHERE n.updateprogram = :updateprogram"), @NamedQuery(name = "Nextdayschedule.findByUpdatecode", query = "SELECT n FROM Nextdayschedule n WHERE n.updatecode = :updatecode"), @NamedQuery(name = "Nextdayschedule.findByValidrow", query = "SELECT n FROM Nextdayschedule n WHERE n.validrow = :validrow")}) public class Nextdayschedule implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) private Integer id; @Size(max = 2147483647) private String sendto; @Size(max = 2147483647) private String sendmessagetitle; @Size(max = 2147483647) private String sendmessage; private Boolean returnflg; @Size(max = 2147483647) private String returnmessage; @Basic(optional = false) @NotNull @Temporal(TemporalType.TIMESTAMP) private Date adddate; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String addprogram; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String addcode; @Basic(optional = false) @NotNull @Temporal(TemporalType.TIMESTAMP) private Date updatedate; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String updateprogram; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String updatecode; @Basic(optional = false) @NotNull private boolean validrow; public Nextdayschedule() { } public Nextdayschedule(Integer id) { this.id = id; } public Nextdayschedule(Integer id, Date adddate, String addprogram, String addcode, Date updatedate, String updateprogram, String updatecode, boolean validrow) { this.id = id; this.adddate = adddate; this.addprogram = addprogram; this.addcode = addcode; this.updatedate = updatedate; this.updateprogram = updateprogram; this.updatecode = updatecode; this.validrow = validrow; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSendto() { return sendto; } public void setSendto(String sendto) { this.sendto = sendto; } public String getSendmessagetitle() { return sendmessagetitle; } public void setSendmessagetitle(String sendmessagetitle) { this.sendmessagetitle = sendmessagetitle; } public String getSendmessage() { return sendmessage; } public void setSendmessage(String sendmessage) { this.sendmessage = sendmessage; } public Boolean getReturnflg() { return returnflg; } public void setReturnflg(Boolean returnflg) { this.returnflg = returnflg; } public String getReturnmessage() { return returnmessage; } public void setReturnmessage(String returnmessage) { this.returnmessage = returnmessage; } public Date getAdddate() { return adddate; } public void setAdddate(Date adddate) { this.adddate = adddate; } public String getAddprogram() { return addprogram; } public void setAddprogram(String addprogram) { this.addprogram = addprogram; } public String getAddcode() { return addcode; } public void setAddcode(String addcode) { this.addcode = addcode; } public Date getUpdatedate() { return updatedate; } public void setUpdatedate(Date updatedate) { this.updatedate = updatedate; } public String getUpdateprogram() { return updateprogram; } public void setUpdateprogram(String updateprogram) { this.updateprogram = updateprogram; } public String getUpdatecode() { return updatecode; } public void setUpdatecode(String updatecode) { this.updatecode = updatecode; } public boolean getValidrow() { return validrow; } public void setValidrow(boolean validrow) { this.validrow = validrow; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Nextdayschedule)) { return false; } Nextdayschedule other = (Nextdayschedule) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "jp.co.orangeright.crossheadofficesample2.entity.Nextdayschedule[ id=" + id + " ]"; } }
UTF-8
Java
7,315
java
Nextdayschedule.java
Java
[ { "context": "bind.annotation.XmlRootElement;\n\n/**\n *\n * @author yosh\n */\n@Entity\n@XmlRootElement\n@NamedQueries({\n ", "end": 777, "score": 0.6205945014953613, "start": 776, "tag": "NAME", "value": "y" }, { "context": "nd.annotation.XmlRootElement;\n\n/**\n *\n * @author yosh\n */\n@Entity\n@XmlRootElement\n@NamedQueries({\n @", "end": 780, "score": 0.8499987721443176, "start": 777, "tag": "USERNAME", "value": "osh" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jp.co.orangeright.crossheadofficesample2.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author yosh */ @Entity @XmlRootElement @NamedQueries({ @NamedQuery(name = "Nextdayschedule.findAll", query = "SELECT n FROM Nextdayschedule n"), @NamedQuery(name = "Nextdayschedule.findById", query = "SELECT n FROM Nextdayschedule n WHERE n.id = :id"), @NamedQuery(name = "Nextdayschedule.findBySendto", query = "SELECT n FROM Nextdayschedule n WHERE n.sendto = :sendto"), @NamedQuery(name = "Nextdayschedule.findBySendmessagetitle", query = "SELECT n FROM Nextdayschedule n WHERE n.sendmessagetitle = :sendmessagetitle"), @NamedQuery(name = "Nextdayschedule.findBySendmessage", query = "SELECT n FROM Nextdayschedule n WHERE n.sendmessage = :sendmessage"), @NamedQuery(name = "Nextdayschedule.findByReturnflg", query = "SELECT n FROM Nextdayschedule n WHERE n.returnflg = :returnflg"), @NamedQuery(name = "Nextdayschedule.findByReturnmessage", query = "SELECT n FROM Nextdayschedule n WHERE n.returnmessage = :returnmessage"), @NamedQuery(name = "Nextdayschedule.findByAdddate", query = "SELECT n FROM Nextdayschedule n WHERE n.adddate = :adddate"), @NamedQuery(name = "Nextdayschedule.findByAddprogram", query = "SELECT n FROM Nextdayschedule n WHERE n.addprogram = :addprogram"), @NamedQuery(name = "Nextdayschedule.findByAddcode", query = "SELECT n FROM Nextdayschedule n WHERE n.addcode = :addcode"), @NamedQuery(name = "Nextdayschedule.findByUpdatedate", query = "SELECT n FROM Nextdayschedule n WHERE n.updatedate = :updatedate"), @NamedQuery(name = "Nextdayschedule.findByUpdateprogram", query = "SELECT n FROM Nextdayschedule n WHERE n.updateprogram = :updateprogram"), @NamedQuery(name = "Nextdayschedule.findByUpdatecode", query = "SELECT n FROM Nextdayschedule n WHERE n.updatecode = :updatecode"), @NamedQuery(name = "Nextdayschedule.findByValidrow", query = "SELECT n FROM Nextdayschedule n WHERE n.validrow = :validrow")}) public class Nextdayschedule implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) private Integer id; @Size(max = 2147483647) private String sendto; @Size(max = 2147483647) private String sendmessagetitle; @Size(max = 2147483647) private String sendmessage; private Boolean returnflg; @Size(max = 2147483647) private String returnmessage; @Basic(optional = false) @NotNull @Temporal(TemporalType.TIMESTAMP) private Date adddate; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String addprogram; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String addcode; @Basic(optional = false) @NotNull @Temporal(TemporalType.TIMESTAMP) private Date updatedate; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String updateprogram; @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) private String updatecode; @Basic(optional = false) @NotNull private boolean validrow; public Nextdayschedule() { } public Nextdayschedule(Integer id) { this.id = id; } public Nextdayschedule(Integer id, Date adddate, String addprogram, String addcode, Date updatedate, String updateprogram, String updatecode, boolean validrow) { this.id = id; this.adddate = adddate; this.addprogram = addprogram; this.addcode = addcode; this.updatedate = updatedate; this.updateprogram = updateprogram; this.updatecode = updatecode; this.validrow = validrow; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSendto() { return sendto; } public void setSendto(String sendto) { this.sendto = sendto; } public String getSendmessagetitle() { return sendmessagetitle; } public void setSendmessagetitle(String sendmessagetitle) { this.sendmessagetitle = sendmessagetitle; } public String getSendmessage() { return sendmessage; } public void setSendmessage(String sendmessage) { this.sendmessage = sendmessage; } public Boolean getReturnflg() { return returnflg; } public void setReturnflg(Boolean returnflg) { this.returnflg = returnflg; } public String getReturnmessage() { return returnmessage; } public void setReturnmessage(String returnmessage) { this.returnmessage = returnmessage; } public Date getAdddate() { return adddate; } public void setAdddate(Date adddate) { this.adddate = adddate; } public String getAddprogram() { return addprogram; } public void setAddprogram(String addprogram) { this.addprogram = addprogram; } public String getAddcode() { return addcode; } public void setAddcode(String addcode) { this.addcode = addcode; } public Date getUpdatedate() { return updatedate; } public void setUpdatedate(Date updatedate) { this.updatedate = updatedate; } public String getUpdateprogram() { return updateprogram; } public void setUpdateprogram(String updateprogram) { this.updateprogram = updateprogram; } public String getUpdatecode() { return updatecode; } public void setUpdatecode(String updatecode) { this.updatecode = updatecode; } public boolean getValidrow() { return validrow; } public void setValidrow(boolean validrow) { this.validrow = validrow; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Nextdayschedule)) { return false; } Nextdayschedule other = (Nextdayschedule) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "jp.co.orangeright.crossheadofficesample2.entity.Nextdayschedule[ id=" + id + " ]"; } }
7,315
0.677375
0.665208
235
30.127659
32.904125
165
false
false
0
0
0
0
0
0
0.489362
false
false
7
2a5c3e94e5ecd86c6968308b8663128a436e5eef
5,875,515,312,722
06725a220ac730c6957e2256c18050a0079ad9f9
/src/agenda/Manipular.java
94deda024a876cc23cc50f32a2663cb0a5f02fe3
[]
no_license
johannlucas/TADS-Agenda
https://github.com/johannlucas/TADS-Agenda
1179fe57db102a6fd32a1b6f01a70d740f94b9d6
7d124759bc506f3f2cb124b30cc178e5a3e0b55b
refs/heads/master
2021-08-24T03:51:18.240000
2017-12-07T23:50:20
2017-12-07T23:50:20
111,850,849
0
0
null
false
2017-11-23T23:20:00
2017-11-23T21:17:02
2017-11-23T21:39:21
2017-11-23T23:20:00
17
0
0
0
Java
false
null
package agenda; import java.io.IOException; import java.util.Scanner; public class Manipular { //Windows //String arquivo = "C:\\Users\\k27394\\Documents\\minhaagenda.dat"; //Linux String arquivo = "/local/home/tads/Documentos/minhaagenda.dat"; public static void main(String[] args) throws IOException { //System.out.println("Insira o nome do arquivo: "); //Linux //String arquivo = "/local/home/tads/Documentos/minhaagenda.dat"; //Windows Manipular contexto = new Manipular(); Scanner entrada = new Scanner(System.in); Boolean sair = true; System.out.println("------------------------------------------"); System.out.println("-------------Olá! Bem vindo!--------------"); System.out.println("------------------------------------------"); while (sair) { Opcoes(); switch (entrada.next()) { case "1": contexto.Inserir(); break; case "2": contexto.Alterar(); break; case "3": contexto.Buscar(); break; case "4": contexto.Listar(); break; case "5": contexto.Excluir(); break; default: sair = false; System.out.println("------------------------------------------"); System.out.println("----------------Até mais!-----------------"); System.out.println("------------------------------------------"); break; } } } private static void Opcoes() { System.out.println("1- Inserir"); System.out.println("2- Alterar"); System.out.println("3- Buscar"); System.out.println("4- Listar"); System.out.println("5- Excluir"); System.out.println("6- Sair"); } private void Inserir() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); System.out.println("Insira um nome: "); String nome = entrada.next(); //String nome = padRight(entrada.next(), 10); System.out.println("Insira um telefone: "); String telefone = entrada.next(); //String telefone = padRight(entrada.next(), 8); //Instanciando agenda Agenda age = new Agenda(id, nome, telefone); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Salvar arquivo arq.Inserir(); } private void Alterar() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira o ID do registro que você quer alterar:"); String id = entrada.next(); System.out.println("Insira um nome: "); String nome = entrada.next(); System.out.println("Insira um telefone: "); String telefone = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id, nome, telefone); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Buscar arquivo arq.ExcluirAlterar(true); } private void Buscar() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); //Buscar arquivo arq.Buscar(); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); } private void Excluir() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Buscar arquivo arq.ExcluirAlterar(false); } private void Listar() throws IOException { //Pedir informacoes System.out.println("Agenda completa"); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, new Agenda()); //Buscar arquivo arq.Listar(); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); } public static String padRight(String s, int n) { return String.format("%1$-" + n + "s", s); } }
UTF-8
Java
5,277
java
Manipular.java
Java
[ { "context": "\n //Windows\n //String arquivo = \"C:\\\\Users\\\\k27394\\\\Documents\\\\minhaagenda.dat\";\n //Linux\n Str", "end": 153, "score": 0.9993614554405212, "start": 147, "tag": "USERNAME", "value": "k27394" } ]
null
[]
package agenda; import java.io.IOException; import java.util.Scanner; public class Manipular { //Windows //String arquivo = "C:\\Users\\k27394\\Documents\\minhaagenda.dat"; //Linux String arquivo = "/local/home/tads/Documentos/minhaagenda.dat"; public static void main(String[] args) throws IOException { //System.out.println("Insira o nome do arquivo: "); //Linux //String arquivo = "/local/home/tads/Documentos/minhaagenda.dat"; //Windows Manipular contexto = new Manipular(); Scanner entrada = new Scanner(System.in); Boolean sair = true; System.out.println("------------------------------------------"); System.out.println("-------------Olá! Bem vindo!--------------"); System.out.println("------------------------------------------"); while (sair) { Opcoes(); switch (entrada.next()) { case "1": contexto.Inserir(); break; case "2": contexto.Alterar(); break; case "3": contexto.Buscar(); break; case "4": contexto.Listar(); break; case "5": contexto.Excluir(); break; default: sair = false; System.out.println("------------------------------------------"); System.out.println("----------------Até mais!-----------------"); System.out.println("------------------------------------------"); break; } } } private static void Opcoes() { System.out.println("1- Inserir"); System.out.println("2- Alterar"); System.out.println("3- Buscar"); System.out.println("4- Listar"); System.out.println("5- Excluir"); System.out.println("6- Sair"); } private void Inserir() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); System.out.println("Insira um nome: "); String nome = entrada.next(); //String nome = padRight(entrada.next(), 10); System.out.println("Insira um telefone: "); String telefone = entrada.next(); //String telefone = padRight(entrada.next(), 8); //Instanciando agenda Agenda age = new Agenda(id, nome, telefone); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Salvar arquivo arq.Inserir(); } private void Alterar() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira o ID do registro que você quer alterar:"); String id = entrada.next(); System.out.println("Insira um nome: "); String nome = entrada.next(); System.out.println("Insira um telefone: "); String telefone = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id, nome, telefone); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Buscar arquivo arq.ExcluirAlterar(true); } private void Buscar() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); //Buscar arquivo arq.Buscar(); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); } private void Excluir() throws IOException { Scanner entrada = new Scanner(System.in); //Pedir informacoes System.out.println("Insira um ID"); String id = entrada.next(); //Instanciando agenda Agenda age = new Agenda(id); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, age); //Buscar arquivo arq.ExcluirAlterar(false); } private void Listar() throws IOException { //Pedir informacoes System.out.println("Agenda completa"); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); //Instanciando arquivo Arquivo arq = new Arquivo(arquivo, new Agenda()); //Buscar arquivo arq.Listar(); System.out.println("------------------------------------------"); System.out.println("------------------------------------------"); } public static String padRight(String s, int n) { return String.format("%1$-" + n + "s", s); } }
5,277
0.474972
0.471179
164
31.158537
22.905676
85
false
false
0
0
0
0
0
0
0.573171
false
false
7
eb3b51f04341301584476ae9dfddb8a79dc7af5b
23,321,672,417,346
cfc4ef07a3275b68b49ad3ad563a0e653c3f6e11
/user/src/main/java/com/eric/user/service/UserInfoService.java
fc3b8d926c172cf0966f48a607cde12585db0333
[]
no_license
henanren/second-kill
https://github.com/henanren/second-kill
32b30d36412b79bff17ee57ab14e85690405393b
2570c4371321daa80ac72e1476d08e2faef8bc7b
refs/heads/master
2020-06-27T04:19:14.363000
2019-03-16T04:48:42
2019-03-16T04:48:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eric.user.service; import com.eric.seckill.common.model.CommonResult; import com.eric.seckill.common.model.feign.ChangePointRequest; import com.eric.user.bean.UserMaster; import com.eric.user.model.*; /** * @author wang.js on 2019/1/16. * @version 1.0 */ public interface UserInfoService { /** * 保存用户信息 * * @param userMaster * @param mobile * @return */ int insert(UserMaster userMaster, String mobile); /** * 根据手机号判断是否已经注册过 * * @param phone * @return */ Integer checkMobileExist(String phone); /** * 更新用户信息 * * @param userInfo * @return */ CommonResult<Void> updateUserInfo(UserInfoModifyRequest userInfo); /** * 更新用户余额 * * @param request * @return */ ChargeBalanceResponse updateUserBalance(ChargeBalanceRequest request); /** * 积分变更 * * @param request * @return */ UserPointChangeResponse updateUserPoint(UserPointChangeRequest request); /** * 积分变动 * * @param request * @return */ CommonResult<Void> changePoint(ChangePointRequest request); /** * 根据用户id获取用户的等级 * * @param userId * @return */ CommonResult<String> findUserLevelIdByUserId(String userId); }
UTF-8
Java
1,269
java
UserInfoService.java
Java
[ { "context": "ter;\nimport com.eric.user.model.*;\n\n/**\n * @author wang.js on 2019/1/16.\n * @version 1.0\n */\npublic interfac", "end": 237, "score": 0.998196542263031, "start": 230, "tag": "USERNAME", "value": "wang.js" } ]
null
[]
package com.eric.user.service; import com.eric.seckill.common.model.CommonResult; import com.eric.seckill.common.model.feign.ChangePointRequest; import com.eric.user.bean.UserMaster; import com.eric.user.model.*; /** * @author wang.js on 2019/1/16. * @version 1.0 */ public interface UserInfoService { /** * 保存用户信息 * * @param userMaster * @param mobile * @return */ int insert(UserMaster userMaster, String mobile); /** * 根据手机号判断是否已经注册过 * * @param phone * @return */ Integer checkMobileExist(String phone); /** * 更新用户信息 * * @param userInfo * @return */ CommonResult<Void> updateUserInfo(UserInfoModifyRequest userInfo); /** * 更新用户余额 * * @param request * @return */ ChargeBalanceResponse updateUserBalance(ChargeBalanceRequest request); /** * 积分变更 * * @param request * @return */ UserPointChangeResponse updateUserPoint(UserPointChangeRequest request); /** * 积分变动 * * @param request * @return */ CommonResult<Void> changePoint(ChangePointRequest request); /** * 根据用户id获取用户的等级 * * @param userId * @return */ CommonResult<String> findUserLevelIdByUserId(String userId); }
1,269
0.682948
0.675236
70
15.671429
19.179396
73
false
false
0
0
0
0
0
0
0.9
false
false
7
ffe09238bfde6b9b066d715006da12620c5b4e68
20,444,044,357,688
82a0a2799af02afadde8dffbd4f0e615c8f6592e
/src/main/java/com/bbd/dataplatform/mysql/util/DbPoolConnection.java
cd28949f834c44099c89d2483bc46f8f60abe1b3
[]
no_license
code-wujie/mysql-exporter
https://github.com/code-wujie/mysql-exporter
3e58a50581232719572990e1141fce48d8d7c4db
5a2600d4dfbbff22a502b535eb763a93c423ea0a
refs/heads/master
2020-04-17T08:36:53.200000
2019-01-18T14:42:52
2019-01-18T14:42:52
166,419,128
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bbd.dataplatform.mysql.util; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Properties; public class DbPoolConnection { private static HashMap<Properties, DbPoolConnection> DbMap = new HashMap<>(); private DruidDataSource dds = null; public DbPoolConnection(Properties properties) { try { dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } public static synchronized DbPoolConnection getInstance(Properties properties) { DbPoolConnection databasePool; if (DbMap.containsKey(properties)) { databasePool = DbMap.get(properties); } else { databasePool = new DbPoolConnection(properties); DbMap.put(properties, databasePool); } return databasePool; } public void discardConnection(Connection realConnection) throws SQLException { dds.discardConnection(realConnection); } public DruidPooledConnection getConnection() throws SQLException { return dds.getConnection(); } }
UTF-8
Java
1,348
java
DbPoolConnection.java
Java
[]
null
[]
package com.bbd.dataplatform.mysql.util; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Properties; public class DbPoolConnection { private static HashMap<Properties, DbPoolConnection> DbMap = new HashMap<>(); private DruidDataSource dds = null; public DbPoolConnection(Properties properties) { try { dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } public static synchronized DbPoolConnection getInstance(Properties properties) { DbPoolConnection databasePool; if (DbMap.containsKey(properties)) { databasePool = DbMap.get(properties); } else { databasePool = new DbPoolConnection(properties); DbMap.put(properties, databasePool); } return databasePool; } public void discardConnection(Connection realConnection) throws SQLException { dds.discardConnection(realConnection); } public DruidPooledConnection getConnection() throws SQLException { return dds.getConnection(); } }
1,348
0.706231
0.706231
43
30.372093
26.057203
88
false
false
0
0
0
0
0
0
0.488372
false
false
7
51db21a77ff264aa0f4c33c4024ad65350f05f83
20,444,044,354,457
f0c6ca70a4389a8978e23a99f1b0d44f12ac37de
/SelFramework/src/test/java/pdms/tests/UpdateDATests.java
68140db3e5c46498748008da2c118058853783a1
[]
no_license
UmaDav/SeleniumWebAutomation
https://github.com/UmaDav/SeleniumWebAutomation
b610f2b62c4dc47b1aec1218551538ef9cd450a4
ed1c9fb874954d9422f1c49eff50278f6cb1760e
refs/heads/master
2022-07-09T15:12:54.902000
2019-07-17T11:26:16
2019-07-17T11:26:16
197,374,324
0
0
null
false
2021-04-26T19:20:06
2019-07-17T11:14:43
2019-07-18T05:37:06
2021-04-26T19:20:05
10,061
0
0
2
HTML
false
false
package pdms.tests; import java.io.IOException; import java.net.MalformedURLException; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import com.utilities.Base; import com.utilities.CustomListener; import com.utilities.excelComponent; import pdms.repository.AddPensionerPage; import pdms.repository.HomePage; import pdms.repository.LeftNavigationPage; import pdms.repository.UpdateDAPage; @Listeners(CustomListener.class) public class UpdateDATests extends Base { private String strDAObjId; public void testEMudhra() throws InterruptedException, IOException { loginUser(5,reader.getCellData("UpdateDA", "LoginType", 5),reader.getCellData("UpdateDA", "UserName", 5), reader.getCellData("UpdateDA", "Password", 5)); Thread.sleep(2000); clickOn(driver,UpdateDAPage.span_PDMSPendingTasks(driver),10); Thread.sleep(4000); driver.findElement(By.xpath("//a[contains(text(),'June 2019')]")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//button[contains(.,'Generate Digital Signature')]")).click(); Thread.sleep(5000); //String outlookApplicationPath = "C:\\Signer\\Signer\\Signer.exe"; //String winiumDriverPath = "C:\\Users\\uma.davuluri\\Downloads\\drk sarma\\Winium.Desktop.exe"; // DesktopOptions options = new DesktopOptions(); //Initiate Winium Desktop Options //options.setApplicationPath(outlookApplicationPath); //Set outlook application path // File drivePath = new File(winiumDriverPath); //Set winium driver path // WiniumDriverService service = new WiniumDriverService.Builder().usingDriverExecutable(drivePath).usingPort(9999).withVerbose(true).withSilent(false).buildDesktopService(); // service.start(); //Build and Start a Winium Driver service //WiniumDriver driverwin = new WiniumDriver(options); //Start a winium driver //String str[] = driverwin.getWindowHandles(); //Thread.sleep(5000); //driverwin.findElement(By.xpath("//button[contains(.,'Cancel')]")).click(); } @Test public void updateDATest() throws InterruptedException, ParseException, IOException { loggerExtentReport = extent.startTest("Update DA Test"); UpdateDA_SectionHead(2); UpdateDA_AuditOfficer(3); UpdateDA_DeputyDirector(4); UpdateDA_Comissioner(5); checkDAArrears(2); } public void checkDAArrears(int rowNum) throws InterruptedException, ParseException, IOException { String filePath = System.getProperty("user.dir") + "\\testResults\\"; String timestamp= getCurrentTimeStamp(); String strFile = "PDMS_DA_Arrears_" + timestamp; String[] headers = new String[] { "PPONumber", "TotalAmount", "ActualDRArrears", "ExpectedDRArrears", "Status"}; createExcelFile(filePath,strFile,"Results",headers); excelComponent DAreader = new excelComponent(filePath + strFile +".xlsx"); String strPPONum , strRtDate , strActualDAArrs, strExpDAArrs, strEffDate; double dblTotalAmt ,TotalDAArrears=0, dblDA_Months, dblNewDA, dblCurrDA; //dblDA_Months = Double.parseDouble(reader.getCellData("UpdateDA", "DA_Arr_Months", rowNum)); dblNewDA = Double.parseDouble(reader.getCellData("UpdateDA", "NewDA", rowNum)); dblCurrDA = Double.parseDouble(reader.getCellData("UpdateDA", "CurrentDA", rowNum)); dblNewDA = dblNewDA - dblCurrDA; strEffDate = reader.getCellData("UpdateDA", "FromDate", rowNum); strEffDate = getConvertodDate(strEffDate); strEffDate = ConvertDateMonthInTwoDigitFormat(strEffDate); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Date EffectDate = formatter.parse(strEffDate); Date PenRtDate; SoftAssert sftAssert = new SoftAssert(); loginUser(2,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); Thread.sleep(2000); clickOn(driver,HomePage.menu_DownArrow(driver),10); Thread.sleep(2000); clickOn(driver,HomePage.span_Reports(driver),10); selValue(driver,HomePage.sel_Reports_PensionerStatus(driver),10,"Active"); Thread.sleep(2000); int row=2,currtRow;; HomePage.btn_Action(driver, "Search"); Thread.sleep(5000); boolean pagination=true; while(pagination==true) { currtRow = DAreader.getRowCount("Results") +1; int rows = HomePage.tbl_Report_PensionersRows(driver); //System.out.println("ROW COUNT : "+rows); for (row=2;row<=rows;row++) { strPPONum = HomePage.tbl_Report_PensionersData(driver, row, 4).getText(); strRtDate = HomePage.tbl_Report_PensionersData(driver, row, 6).getText(); strActualDAArrs = HomePage.tbl_Report_PensionersData(driver, row, 28).getText(); strActualDAArrs = strActualDAArrs.substring(2,strActualDAArrs.length()); DAreader.setCellData("Results", "PPONumber", currtRow, strPPONum); DAreader.setCellData("Results", "ActualDRArrears", currtRow, strActualDAArrs); Double dblActDA = Double.valueOf(strActualDAArrs.replaceAll(",", "").toString()); String strTotalAmt = HomePage.tbl_Report_PensionersData(driver, row, 18).getText(); DecimalFormat df = new DecimalFormat("#,###,##0"); strTotalAmt = strTotalAmt.substring(2, strTotalAmt.length()); DAreader.setCellData("Results", "TotalAmount", currtRow, strTotalAmt); Double dblTotal = Double.valueOf(strTotalAmt.replaceAll(",", "").toString()); PenRtDate = formatter.parse(strRtDate); String strExpToDate = getLastDayOfTheMonth(); if(!strRtDate.equals("")) { if (PenRtDate.compareTo(EffectDate) > 0) { int Expectedmnths = getMonthsDifference(strRtDate, strExpToDate); TotalDAArrears = (Expectedmnths * dblNewDA * dblTotal)/100 ; //System.out.println("Rt date is greater EffDate"); }else if (PenRtDate.compareTo(EffectDate) <= 0) { int Expectedmnths = getMonthsDifference(strEffDate, strExpToDate); //TotalDAArrears = (dblDA_Months * dblNewDA * dblTotal)/100 ; TotalDAArrears = (Expectedmnths * dblNewDA * dblTotal)/100 ; } TotalDAArrears = Math.round(TotalDAArrears); if(TotalDAArrears == dblActDA) { DAreader.setCellData("Results", "Status", currtRow, "Pass"); } else { DAreader.setCellData("Results", "Status", currtRow, "Fail"); } String strFinalAmt = df.format(TotalDAArrears); DAreader.setCellData("Results", "ExpectedDRArrears", currtRow, strFinalAmt); } currtRow = currtRow+1; }//end for loop if(UpdateDAPage.btn_PaginationNext(driver).isDisplayed() == true) { clickOn(driver,UpdateDAPage.btn_PaginationNext(driver),10); Thread.sleep(5000); row=2; pagination = true; } else { pagination = false; } }//end while loop } private void UpdateDA_SectionHead(int rowNum) throws InterruptedException, ParseException { SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); //verify current DA field String strActualDA = UpdateDAPage.span_DAPercentage(driver).getText(); String strExpectedDA = reader.getCellData("UpdateDA", "CurrentDA", rowNum); Assert.assertEquals(Double.parseDouble(strActualDA), Double.parseDouble(strExpectedDA), "Current DA not matched"); //enter New DA field UpdateDAPage.txtbx_NewDA(driver).sendKeys(Keys.CONTROL + "a"); Thread.sleep(1000); UpdateDAPage.txtbx_NewDA(driver).sendKeys(Keys.DELETE); Thread.sleep(1000); sendkeys(driver,UpdateDAPage.txtbx_NewDA(driver),20,reader.getCellData("UpdateDA", "NewDA", rowNum)); //enter From / Effective Date clickOn(driver,UpdateDAPage.calendar_FromDate(driver),10); Thread.sleep(2000); DatePicker(reader.getCellData("UpdateDA", "FromDate", rowNum)); Thread.sleep(2000); //verify To Date String strActualToDate = UpdateDAPage.span_ToDate(driver).getText(); String strExpToDate = getLastDayOfTheMonth(); sftAssert.assertEquals(strActualToDate, strExpToDate, "Mismatch in To Date"); //verify DA for Months String strFrom = UpdateDAPage.calendar_FromDate(driver).getAttribute("innerText"); strFrom.trim(); int Expectedmnths = getMonthsDifference(strFrom, UpdateDAPage.span_ToDate(driver).getText()); String strMonths = UpdateDAPage.span_DAforMonths(driver).getText() ; int intactualMonths = Integer.parseInt(strMonths); Assert.assertEquals(intactualMonths, Expectedmnths,"Mismatch in DA for Months"); reader.setCellData("Properties", "OldDA", 2,strActualDA); reader.setCellData("Properties", "CurrentDA", 2, reader.getCellData("UpdateDA", "NewDA", rowNum)); reader.setCellData("Properties", "DAMonths", 2, strMonths); reader.setCellData("Properties", "DAEffDate", 2, UpdateDAPage.calendar_FromDate(driver).getText()); clickOn(driver,UpdateDAPage.btn_Action(driver, "Attach GO"),10); Thread.sleep(2000); UploadFiles.uploadDocument(reader.getCellData("UpdateDA", "Modal_FileName", rowNum), reader.getCellData("UpdateDA", "Modal_File", rowNum), reader.getCellData("UpdateDA", "Modal_Category", rowNum), sftAssert); /*if(bln==true) { if(UpdateDAPage.lnk_File(driver, reader.getCellData("UpdateDA", "Modal_FileName", rowNum)).isDisplayed() == true) { Assert.assertEquals(true, true); } else { Assert.assertEquals(false, true,"Upload unsuccessful"); } clickOn(driver,UpdateDAPage.btn_Action(driver, "Update"),10); }*/ clickOn(driver,UpdateDAPage.btn_Action(driver, "Update"),10); Thread.sleep(3000); /*if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); }*/ clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); Thread.sleep(5000); boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Audit Officer").isDisplayed(); sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-AuditOfficer").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); getDAObjectId(); reader.setCellData("UpdateDA", "DAObjID", 2, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 3, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 4, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 5, strDAObjId); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_AuditOfficer(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); //boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Deputy Director").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-DeputyDirector").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_DeputyDirector(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); //boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Commissioner").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-Commissioner").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); //Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_Comissioner(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); clickOn(driver,UpdateDAPage.span_PDMSPendingTasks(driver),10); Thread.sleep(4000); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); /*boolean flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pensioner records are successfully updated with new DA").isDisplayed(); sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(2000);*/ LogOut(); sftAssert.assertAll(); } private void verifyDAReadOnlyFields(int rowNum , SoftAssert asst) throws ParseException, InterruptedException { //verify current DA field String strActual = UpdateDAPage.span_DAReadonlyField(driver, "Current DA %").getText(); String strExpected = reader.getCellData("UpdateDA", "CurrentDA", rowNum); asst.assertEquals(Double.parseDouble(strActual), Double.parseDouble(strExpected), "Current DA not matched"); //verify New DA % strActual = UpdateDAPage.span_DAReadonlyField(driver, "New DA %").getText(); strExpected = reader.getCellData("UpdateDA", "NewDA", rowNum); asst.assertEquals(Double.parseDouble(strActual), Double.parseDouble(strExpected), "New DA not matched"); //verify From Date strExpected = getConvertodDate(reader.getCellData("UpdateDA", "FromDate", rowNum)); strExpected = ConvertDateMonthInTwoDigitFormat(strExpected); strActual = UpdateDAPage.span_DAReadonlyField(driver, "From Date").getText(); //verify To Date strActual = UpdateDAPage.span_DAReadonlyField(driver, "To Date").getText(); strExpected = getLastDayOfTheMonth(); asst.assertEquals(strActual, strExpected, "Mismatch in To Date"); //verify To Date strActual = UpdateDAPage.span_DAReadonlyField(driver, "DA for months").getText(); int mnths = getMonthsDifference(UpdateDAPage.span_DAReadonlyField(driver, "From Date").getText(), UpdateDAPage.span_DAReadonlyField(driver, "To Date").getText()); asst.assertEquals(Integer.parseInt(strActual), mnths, "Mismatch in To Date"); if(UpdateDAPage.lnk_File(driver, reader.getCellData("UpdateDA", "Modal_FileName", rowNum)).isDisplayed() == true) { asst.assertEquals(true, true); } else { asst.assertEquals(false, true,"Upload unsuccessful"); } //clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); } private void navigateToUpDateDA(String strDAID) throws InterruptedException { if(strDAID.isEmpty()) { //Navigate to Add New Pensioner from Left Pane navigateToDA(); } else { HomeTests.UpdateDASearch(strDAID); strDAObjId = strDAID; } } private void navigateToDA() throws InterruptedException { clickOn(driver,LeftNavigationPage.lnk_UpdateDA(driver),10); Thread.sleep(3000); } private void getDAObjectId() { if(UpdateDAPage.span_DAObjectId(driver).isDisplayed()==true) { strDAObjId = UpdateDAPage.span_DAObjectId(driver).getText(); strDAObjId=strDAObjId.substring(1, strDAObjId.length()-1); //Removing First & last characters from string () logfile.info("Fetched DA Work Object Id as : " + strDAObjId); } } }
UTF-8
Java
17,767
java
UpdateDATests.java
Java
[ { "context": "e\";\r\n\t //String winiumDriverPath = \"C:\\\\Users\\\\uma.davuluri\\\\Downloads\\\\drk sarma\\\\Winium.Desktop.exe\";\r", "end": 1502, "score": 0.919342577457428, "start": 1495, "tag": "USERNAME", "value": "uma.dav" }, { "context": " //String winiumDriverPath = \"C:\\\\Users\\\\uma.davuluri\\\\Downloads\\\\drk sarma\\\\Winium.Desktop.exe\";\r\n\t \r\n", "end": 1507, "score": 0.7037967443466187, "start": 1502, "tag": "NAME", "value": "uluri" }, { "context": "ginType\", rowNum),reader.getCellData(\"UpdateDA\", \"UserName\", rowNum), reader.getCellData(\"UpdateDA\", \"Passwo", "end": 4063, "score": 0.7383764386177063, "start": 4055, "tag": "USERNAME", "value": "UserName" }, { "context": "ginType\", rowNum),reader.getCellData(\"UpdateDA\", \"UserName\", rowNum), reader.getCellData(\"UpdateDA\", \"Passwo", "end": 7567, "score": 0.6592856645584106, "start": 7559, "tag": "USERNAME", "value": "UserName" }, { "context": "ginType\", rowNum),reader.getCellData(\"UpdateDA\", \"UserName\", rowNum), reader.getCellData(\"UpdateDA\", \"Passwo", "end": 14253, "score": 0.785270631313324, "start": 14245, "tag": "USERNAME", "value": "UserName" } ]
null
[]
package pdms.tests; import java.io.IOException; import java.net.MalformedURLException; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import com.utilities.Base; import com.utilities.CustomListener; import com.utilities.excelComponent; import pdms.repository.AddPensionerPage; import pdms.repository.HomePage; import pdms.repository.LeftNavigationPage; import pdms.repository.UpdateDAPage; @Listeners(CustomListener.class) public class UpdateDATests extends Base { private String strDAObjId; public void testEMudhra() throws InterruptedException, IOException { loginUser(5,reader.getCellData("UpdateDA", "LoginType", 5),reader.getCellData("UpdateDA", "UserName", 5), reader.getCellData("UpdateDA", "Password", 5)); Thread.sleep(2000); clickOn(driver,UpdateDAPage.span_PDMSPendingTasks(driver),10); Thread.sleep(4000); driver.findElement(By.xpath("//a[contains(text(),'June 2019')]")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//button[contains(.,'Generate Digital Signature')]")).click(); Thread.sleep(5000); //String outlookApplicationPath = "C:\\Signer\\Signer\\Signer.exe"; //String winiumDriverPath = "C:\\Users\\uma.davuluri\\Downloads\\drk sarma\\Winium.Desktop.exe"; // DesktopOptions options = new DesktopOptions(); //Initiate Winium Desktop Options //options.setApplicationPath(outlookApplicationPath); //Set outlook application path // File drivePath = new File(winiumDriverPath); //Set winium driver path // WiniumDriverService service = new WiniumDriverService.Builder().usingDriverExecutable(drivePath).usingPort(9999).withVerbose(true).withSilent(false).buildDesktopService(); // service.start(); //Build and Start a Winium Driver service //WiniumDriver driverwin = new WiniumDriver(options); //Start a winium driver //String str[] = driverwin.getWindowHandles(); //Thread.sleep(5000); //driverwin.findElement(By.xpath("//button[contains(.,'Cancel')]")).click(); } @Test public void updateDATest() throws InterruptedException, ParseException, IOException { loggerExtentReport = extent.startTest("Update DA Test"); UpdateDA_SectionHead(2); UpdateDA_AuditOfficer(3); UpdateDA_DeputyDirector(4); UpdateDA_Comissioner(5); checkDAArrears(2); } public void checkDAArrears(int rowNum) throws InterruptedException, ParseException, IOException { String filePath = System.getProperty("user.dir") + "\\testResults\\"; String timestamp= getCurrentTimeStamp(); String strFile = "PDMS_DA_Arrears_" + timestamp; String[] headers = new String[] { "PPONumber", "TotalAmount", "ActualDRArrears", "ExpectedDRArrears", "Status"}; createExcelFile(filePath,strFile,"Results",headers); excelComponent DAreader = new excelComponent(filePath + strFile +".xlsx"); String strPPONum , strRtDate , strActualDAArrs, strExpDAArrs, strEffDate; double dblTotalAmt ,TotalDAArrears=0, dblDA_Months, dblNewDA, dblCurrDA; //dblDA_Months = Double.parseDouble(reader.getCellData("UpdateDA", "DA_Arr_Months", rowNum)); dblNewDA = Double.parseDouble(reader.getCellData("UpdateDA", "NewDA", rowNum)); dblCurrDA = Double.parseDouble(reader.getCellData("UpdateDA", "CurrentDA", rowNum)); dblNewDA = dblNewDA - dblCurrDA; strEffDate = reader.getCellData("UpdateDA", "FromDate", rowNum); strEffDate = getConvertodDate(strEffDate); strEffDate = ConvertDateMonthInTwoDigitFormat(strEffDate); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Date EffectDate = formatter.parse(strEffDate); Date PenRtDate; SoftAssert sftAssert = new SoftAssert(); loginUser(2,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); Thread.sleep(2000); clickOn(driver,HomePage.menu_DownArrow(driver),10); Thread.sleep(2000); clickOn(driver,HomePage.span_Reports(driver),10); selValue(driver,HomePage.sel_Reports_PensionerStatus(driver),10,"Active"); Thread.sleep(2000); int row=2,currtRow;; HomePage.btn_Action(driver, "Search"); Thread.sleep(5000); boolean pagination=true; while(pagination==true) { currtRow = DAreader.getRowCount("Results") +1; int rows = HomePage.tbl_Report_PensionersRows(driver); //System.out.println("ROW COUNT : "+rows); for (row=2;row<=rows;row++) { strPPONum = HomePage.tbl_Report_PensionersData(driver, row, 4).getText(); strRtDate = HomePage.tbl_Report_PensionersData(driver, row, 6).getText(); strActualDAArrs = HomePage.tbl_Report_PensionersData(driver, row, 28).getText(); strActualDAArrs = strActualDAArrs.substring(2,strActualDAArrs.length()); DAreader.setCellData("Results", "PPONumber", currtRow, strPPONum); DAreader.setCellData("Results", "ActualDRArrears", currtRow, strActualDAArrs); Double dblActDA = Double.valueOf(strActualDAArrs.replaceAll(",", "").toString()); String strTotalAmt = HomePage.tbl_Report_PensionersData(driver, row, 18).getText(); DecimalFormat df = new DecimalFormat("#,###,##0"); strTotalAmt = strTotalAmt.substring(2, strTotalAmt.length()); DAreader.setCellData("Results", "TotalAmount", currtRow, strTotalAmt); Double dblTotal = Double.valueOf(strTotalAmt.replaceAll(",", "").toString()); PenRtDate = formatter.parse(strRtDate); String strExpToDate = getLastDayOfTheMonth(); if(!strRtDate.equals("")) { if (PenRtDate.compareTo(EffectDate) > 0) { int Expectedmnths = getMonthsDifference(strRtDate, strExpToDate); TotalDAArrears = (Expectedmnths * dblNewDA * dblTotal)/100 ; //System.out.println("Rt date is greater EffDate"); }else if (PenRtDate.compareTo(EffectDate) <= 0) { int Expectedmnths = getMonthsDifference(strEffDate, strExpToDate); //TotalDAArrears = (dblDA_Months * dblNewDA * dblTotal)/100 ; TotalDAArrears = (Expectedmnths * dblNewDA * dblTotal)/100 ; } TotalDAArrears = Math.round(TotalDAArrears); if(TotalDAArrears == dblActDA) { DAreader.setCellData("Results", "Status", currtRow, "Pass"); } else { DAreader.setCellData("Results", "Status", currtRow, "Fail"); } String strFinalAmt = df.format(TotalDAArrears); DAreader.setCellData("Results", "ExpectedDRArrears", currtRow, strFinalAmt); } currtRow = currtRow+1; }//end for loop if(UpdateDAPage.btn_PaginationNext(driver).isDisplayed() == true) { clickOn(driver,UpdateDAPage.btn_PaginationNext(driver),10); Thread.sleep(5000); row=2; pagination = true; } else { pagination = false; } }//end while loop } private void UpdateDA_SectionHead(int rowNum) throws InterruptedException, ParseException { SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); //verify current DA field String strActualDA = UpdateDAPage.span_DAPercentage(driver).getText(); String strExpectedDA = reader.getCellData("UpdateDA", "CurrentDA", rowNum); Assert.assertEquals(Double.parseDouble(strActualDA), Double.parseDouble(strExpectedDA), "Current DA not matched"); //enter New DA field UpdateDAPage.txtbx_NewDA(driver).sendKeys(Keys.CONTROL + "a"); Thread.sleep(1000); UpdateDAPage.txtbx_NewDA(driver).sendKeys(Keys.DELETE); Thread.sleep(1000); sendkeys(driver,UpdateDAPage.txtbx_NewDA(driver),20,reader.getCellData("UpdateDA", "NewDA", rowNum)); //enter From / Effective Date clickOn(driver,UpdateDAPage.calendar_FromDate(driver),10); Thread.sleep(2000); DatePicker(reader.getCellData("UpdateDA", "FromDate", rowNum)); Thread.sleep(2000); //verify To Date String strActualToDate = UpdateDAPage.span_ToDate(driver).getText(); String strExpToDate = getLastDayOfTheMonth(); sftAssert.assertEquals(strActualToDate, strExpToDate, "Mismatch in To Date"); //verify DA for Months String strFrom = UpdateDAPage.calendar_FromDate(driver).getAttribute("innerText"); strFrom.trim(); int Expectedmnths = getMonthsDifference(strFrom, UpdateDAPage.span_ToDate(driver).getText()); String strMonths = UpdateDAPage.span_DAforMonths(driver).getText() ; int intactualMonths = Integer.parseInt(strMonths); Assert.assertEquals(intactualMonths, Expectedmnths,"Mismatch in DA for Months"); reader.setCellData("Properties", "OldDA", 2,strActualDA); reader.setCellData("Properties", "CurrentDA", 2, reader.getCellData("UpdateDA", "NewDA", rowNum)); reader.setCellData("Properties", "DAMonths", 2, strMonths); reader.setCellData("Properties", "DAEffDate", 2, UpdateDAPage.calendar_FromDate(driver).getText()); clickOn(driver,UpdateDAPage.btn_Action(driver, "Attach GO"),10); Thread.sleep(2000); UploadFiles.uploadDocument(reader.getCellData("UpdateDA", "Modal_FileName", rowNum), reader.getCellData("UpdateDA", "Modal_File", rowNum), reader.getCellData("UpdateDA", "Modal_Category", rowNum), sftAssert); /*if(bln==true) { if(UpdateDAPage.lnk_File(driver, reader.getCellData("UpdateDA", "Modal_FileName", rowNum)).isDisplayed() == true) { Assert.assertEquals(true, true); } else { Assert.assertEquals(false, true,"Upload unsuccessful"); } clickOn(driver,UpdateDAPage.btn_Action(driver, "Update"),10); }*/ clickOn(driver,UpdateDAPage.btn_Action(driver, "Update"),10); Thread.sleep(3000); /*if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); }*/ clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); Thread.sleep(5000); boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Audit Officer").isDisplayed(); sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-AuditOfficer").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); getDAObjectId(); reader.setCellData("UpdateDA", "DAObjID", 2, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 3, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 4, strDAObjId); reader.setCellData("UpdateDA", "DAObjID", 5, strDAObjId); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_AuditOfficer(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); //boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Deputy Director").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-DeputyDirector").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_DeputyDirector(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); //boolean flg= UpdateDAPage.span_ConfirmMsg(driver,"This case has been routed successfully to the Commissioner").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); //flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pending-Commissioner").isDisplayed(); //sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); //Thread.sleep(3000); LogOut(); sftAssert.assertAll(); } private void UpdateDA_Comissioner(int rowNum) throws InterruptedException, ParseException { // TODO Auto-generated method stub SoftAssert sftAssert = new SoftAssert(); loginUser(rowNum,reader.getCellData("UpdateDA", "LoginType", rowNum),reader.getCellData("UpdateDA", "UserName", rowNum), reader.getCellData("UpdateDA", "Password", rowNum)); clickOn(driver,UpdateDAPage.span_PDMSPendingTasks(driver),10); Thread.sleep(4000); //Navigate to Current DA page navigateToUpDateDA(reader.getCellData("UpdateDA", "DAObjID", rowNum)); verifyDAReadOnlyFields(rowNum,sftAssert); clickOn(driver,UpdateDAPage.btn_Action(driver, "Approve"),10); Thread.sleep(2000); if(UpdateDAPage.span_Confirm(driver).isDisplayed()==true) { clickOn(driver,UpdateDAPage.btn_Action(driver, "OK"),10); } Thread.sleep(3000); /*boolean flg= UpdateDAPage.span_MsgPendingInfo(driver,"Pensioner records are successfully updated with new DA").isDisplayed(); sftAssert.assertTrue(flg,"Confirmation message was not dispalyed after submission"); clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(2000);*/ LogOut(); sftAssert.assertAll(); } private void verifyDAReadOnlyFields(int rowNum , SoftAssert asst) throws ParseException, InterruptedException { //verify current DA field String strActual = UpdateDAPage.span_DAReadonlyField(driver, "Current DA %").getText(); String strExpected = reader.getCellData("UpdateDA", "CurrentDA", rowNum); asst.assertEquals(Double.parseDouble(strActual), Double.parseDouble(strExpected), "Current DA not matched"); //verify New DA % strActual = UpdateDAPage.span_DAReadonlyField(driver, "New DA %").getText(); strExpected = reader.getCellData("UpdateDA", "NewDA", rowNum); asst.assertEquals(Double.parseDouble(strActual), Double.parseDouble(strExpected), "New DA not matched"); //verify From Date strExpected = getConvertodDate(reader.getCellData("UpdateDA", "FromDate", rowNum)); strExpected = ConvertDateMonthInTwoDigitFormat(strExpected); strActual = UpdateDAPage.span_DAReadonlyField(driver, "From Date").getText(); //verify To Date strActual = UpdateDAPage.span_DAReadonlyField(driver, "To Date").getText(); strExpected = getLastDayOfTheMonth(); asst.assertEquals(strActual, strExpected, "Mismatch in To Date"); //verify To Date strActual = UpdateDAPage.span_DAReadonlyField(driver, "DA for months").getText(); int mnths = getMonthsDifference(UpdateDAPage.span_DAReadonlyField(driver, "From Date").getText(), UpdateDAPage.span_DAReadonlyField(driver, "To Date").getText()); asst.assertEquals(Integer.parseInt(strActual), mnths, "Mismatch in To Date"); if(UpdateDAPage.lnk_File(driver, reader.getCellData("UpdateDA", "Modal_FileName", rowNum)).isDisplayed() == true) { asst.assertEquals(true, true); } else { asst.assertEquals(false, true,"Upload unsuccessful"); } //clickOn(driver,UpdateDAPage.btn_Action(driver, "Close"),10); Thread.sleep(3000); } private void navigateToUpDateDA(String strDAID) throws InterruptedException { if(strDAID.isEmpty()) { //Navigate to Add New Pensioner from Left Pane navigateToDA(); } else { HomeTests.UpdateDASearch(strDAID); strDAObjId = strDAID; } } private void navigateToDA() throws InterruptedException { clickOn(driver,LeftNavigationPage.lnk_UpdateDA(driver),10); Thread.sleep(3000); } private void getDAObjectId() { if(UpdateDAPage.span_DAObjectId(driver).isDisplayed()==true) { strDAObjId = UpdateDAPage.span_DAObjectId(driver).getText(); strDAObjId=strDAObjId.substring(1, strDAObjId.length()-1); //Removing First & last characters from string () logfile.info("Fetched DA Work Object Id as : " + strDAObjId); } } }
17,767
0.713289
0.700681
381
44.632545
38.421021
210
false
false
0
0
0
0
0
0
2.887139
false
false
7
6dc4519954e11dafe9334f2b763a980ccf9d8a34
28,011,776,769,197
db1114568c2893f7766ca1646811608607d0e042
/renrenentity/src/main/java/com/renrentui/renrenentity/MenuInfo.java
94213e89ce98b8df24d0c51259fcb93af7260d97
[]
no_license
xiaotou745/et-rrt
https://github.com/xiaotou745/et-rrt
ef6d57041a91edf224d86a2a5e7f63d82114d56c
ba84b7f2536603871ac0692f67259daa2dd96be1
refs/heads/master
2021-01-01T05:17:41.195000
2015-11-24T08:35:47
2015-11-24T08:36:12
56,681,334
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.renrentui.renrenentity; import java.io.Serializable; public class MenuInfo implements Serializable{ private Integer id; private Integer parId; private String menuName; private Boolean beLock; private String url; private Boolean isButton; private String authCode; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public Integer getParId() { return parId; } public void setParId(Integer parId) { this.parId = parId; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public Boolean getBeLock() { return beLock; } public void setBeLock(Boolean beLock) { this.beLock = beLock; } public Boolean getIsButton() { return isButton; } public void setIsButton(Boolean isButton) { this.isButton = isButton; } public String getAuthCode() { return "UPDATE_TASK"; } public void setAuthCode(String authCode) { this.authCode = authCode; } }
UTF-8
Java
1,227
java
MenuInfo.java
Java
[]
null
[]
package com.renrentui.renrenentity; import java.io.Serializable; public class MenuInfo implements Serializable{ private Integer id; private Integer parId; private String menuName; private Boolean beLock; private String url; private Boolean isButton; private String authCode; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public Integer getParId() { return parId; } public void setParId(Integer parId) { this.parId = parId; } public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public Boolean getBeLock() { return beLock; } public void setBeLock(Boolean beLock) { this.beLock = beLock; } public Boolean getIsButton() { return isButton; } public void setIsButton(Boolean isButton) { this.isButton = isButton; } public String getAuthCode() { return "UPDATE_TASK"; } public void setAuthCode(String authCode) { this.authCode = authCode; } }
1,227
0.655257
0.655257
78
14.743589
15.192303
51
false
false
0
0
0
0
0
0
0.807692
false
false
7
44bebc9752c691964ffbb191dad9e8b417efcc84
15,461,882,290,554
d9223a2b7d53ef7405c5161b68cb8fc312302dd8
/java/com/com2us/module/inapp/googleplay/BillingDatabase.java
2a83a5d6bcb636f931ad1b549f9765651337f645
[]
no_license
cpjreynolds/swar
https://github.com/cpjreynolds/swar
24e3ad2ec35cec55afe8c620c2d90c08654f061c
39911c3580b37e5f3425e0e13d5e4341412d3b0e
refs/heads/master
2021-01-10T12:41:58.223000
2015-12-01T23:51:14
2015-12-01T23:51:14
47,224,636
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.com2us.module.inapp.googleplay; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.lang.reflect.Array; public class BillingDatabase { private DatabaseHelper mDatabaseHelper; private SQLiteDatabase mDb = this.mDatabaseHelper.getWritableDatabase(); private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, Utility.getString(0), null, 1); } public void onCreate(SQLiteDatabase db) { createPurchaseTable(db); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("Upgrading database from version " + oldVersion + " to " + newVersion + "."); db.execSQL("CREATE TABLE IF NOT EXISTS " + Utility.getString(1) + "(" + Utility.getString(7) + " TEXT PRIMARY KEY, " + Utility.getString(2) + " TEXT, " + Utility.getString(3) + " TEXT, " + Utility.getString(4) + " TEXT)"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Utility.getString(5) + "(" + Utility.getString(6) + " TEXT PRIMARY KEY)"); } private void createPurchaseTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Utility.getString(1) + "(" + Utility.getString(7) + " TEXT PRIMARY KEY, " + Utility.getString(2) + " TEXT, " + Utility.getString(3) + " TEXT, " + Utility.getString(4) + " TEXT)"); db.execSQL("CREATE TABLE " + Utility.getString(5) + "(" + Utility.getString(6) + " TEXT PRIMARY KEY)"); } } public BillingDatabase(Context context) { this.mDatabaseHelper = new DatabaseHelper(context); } public void close() { this.mDatabaseHelper.close(); } public synchronized void updatePurchase(String signedData, String signature, String responseStr) { ContentValues values = new ContentValues(); values.put(Utility.getString(7), signedData); values.put(Utility.getString(2), signedData); values.put(Utility.getString(3), signature); values.put(Utility.getString(4), responseStr); this.mDb.replace(Utility.getString(1), null, values); } public synchronized void deletePurchase(String signedData) { this.mDb.delete(Utility.getString(1), Utility.getString(7) + "=?", new String[]{signedData}); } public synchronized String[][] getPurchaseData() { String[][] strArr; Cursor cursor = this.mDb.query(Utility.getString(1), new String[]{Utility.getString(7), Utility.getString(2), Utility.getString(3), Utility.getString(4)}, null, null, null, null, null, null); if (cursor == null) { strArr = null; } else { String[][] ret = (String[][]) Array.newInstance(String.class, new int[]{cursor.getCount(), 4}); int cnt = 0; while (cursor.moveToNext()) { try { ret[cnt][0] = cursor.getString(0); ret[cnt][1] = cursor.getString(1); ret[cnt][2] = cursor.getString(2); ret[cnt][3] = cursor.getString(3); cnt++; } catch (Throwable th) { if (cursor != null) { cursor.close(); } } } if (cursor != null) { cursor.close(); } strArr = ret; } return strArr; } public synchronized void updateLogData(String logData) { ContentValues values = new ContentValues(); values.put(Utility.getString(6), logData); this.mDb.replace(Utility.getString(5), null, values); } public synchronized void deleteLogData(String hash) { this.mDb.delete(Utility.getString(5), Utility.getString(6) + "=?", new String[]{hash}); } public synchronized String[][] getLogData() { String[][] strArr; Cursor cursor = this.mDb.query(Utility.getString(5), new String[]{Utility.getString(6)}, null, null, null, null, null, null); if (cursor == null) { strArr = null; } else { String[][] ret = (String[][]) Array.newInstance(String.class, new int[]{cursor.getCount(), 1}); int cnt = 0; while (cursor.moveToNext()) { try { ret[cnt][0] = cursor.getString(0); cnt++; } catch (Throwable th) { if (cursor != null) { cursor.close(); } } } if (cursor != null) { cursor.close(); } strArr = ret; } return strArr; } }
UTF-8
Java
4,893
java
BillingDatabase.java
Java
[]
null
[]
package com.com2us.module.inapp.googleplay; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.lang.reflect.Array; public class BillingDatabase { private DatabaseHelper mDatabaseHelper; private SQLiteDatabase mDb = this.mDatabaseHelper.getWritableDatabase(); private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, Utility.getString(0), null, 1); } public void onCreate(SQLiteDatabase db) { createPurchaseTable(db); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("Upgrading database from version " + oldVersion + " to " + newVersion + "."); db.execSQL("CREATE TABLE IF NOT EXISTS " + Utility.getString(1) + "(" + Utility.getString(7) + " TEXT PRIMARY KEY, " + Utility.getString(2) + " TEXT, " + Utility.getString(3) + " TEXT, " + Utility.getString(4) + " TEXT)"); db.execSQL("CREATE TABLE IF NOT EXISTS " + Utility.getString(5) + "(" + Utility.getString(6) + " TEXT PRIMARY KEY)"); } private void createPurchaseTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Utility.getString(1) + "(" + Utility.getString(7) + " TEXT PRIMARY KEY, " + Utility.getString(2) + " TEXT, " + Utility.getString(3) + " TEXT, " + Utility.getString(4) + " TEXT)"); db.execSQL("CREATE TABLE " + Utility.getString(5) + "(" + Utility.getString(6) + " TEXT PRIMARY KEY)"); } } public BillingDatabase(Context context) { this.mDatabaseHelper = new DatabaseHelper(context); } public void close() { this.mDatabaseHelper.close(); } public synchronized void updatePurchase(String signedData, String signature, String responseStr) { ContentValues values = new ContentValues(); values.put(Utility.getString(7), signedData); values.put(Utility.getString(2), signedData); values.put(Utility.getString(3), signature); values.put(Utility.getString(4), responseStr); this.mDb.replace(Utility.getString(1), null, values); } public synchronized void deletePurchase(String signedData) { this.mDb.delete(Utility.getString(1), Utility.getString(7) + "=?", new String[]{signedData}); } public synchronized String[][] getPurchaseData() { String[][] strArr; Cursor cursor = this.mDb.query(Utility.getString(1), new String[]{Utility.getString(7), Utility.getString(2), Utility.getString(3), Utility.getString(4)}, null, null, null, null, null, null); if (cursor == null) { strArr = null; } else { String[][] ret = (String[][]) Array.newInstance(String.class, new int[]{cursor.getCount(), 4}); int cnt = 0; while (cursor.moveToNext()) { try { ret[cnt][0] = cursor.getString(0); ret[cnt][1] = cursor.getString(1); ret[cnt][2] = cursor.getString(2); ret[cnt][3] = cursor.getString(3); cnt++; } catch (Throwable th) { if (cursor != null) { cursor.close(); } } } if (cursor != null) { cursor.close(); } strArr = ret; } return strArr; } public synchronized void updateLogData(String logData) { ContentValues values = new ContentValues(); values.put(Utility.getString(6), logData); this.mDb.replace(Utility.getString(5), null, values); } public synchronized void deleteLogData(String hash) { this.mDb.delete(Utility.getString(5), Utility.getString(6) + "=?", new String[]{hash}); } public synchronized String[][] getLogData() { String[][] strArr; Cursor cursor = this.mDb.query(Utility.getString(5), new String[]{Utility.getString(6)}, null, null, null, null, null, null); if (cursor == null) { strArr = null; } else { String[][] ret = (String[][]) Array.newInstance(String.class, new int[]{cursor.getCount(), 1}); int cnt = 0; while (cursor.moveToNext()) { try { ret[cnt][0] = cursor.getString(0); cnt++; } catch (Throwable th) { if (cursor != null) { cursor.close(); } } } if (cursor != null) { cursor.close(); } strArr = ret; } return strArr; } }
4,893
0.568363
0.558349
120
39.775002
41.042145
234
false
false
0
0
0
0
0
0
0.841667
false
false
7
9d9e874f25cf662f1565f295f527433af2b6249a
10,539,849,770,996
0fbe667a1356219480e7c889da46bc00bfba786d
/auth-service/src/test/java/com/piggymetrics/auth/repository/UserRepositoryTest.java
8fd4b9411bf36939760ed1017d79b8277ee0d20f
[ "MIT" ]
permissive
DataSays/PiggyMetrics
https://github.com/DataSays/PiggyMetrics
55db4ca755ce5919b9a0c8c192865b2ac8dbc885
5a220e4db3630e555984692ba0ce2fdc399050d7
refs/heads/master
2021-01-09T05:51:40.946000
2017-02-08T08:39:08
2017-02-08T08:39:08
80,849,288
4
0
null
true
2017-02-08T07:32:40
2017-02-03T16:56:04
2017-02-03T16:56:06
2017-02-05T05:31:48
1,404
0
0
1
Java
null
null
package com.piggymetrics.auth.repository; import com.piggymetrics.auth.AuthApplication; import com.piggymetrics.auth.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class UserRepositoryTest { @Autowired private UserRepository repository; @Test public void shouldSaveAndFindUserByName() { User user = new User(); user.setUsername("name"); user.setPassword("password"); repository.save(user); User found = repository.findOne(user.getUsername()); assertEquals(user.getUsername(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); } }
UTF-8
Java
942
java
UserRepositoryTest.java
Java
[ { "context": " {\n\n\t\tUser user = new User();\n\t\tuser.setUsername(\"name\");\n\t\tuser.setPassword(\"password\");\n\t\trepository.s", "end": 706, "score": 0.9884113073348999, "start": 702, "tag": "USERNAME", "value": "name" }, { "context": ";\n\t\tuser.setUsername(\"name\");\n\t\tuser.setPassword(\"password\");\n\t\trepository.save(user);\n\n\t\tUser found = repos", "end": 738, "score": 0.9995948672294617, "start": 730, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.piggymetrics.auth.repository; import com.piggymetrics.auth.AuthApplication; import com.piggymetrics.auth.domain.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class UserRepositoryTest { @Autowired private UserRepository repository; @Test public void shouldSaveAndFindUserByName() { User user = new User(); user.setUsername("name"); user.setPassword("<PASSWORD>"); repository.save(user); User found = repository.findOne(user.getUsername()); assertEquals(user.getUsername(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); } }
944
0.800425
0.79724
32
28.4375
22.188028
71
false
false
0
0
0
0
0
0
1.1875
false
false
7
b4172d230fbdf4b32a29be3e45ea7c182b25a862
11,819,750,030,192
91c41b04277c2a5e3f312e926b1cd430edc3824b
/cde-pentaho/test-src/pt/webdetails/cdf/dd/MockParameterProvider.java
f4b801bbe8831aded7d7df31dedcf6f970c10945
[]
no_license
pmalves/cde
https://github.com/pmalves/cde
9988111640df9b33e7fef211372e86c8ed4d9fd7
2121d1f0c8c5a1cf0b019835f421b0e01172e6f7
refs/heads/master
2021-01-14T13:44:05.520000
2014-10-08T03:03:04
2014-10-08T03:03:04
931,255
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
/*! * Copyright 2002 - 2014 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cdf.dd; import org.pentaho.platform.api.engine.IParameterProvider; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Iterator; public class MockParameterProvider implements IParameterProvider { private HashMap parameters; public MockParameterProvider (HashMap parameters) { this.parameters = parameters; } public MockParameterProvider () { this.parameters = new HashMap<String, Object>(); } @Override public String getStringParameter( String s, String s2 ) { if (parameters.get( s ) != null && parameters.get( s ) instanceof String) { return (String) parameters.get( s ); } else { return s2; } } @Override public long getLongParameter( String s, long l ) { return 0; } @Override public Date getDateParameter( String s, Date date ) { return null; } @Override public BigDecimal getDecimalParameter( String s, BigDecimal bigDecimal ) { return null; } @Override public Object[] getArrayParameter( String s, Object[] objects ) { return new Object[0]; } @Override public String[] getStringArrayParameter( String s, String[] strings ) { return new String[0]; } @Override public Iterator getParameterNames() { return null; } @Override public Object getParameter( String s ) { return parameters.get( s ); } @Override public boolean hasParameter( String s ) { return false; } public void setParameter(String key, Object value) { parameters.put( key, value ); } }
UTF-8
Java
2,217
java
MockParameterProvider.java
Java
[]
null
[]
/*! * Copyright 2002 - 2014 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cdf.dd; import org.pentaho.platform.api.engine.IParameterProvider; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Iterator; public class MockParameterProvider implements IParameterProvider { private HashMap parameters; public MockParameterProvider (HashMap parameters) { this.parameters = parameters; } public MockParameterProvider () { this.parameters = new HashMap<String, Object>(); } @Override public String getStringParameter( String s, String s2 ) { if (parameters.get( s ) != null && parameters.get( s ) instanceof String) { return (String) parameters.get( s ); } else { return s2; } } @Override public long getLongParameter( String s, long l ) { return 0; } @Override public Date getDateParameter( String s, Date date ) { return null; } @Override public BigDecimal getDecimalParameter( String s, BigDecimal bigDecimal ) { return null; } @Override public Object[] getArrayParameter( String s, Object[] objects ) { return new Object[0]; } @Override public String[] getStringArrayParameter( String s, String[] strings ) { return new String[0]; } @Override public Iterator getParameterNames() { return null; } @Override public Object getParameter( String s ) { return parameters.get( s ); } @Override public boolean hasParameter( String s ) { return false; } public void setParameter(String key, Object value) { parameters.put( key, value ); } }
2,217
0.716734
0.709066
77
27.792208
29.981958
86
false
false
0
0
0
0
0
0
0.454545
false
false
7
52ac8beb30bd35cf16a3334f71b1656529b823a0
31,499,290,173,714
412bb06cd78c9109f80b1952dba66e5c72e6c427
/java/littlebreadloaf/bleach/entities/EntityMenosGrande.java
1dd4d1b341f9624f4251bc73dccfd59433c3f56b
[]
no_license
MaxFuryBleach/BleachMod2
https://github.com/MaxFuryBleach/BleachMod2
09f1d0d398f6aeb4efbbf71892a4ac0b3750ae2d
d7b81e4b78f6a9767e86d1fb7b2503cfff189578
refs/heads/master
2020-03-30T12:50:09.726000
2018-10-02T11:25:01
2018-10-02T11:25:01
151,243,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package littlebreadloaf.bleach.entities; import java.util.Random; import littlebreadloaf.bleach.events.ExtendedPlayer; import littlebreadloaf.bleach.items.BleachItems; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIMoveTowardsRestriction; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAITasks; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; public class EntityMenosGrande extends EntityMob { public int deathTicks = 0; private int ceroCooldown = 100; private int ceroCharging = 60; private EntityPlayer target = null; public EntityMenosGrande(World par1World) { super(par1World); this.tasks.addTask(1, new EntityAIAttackOnCollide(this, EntityPlayer.class, 0.4D, false)); this.tasks.addTask(2, new EntityAIAttackOnCollide(this, EntityWhole.class, 0.4D, false)); this.tasks.addTask(3, new EntityAIAttackOnCollide(this, EntityShinigami.class, 0.4D, false)); this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 0.4D)); this.tasks.addTask(6, new EntityAIWander(this, 0.4D)); this.tasks.addTask(7, new EntityAILookIdle(this)); this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(9, new EntityAIWatchClosest(this, EntityWhole.class, 8.0F)); this.targetTasks.addTask(0, new net.minecraft.entity.ai.EntityAIHurtByTarget(this, false)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, 0, true)); this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityWhole.class, 0, false)); this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityShinigami.class, 0, false)); this.isImmuneToFire = true; this.ignoreFrustumCheck = true; setSize(1.9F, 20.9F); this.stepHeight = 3.5F; } public float getEyeHeight() { return this.height - 1.0F; } protected boolean isAIEnabled() { return true; } public int getTotalArmorValue() { return 4; } protected void applyEntityAttributes() { super.applyEntityAttributes(); if ((this.worldObj.difficultySetting == EnumDifficulty.NORMAL) || (this.worldObj.difficultySetting == EnumDifficulty.HARD)) { getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(170.0D); getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(8.0D); } else { getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(150.0D); getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); } getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(60.0D); getEntityAttribute(SharedMonsterAttributes.knockbackResistance).setBaseValue(10.0D); } public net.minecraft.entity.EnumCreatureAttribute getCreatureAttribute() { return littlebreadloaf.bleach.api.Tools.SPIRIT; } protected String getHurtSound() { if (this.rand.nextInt(2) == 0) { return "bleach:hollowscream"; } return null; } protected String getLivingSound() { if (this.rand.nextInt(100) >= 25) { return "bleach:hollowscream"; } return null; } protected String getDeathSound() { return "bleach:hollowscream"; } protected float getSoundPitch() { return super.getSoundPitch() * 0.8F; } protected float getSoundVolume() { return 3.0F; } protected void dropFewItems(boolean par1, int par2) { super.dropFewItems(par1, par2); entityDropItem(new ItemStack(BleachItems.reiatsu, 8 + this.rand.nextInt(3) + par2), 0.0F); if (this.rand.nextInt(20 - par2) == 0) { dropItem(BleachItems.menosmask, 1); } } public void onLivingUpdate() { super.onLivingUpdate(); } public int getMaxSpawnedInChunk() { return 16; } protected void fall(float var1) {} protected void onDeathUpdate() { this.deathTicks += 1; int var1 = MathHelper.floor_double(this.posY); int var2 = MathHelper.floor_double(this.posX); int var3 = MathHelper.floor_double(this.posZ); if (this.deathTicks <= 200) { for (int var4 = -3; var4 <= 3; var4++) { for (int var5 = -3; var5 <= 3; var5++) { for (int var6 = -1; var6 <= 20; var6++) { if (this.rand.nextInt(1500) == 0) { int var7 = var2 + var4; int var8 = var1 + var6; int var9 = var3 + var5; this.worldObj.spawnParticle("largeexplode", var7, var8, var9, 0.0D, 0.0D, 0.0D); } } } } } if (!this.worldObj.isRemote) { if ((this.deathTicks > 150) && (this.deathTicks % 5 == 0)) { int var4 = 10; while (var4 > 0) { int var5 = EntityXPOrb.getXPSplit(var4); var4 -= var5; this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, var5)); } } if (this.deathTicks == 1) { this.worldObj.playBroadcastSound(1018, (int)this.posX, (int)this.posY, (int)this.posZ, 0); } } if ((this.deathTicks == 200) && (!this.worldObj.isRemote)) { int var4 = 10; while (var4 > 0) { int var5 = EntityXPOrb.getXPSplit(var4); var4 -= var5; this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, var5)); } setDead(); } } public void onDeath(DamageSource par1DamageSource) { super.onDeath(par1DamageSource); Item var2; if ((par1DamageSource.getEntity() instanceof EntityPlayer)) { ExtendedPlayer props = (ExtendedPlayer)this.attackingPlayer.getExtendedProperties("BleachPlayer"); if (props.getFaction() == 3) props.addSXP(10); if ((props.getFaction() == 1) && (this.attackingPlayer.inventory.getCurrentItem() != null) && (this.attackingPlayer.inventory.getCurrentItem().getItem() == BleachItems.zanpakuto) && (props.getZTotal() < 376)) { for (int i = 0; i < 25; i++) { props.addPoints(this.rand.nextInt(8) + 1, 1); } } if (this.rand.nextInt(50) == 0) { var2 = BleachItems.recordNumberOne; } } } public int getChargingProgress() { return this.ceroCharging; } public boolean getCanSpawnHere() { return (this.posY < 50.0D) && (this.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) && (!this.worldObj.isAnyLiquid(this.boundingBox)); } public boolean canDespawn() { return false; } }
UTF-8
Java
7,590
java
EntityMenosGrande.java
Java
[]
null
[]
package littlebreadloaf.bleach.entities; import java.util.Random; import littlebreadloaf.bleach.events.ExtendedPlayer; import littlebreadloaf.bleach.items.BleachItems; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAIAttackOnCollide; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIMoveTowardsRestriction; import net.minecraft.entity.ai.EntityAINearestAttackableTarget; import net.minecraft.entity.ai.EntityAITasks; import net.minecraft.entity.ai.EntityAIWander; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; public class EntityMenosGrande extends EntityMob { public int deathTicks = 0; private int ceroCooldown = 100; private int ceroCharging = 60; private EntityPlayer target = null; public EntityMenosGrande(World par1World) { super(par1World); this.tasks.addTask(1, new EntityAIAttackOnCollide(this, EntityPlayer.class, 0.4D, false)); this.tasks.addTask(2, new EntityAIAttackOnCollide(this, EntityWhole.class, 0.4D, false)); this.tasks.addTask(3, new EntityAIAttackOnCollide(this, EntityShinigami.class, 0.4D, false)); this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 0.4D)); this.tasks.addTask(6, new EntityAIWander(this, 0.4D)); this.tasks.addTask(7, new EntityAILookIdle(this)); this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(9, new EntityAIWatchClosest(this, EntityWhole.class, 8.0F)); this.targetTasks.addTask(0, new net.minecraft.entity.ai.EntityAIHurtByTarget(this, false)); this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, 0, true)); this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityWhole.class, 0, false)); this.targetTasks.addTask(3, new EntityAINearestAttackableTarget(this, EntityShinigami.class, 0, false)); this.isImmuneToFire = true; this.ignoreFrustumCheck = true; setSize(1.9F, 20.9F); this.stepHeight = 3.5F; } public float getEyeHeight() { return this.height - 1.0F; } protected boolean isAIEnabled() { return true; } public int getTotalArmorValue() { return 4; } protected void applyEntityAttributes() { super.applyEntityAttributes(); if ((this.worldObj.difficultySetting == EnumDifficulty.NORMAL) || (this.worldObj.difficultySetting == EnumDifficulty.HARD)) { getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(170.0D); getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(8.0D); } else { getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(150.0D); getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); } getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(60.0D); getEntityAttribute(SharedMonsterAttributes.knockbackResistance).setBaseValue(10.0D); } public net.minecraft.entity.EnumCreatureAttribute getCreatureAttribute() { return littlebreadloaf.bleach.api.Tools.SPIRIT; } protected String getHurtSound() { if (this.rand.nextInt(2) == 0) { return "bleach:hollowscream"; } return null; } protected String getLivingSound() { if (this.rand.nextInt(100) >= 25) { return "bleach:hollowscream"; } return null; } protected String getDeathSound() { return "bleach:hollowscream"; } protected float getSoundPitch() { return super.getSoundPitch() * 0.8F; } protected float getSoundVolume() { return 3.0F; } protected void dropFewItems(boolean par1, int par2) { super.dropFewItems(par1, par2); entityDropItem(new ItemStack(BleachItems.reiatsu, 8 + this.rand.nextInt(3) + par2), 0.0F); if (this.rand.nextInt(20 - par2) == 0) { dropItem(BleachItems.menosmask, 1); } } public void onLivingUpdate() { super.onLivingUpdate(); } public int getMaxSpawnedInChunk() { return 16; } protected void fall(float var1) {} protected void onDeathUpdate() { this.deathTicks += 1; int var1 = MathHelper.floor_double(this.posY); int var2 = MathHelper.floor_double(this.posX); int var3 = MathHelper.floor_double(this.posZ); if (this.deathTicks <= 200) { for (int var4 = -3; var4 <= 3; var4++) { for (int var5 = -3; var5 <= 3; var5++) { for (int var6 = -1; var6 <= 20; var6++) { if (this.rand.nextInt(1500) == 0) { int var7 = var2 + var4; int var8 = var1 + var6; int var9 = var3 + var5; this.worldObj.spawnParticle("largeexplode", var7, var8, var9, 0.0D, 0.0D, 0.0D); } } } } } if (!this.worldObj.isRemote) { if ((this.deathTicks > 150) && (this.deathTicks % 5 == 0)) { int var4 = 10; while (var4 > 0) { int var5 = EntityXPOrb.getXPSplit(var4); var4 -= var5; this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, var5)); } } if (this.deathTicks == 1) { this.worldObj.playBroadcastSound(1018, (int)this.posX, (int)this.posY, (int)this.posZ, 0); } } if ((this.deathTicks == 200) && (!this.worldObj.isRemote)) { int var4 = 10; while (var4 > 0) { int var5 = EntityXPOrb.getXPSplit(var4); var4 -= var5; this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, var5)); } setDead(); } } public void onDeath(DamageSource par1DamageSource) { super.onDeath(par1DamageSource); Item var2; if ((par1DamageSource.getEntity() instanceof EntityPlayer)) { ExtendedPlayer props = (ExtendedPlayer)this.attackingPlayer.getExtendedProperties("BleachPlayer"); if (props.getFaction() == 3) props.addSXP(10); if ((props.getFaction() == 1) && (this.attackingPlayer.inventory.getCurrentItem() != null) && (this.attackingPlayer.inventory.getCurrentItem().getItem() == BleachItems.zanpakuto) && (props.getZTotal() < 376)) { for (int i = 0; i < 25; i++) { props.addPoints(this.rand.nextInt(8) + 1, 1); } } if (this.rand.nextInt(50) == 0) { var2 = BleachItems.recordNumberOne; } } } public int getChargingProgress() { return this.ceroCharging; } public boolean getCanSpawnHere() { return (this.posY < 50.0D) && (this.worldObj.difficultySetting != EnumDifficulty.PEACEFUL) && (!this.worldObj.isAnyLiquid(this.boundingBox)); } public boolean canDespawn() { return false; } }
7,590
0.65191
0.625955
414
17.333334
28.120857
214
false
false
0
0
0
0
0
0
0.400966
false
false
7
1226adf706693ae312c9a1d638892e5e6ff604f1
29,815,662,992,680
e86004cdaa62945953a895304056c856c6944a27
/app/src/main/java/com/ychong/androidwan/http/AddCookieInterceptor.java
29f47e908b18475937c8ae3abd478b3a5df08f1d
[]
no_license
ychong996/AndroidWan
https://github.com/ychong996/AndroidWan
22158931cdcce000a9e98b6a7eab3fbb252db3df
6b2022a1b78a8f7cc5ab02b30e18e82be09eb7d4
refs/heads/master
2021-06-15T17:54:33.256000
2021-05-18T12:53:44
2021-05-18T12:53:44
196,672,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ychong.androidwan.http; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import com.ychong.androidwan.utils.Constants; import com.ychong.library.utils.SPUtils; import java.io.IOException; import io.reactivex.Observable; import io.reactivex.functions.Consumer; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * @author ychong */ public class AddCookieInterceptor implements Interceptor { private Context context; public AddCookieInterceptor(Context context){ super(); this.context = context; } @SuppressLint("CheckResult") @Override public Response intercept(Chain chain) throws IOException { final Request.Builder builder = chain.request().newBuilder(); Observable.just(SPUtils.getInstance(context).getString(Constants.COOKIE_KEY)) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { builder.addHeader("Cookie",s); } }); return chain.proceed(builder.build()); } }
UTF-8
Java
1,208
java
AddCookieInterceptor.java
Java
[ { "context": ".Request;\nimport okhttp3.Response;\n\n/**\n * @author ychong\n */\npublic class AddCookieInterceptor implements ", "end": 440, "score": 0.9996703267097473, "start": 434, "tag": "USERNAME", "value": "ychong" } ]
null
[]
package com.ychong.androidwan.http; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import com.ychong.androidwan.utils.Constants; import com.ychong.library.utils.SPUtils; import java.io.IOException; import io.reactivex.Observable; import io.reactivex.functions.Consumer; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * @author ychong */ public class AddCookieInterceptor implements Interceptor { private Context context; public AddCookieInterceptor(Context context){ super(); this.context = context; } @SuppressLint("CheckResult") @Override public Response intercept(Chain chain) throws IOException { final Request.Builder builder = chain.request().newBuilder(); Observable.just(SPUtils.getInstance(context).getString(Constants.COOKIE_KEY)) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { builder.addHeader("Cookie",s); } }); return chain.proceed(builder.build()); } }
1,208
0.67798
0.675497
41
28.463415
22.018948
85
false
false
0
0
0
0
0
0
0.487805
false
false
7
8d17f7d82e2b407452d1336e4c3421d8e07a787f
1,975,684,987,002
428cbc3645d5eb4bdd6fec7388d0b1c6b012f382
/src/main/java/com/zhang/jvm/set/MyHashSet.java
28427bac7e7278787c3cd3ab6c1d9ff776b6e518
[]
no_license
zhangbo512/note
https://github.com/zhangbo512/note
c9853077536bb0ee78f98ed740d821e2dc7e1c0e
82611e6946533cc3e70f9554d279e7a7981120a2
refs/heads/master
2021-06-28T11:16:14.217000
2019-07-25T07:06:15
2019-07-25T07:06:15
161,189,373
7
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhang.jvm.set; /** * description * * @author zb 2019/07/14 15:16 */ public class MyHashSet extends MyAbstractSet implements MySet{ }
UTF-8
Java
153
java
MyHashSet.java
Java
[ { "context": "m.zhang.jvm.set;\n\n/**\n * description\n *\n * @author zb 2019/07/14 15:16\n */\npublic class MyHashSet exten", "end": 63, "score": 0.999378502368927, "start": 61, "tag": "USERNAME", "value": "zb" } ]
null
[]
package com.zhang.jvm.set; /** * description * * @author zb 2019/07/14 15:16 */ public class MyHashSet extends MyAbstractSet implements MySet{ }
153
0.699346
0.620915
10
14.3
18.968658
62
false
false
0
0
0
0
0
0
0.1
false
false
7
ed540cb1a776f5331cd554f25d8e5bedbf57fc25
17,480,516,922,540
692119d2a5d8943c4a7a170a624382bc39b6e547
/skillful_network_server/src/test/java/fr/uca/cdr/skillful_network/repositories/user/UserRepositoryTest.java
8bc6cbdeb9889842b453e92365948a15eae64410
[]
no_license
danglotb/skillful_network
https://github.com/danglotb/skillful_network
ec61e6a6d7e56ff7a925b5cef39f7d117ddbf138
aa15b88139155118623a8fa51a2912f1bc3f8da6
refs/heads/master
2023-01-11T23:17:18.795000
2021-04-20T07:39:13
2021-04-20T07:39:13
272,182,351
5
1
null
false
2023-01-07T19:07:18
2020-06-14T10:48:46
2021-04-20T07:39:16
2023-01-07T19:07:16
5,795
4
1
32
Java
false
false
package fr.uca.cdr.skillful_network.repositories.user; import fr.uca.cdr.skillful_network.entities.user.User; import fr.uca.cdr.skillful_network.repositories.user.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @ActiveProfiles("test") @RunWith(SpringRunner.class) @DataJpaTest public class UserRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private UserRepository userRepository; @Test public void testController() { entityManager.persistAndFlush(createUser()); assertThat(userRepository.findAll()).isNotEmpty(); } private User createUser() { final User user = new User(); user.setEmail("user.name@test.com"); user.setTemporaryCodeExpirationDate(LocalDateTime.now().plus(24, ChronoUnit.HOURS)); final String randomCodeEncrypt = "password"; user.setPassword(randomCodeEncrypt); user.setRoles(Collections.emptySet()); return user; } }
UTF-8
Java
1,494
java
UserRepositoryTest.java
Java
[ { "context": "al User user = new User();\n user.setEmail(\"user.name@test.com\");\n user.setTemporaryCodeExpirationDate(Lo", "end": 1223, "score": 0.9999153017997742, "start": 1205, "tag": "EMAIL", "value": "user.name@test.com" }, { "context": "OURS));\n final String randomCodeEncrypt = \"password\";\n user.setPassword(randomCodeEncrypt);\n ", "end": 1370, "score": 0.9937866926193237, "start": 1362, "tag": "PASSWORD", "value": "password" }, { "context": "rypt = \"password\";\n user.setPassword(randomCodeEncrypt);\n user.setRoles(Collections.emptySet());\n", "end": 1415, "score": 0.6206860542297363, "start": 1404, "tag": "PASSWORD", "value": "CodeEncrypt" } ]
null
[]
package fr.uca.cdr.skillful_network.repositories.user; import fr.uca.cdr.skillful_network.entities.user.User; import fr.uca.cdr.skillful_network.repositories.user.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @ActiveProfiles("test") @RunWith(SpringRunner.class) @DataJpaTest public class UserRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private UserRepository userRepository; @Test public void testController() { entityManager.persistAndFlush(createUser()); assertThat(userRepository.findAll()).isNotEmpty(); } private User createUser() { final User user = new User(); user.setEmail("<EMAIL>"); user.setTemporaryCodeExpirationDate(LocalDateTime.now().plus(24, ChronoUnit.HOURS)); final String randomCodeEncrypt = "<PASSWORD>"; user.setPassword(random<PASSWORD>); user.setRoles(Collections.emptySet()); return user; } }
1,484
0.764391
0.762383
45
32.200001
24.515392
92
false
false
0
0
0
0
0
0
0.577778
false
false
7
e086571bca46a2b845d8061954a612cdf506b424
15,865,609,224,045
1d48571270e1be08d211001b3f8ea172cf0999a6
/src/UserInterface/Reports/FXMLController/ViewVehiclesByYearFXMLController.java
4bc352e0d9f273a225b1bde0355fe7bb4009f610
[]
no_license
OurSRC/SuperRent
https://github.com/OurSRC/SuperRent
d505b18d626e2c25a7e4cf0cca2c41717720de34
0ef97027429df997a8d2054d6852c7c60366075c
refs/heads/master
2021-01-19T16:50:56.094000
2014-04-29T07:16:28
2014-04-29T07:16:28
18,500,146
0
0
null
false
2014-04-09T06:29:35
2014-04-06T21:51:22
2014-04-09T06:29:35
2014-04-09T06:29:35
0
0
1
8
Java
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UserInterface.Reports.FXMLController; import Vehicle.VehicleCtrl; import SystemOperations.DateClass; import SystemOperations.DialogFX; import Dao.DaoException; import Vehicle.VehicleDao; import Vehicle.Vehicle; import Vehicle.VehicleClass; import java.awt.Desktop; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.text.Font; import SystemOperations.PdfGen; /** * FXML Controller class * * @author Ashanthi Perera */ public class ViewVehiclesByYearFXMLController implements Initializable { @FXML private TableView VehiclesListTable; @FXML private TableColumn VehicleNoColumn; @FXML private TableColumn VehicleClassColumn; @FXML private TableColumn VehicleModelColumn; @FXML private TableColumn YearColumn; @FXML private TableColumn OdometerColumn; @FXML private TableColumn StatusColumn; @FXML private Button SearchButton; @FXML private Label YearsLabel; @FXML private TextField YearsTF; @FXML private Button PrintPDFButton; @FXML private CheckBox EmailCHB; @FXML private ComboBox VehicleClassCB; @FXML private Label VehicleTypeLabel; @FXML private RadioButton VehicleTypeCarRB; @FXML private ToggleGroup VehicleTypeTG; @FXML private RadioButton VehicleTypeTruckRB; private String vehicleType; private VehicleClass.TYPE vehicleTypeEnum; private String vehicleClass; public String noofyears; private int Maxmanufactureyear ; private int currentyear ; private int ageinyears ; ArrayList<Vehicle> vehicleArray; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO vehicleType = "CAR"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getCarType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Car; } @FXML private void ViewVehiclesListAction(ActionEvent event)throws DaoException { if (ValidateInput()) { if(VehicleClassCB.valueProperty().isNull().getValue()) { vehicleClass = null; } else { vehicleClass = VehicleClassCB.getSelectionModel().getSelectedItem().toString(); } populateSearchTable(); System.out.println("Vehicle class : " + vehicleClass); noofyears=YearsTF.getText(). toString(); System.out.println("No Of Years : " + noofyears); } else { System.out.println("Please Enter the Required Fields"); DialogFX dialog = new DialogFX(DialogFX.Type.ERROR); dialog.setTitleText("Error"); dialog.setMessage("Please Enter Suitable Values in Mandatory Fields"); dialog.showDialog(); } } public void populateSearchTable() throws DaoException { currentyear = Calendar.getInstance().get(Calendar.YEAR); Maxmanufactureyear = currentyear-ageinyears; VehiclesListTable.getItems().clear(); VehicleDao newVehicleCtrl = new VehicleDao(); vehicleArray = newVehicleCtrl.findVehicleOlderThan(Maxmanufactureyear,vehicleClass,vehicleTypeEnum); /* Get the Arraylist from the Control Object */ //Enabling - Disabling the PrintPDF button if (vehicleArray.size() > 0) { PrintPDFButton.setDisable(false); } else { PrintPDFButton.setDisable(true); } ObservableList<Vehicle> slist = FXCollections.observableArrayList(vehicleArray); VehiclesListTable.setItems(slist); System.out.println("I am here and it is working"); VehicleNoColumn.setCellValueFactory(new PropertyValueFactory("plateNo")); VehicleClassColumn.setCellValueFactory(new PropertyValueFactory("className")); VehicleModelColumn.setCellValueFactory(new PropertyValueFactory("mode")); YearColumn.setCellValueFactory(new PropertyValueFactory("manufactureDate")); OdometerColumn.setCellValueFactory(new PropertyValueFactory("odometer")); StatusColumn.setCellValueFactory(new PropertyValueFactory("status")); } public boolean ValidateInput() { boolean validated=true; if ( YearsTF.getText().equals("")) { validated=false; } try{ ageinyears =Integer.parseInt(YearsTF.getText()); if (ageinyears > 50) validated = false; } catch(NumberFormatException e){ validated=false; } return validated; } @FXML private void PrintPDFAction(ActionEvent event) { String pdfName = "List of Vehicles Older Than " + ageinyears; PdfGen.genVehicleListReport(vehicleArray, pdfName); if (Desktop.isDesktopSupported()) { try { File myFile = new File(pdfName + ".pdf"); Desktop.getDesktop().open(myFile); } catch (Exception e) { System.out.println(e.getMessage()); } } } @FXML private void VehicleClassCBAction(ActionEvent event) { } @FXML private void VehicleTypeCarRBAction(ActionEvent event) { vehicleType = "CAR"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getCarType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Car; } @FXML private void VehicleTypeTruckRBAction(ActionEvent event) { vehicleType = "TRUCK"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getTruckType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Truck; } }
UTF-8
Java
7,453
java
ViewVehiclesByYearFXMLController.java
Java
[ { "context": ";\r\n\r\n/**\r\n * FXML Controller class\r\n *\r\n * @author Ashanthi Perera\r\n */\r\npublic class ViewVehiclesByYearFXMLController", "end": 1332, "score": 0.9809252023696899, "start": 1317, "tag": "NAME", "value": "Ashanthi Perera" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UserInterface.Reports.FXMLController; import Vehicle.VehicleCtrl; import SystemOperations.DateClass; import SystemOperations.DialogFX; import Dao.DaoException; import Vehicle.VehicleDao; import Vehicle.Vehicle; import Vehicle.VehicleClass; import java.awt.Desktop; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.text.Font; import SystemOperations.PdfGen; /** * FXML Controller class * * @author <NAME> */ public class ViewVehiclesByYearFXMLController implements Initializable { @FXML private TableView VehiclesListTable; @FXML private TableColumn VehicleNoColumn; @FXML private TableColumn VehicleClassColumn; @FXML private TableColumn VehicleModelColumn; @FXML private TableColumn YearColumn; @FXML private TableColumn OdometerColumn; @FXML private TableColumn StatusColumn; @FXML private Button SearchButton; @FXML private Label YearsLabel; @FXML private TextField YearsTF; @FXML private Button PrintPDFButton; @FXML private CheckBox EmailCHB; @FXML private ComboBox VehicleClassCB; @FXML private Label VehicleTypeLabel; @FXML private RadioButton VehicleTypeCarRB; @FXML private ToggleGroup VehicleTypeTG; @FXML private RadioButton VehicleTypeTruckRB; private String vehicleType; private VehicleClass.TYPE vehicleTypeEnum; private String vehicleClass; public String noofyears; private int Maxmanufactureyear ; private int currentyear ; private int ageinyears ; ArrayList<Vehicle> vehicleArray; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO vehicleType = "CAR"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getCarType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Car; } @FXML private void ViewVehiclesListAction(ActionEvent event)throws DaoException { if (ValidateInput()) { if(VehicleClassCB.valueProperty().isNull().getValue()) { vehicleClass = null; } else { vehicleClass = VehicleClassCB.getSelectionModel().getSelectedItem().toString(); } populateSearchTable(); System.out.println("Vehicle class : " + vehicleClass); noofyears=YearsTF.getText(). toString(); System.out.println("No Of Years : " + noofyears); } else { System.out.println("Please Enter the Required Fields"); DialogFX dialog = new DialogFX(DialogFX.Type.ERROR); dialog.setTitleText("Error"); dialog.setMessage("Please Enter Suitable Values in Mandatory Fields"); dialog.showDialog(); } } public void populateSearchTable() throws DaoException { currentyear = Calendar.getInstance().get(Calendar.YEAR); Maxmanufactureyear = currentyear-ageinyears; VehiclesListTable.getItems().clear(); VehicleDao newVehicleCtrl = new VehicleDao(); vehicleArray = newVehicleCtrl.findVehicleOlderThan(Maxmanufactureyear,vehicleClass,vehicleTypeEnum); /* Get the Arraylist from the Control Object */ //Enabling - Disabling the PrintPDF button if (vehicleArray.size() > 0) { PrintPDFButton.setDisable(false); } else { PrintPDFButton.setDisable(true); } ObservableList<Vehicle> slist = FXCollections.observableArrayList(vehicleArray); VehiclesListTable.setItems(slist); System.out.println("I am here and it is working"); VehicleNoColumn.setCellValueFactory(new PropertyValueFactory("plateNo")); VehicleClassColumn.setCellValueFactory(new PropertyValueFactory("className")); VehicleModelColumn.setCellValueFactory(new PropertyValueFactory("mode")); YearColumn.setCellValueFactory(new PropertyValueFactory("manufactureDate")); OdometerColumn.setCellValueFactory(new PropertyValueFactory("odometer")); StatusColumn.setCellValueFactory(new PropertyValueFactory("status")); } public boolean ValidateInput() { boolean validated=true; if ( YearsTF.getText().equals("")) { validated=false; } try{ ageinyears =Integer.parseInt(YearsTF.getText()); if (ageinyears > 50) validated = false; } catch(NumberFormatException e){ validated=false; } return validated; } @FXML private void PrintPDFAction(ActionEvent event) { String pdfName = "List of Vehicles Older Than " + ageinyears; PdfGen.genVehicleListReport(vehicleArray, pdfName); if (Desktop.isDesktopSupported()) { try { File myFile = new File(pdfName + ".pdf"); Desktop.getDesktop().open(myFile); } catch (Exception e) { System.out.println(e.getMessage()); } } } @FXML private void VehicleClassCBAction(ActionEvent event) { } @FXML private void VehicleTypeCarRBAction(ActionEvent event) { vehicleType = "CAR"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getCarType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Car; } @FXML private void VehicleTypeTruckRBAction(ActionEvent event) { vehicleType = "TRUCK"; VehicleCtrl vehicleControl = new VehicleCtrl(); ObservableList<String> list = FXCollections.observableArrayList(vehicleControl.getTruckType()); VehicleClassCB.getItems().clear(); VehicleClassCB.setItems(list); vehicleTypeEnum = VehicleClass.TYPE.Truck; } }
7,444
0.640413
0.640011
223
31.421524
25.105194
156
false
false
0
0
0
0
0
0
0.533632
false
false
7
9098831319a1dedf90eff513e1c1c11b780743ee
7,808,250,570,314
32510cb35cb57e0b7d68a9dec9bd72ae6c1812a8
/blogimage/src/main/java/cn/wuaijing/util/TimerUtil.java
d62fc671d46766521fb580e608ddf8b07ab255b3
[]
no_license
BasessGit/blogimage
https://github.com/BasessGit/blogimage
357d75fe02d21de452f9ab1763319113cc87a604
b3403782a4c32e685380a202548fd480c2602797
refs/heads/master
2022-12-22T02:32:00.457000
2020-02-26T06:44:07
2020-02-26T06:44:07
223,517,975
0
0
null
false
2022-12-16T04:58:06
2019-11-23T02:17:02
2020-02-26T06:44:51
2022-12-16T04:58:03
5,788
0
0
12
Java
false
false
package cn.wuaijing.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.stereotype.Component; import javax.xml.ws.soap.Addressing; import java.text.SimpleDateFormat; import java.util.Date; @Component public class TimerUtil { private static final Logger logger = LogManager.getLogger(TimerUtil.class.getName()); public void printSimpleTrigger(){ System.out.println("simpleTrigger正在执行定时"+ new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); logger.info("simpleTrigger开始执行" + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); // attianAccessTokenUtil.getAccessToken(); } public void printCronTrigger(){ // System.out.println("cronTrigger正在执行定时"+ new Sim pleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); //logger.info("cronTrigger正在执行定时"+ new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); } }
UTF-8
Java
1,205
java
TimerUtil.java
Java
[]
null
[]
package cn.wuaijing.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean; import org.springframework.stereotype.Component; import javax.xml.ws.soap.Addressing; import java.text.SimpleDateFormat; import java.util.Date; @Component public class TimerUtil { private static final Logger logger = LogManager.getLogger(TimerUtil.class.getName()); public void printSimpleTrigger(){ System.out.println("simpleTrigger正在执行定时"+ new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); logger.info("simpleTrigger开始执行" + new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); // attianAccessTokenUtil.getAccessToken(); } public void printCronTrigger(){ // System.out.println("cronTrigger正在执行定时"+ new Sim pleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); //logger.info("cronTrigger正在执行定时"+ new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date())); } }
1,205
0.752799
0.751077
28
40.42857
36.553707
114
false
false
0
0
0
0
0
0
0.571429
false
false
7
35698b169ba68daa136bbd34bfc650c1f88d9edd
3,083,786,524,723
15757eee50aed02bda3a3f73f1ac051d0f872ff0
/src/com/library/dto/Book.java
3eeb288dea476a063be51c91af153c9f4ebe41c8
[]
no_license
arijitpaul84/library-management
https://github.com/arijitpaul84/library-management
9d5e677328d8e755e5e93b1029aa0bb8323d1ddb
e9dbe1de1ba2d4c5b1fa2906c188f60a6c7ae49a
refs/heads/master
2021-09-03T07:21:13.944000
2018-01-06T22:44:22
2018-01-06T22:44:22
116,519,705
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.library.dto; public class Book { private String id; private String title; private Author author; private Genre genre; public String getId() { return id; } public void setId(String id) { this.id = id; } public Book withId(String id) { this.id = id; return this; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Book withTitle(String title) { this.title = title; return this; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Book withAuthor(Author author) { this.author = author; return this; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Book withGenre(Genre genre) { this.genre = genre; return this; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((genre == null) ? 0 : genre.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((title == null) ? 0 : title.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; Book other = (Book) obj; if (genre != other.genre) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } }
UTF-8
Java
1,709
java
Book.java
Java
[]
null
[]
package com.library.dto; public class Book { private String id; private String title; private Author author; private Genre genre; public String getId() { return id; } public void setId(String id) { this.id = id; } public Book withId(String id) { this.id = id; return this; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Book withTitle(String title) { this.title = title; return this; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Book withAuthor(Author author) { this.author = author; return this; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } public Book withGenre(Genre genre) { this.genre = genre; return this; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((genre == null) ? 0 : genre.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((title == null) ? 0 : title.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; Book other = (Book) obj; if (genre != other.genre) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } }
1,709
0.626097
0.622586
89
18.202248
14.871872
69
false
false
0
0
0
0
0
0
1.921348
false
false
7
47b34f1a41ba9ef1edea49253933ce449c6d3dd8
24,781,961,348,290
8c6d88ae5d0fdd0c1bc6fe815f4fdda082de9029
/chopdrop/app/src/main/java/com/dorr/chopperdropper/view/Camera.java
2d9befa40727079bcb6938b5ff6ac1584b10241e
[ "MIT" ]
permissive
DouglasOrr/Snippets
https://github.com/DouglasOrr/Snippets
46517d796a886197c1cd7ca96b36a67c20387edd
a3b878429a2b0a5778dedf03ea75d241f406a9d3
refs/heads/master
2023-04-27T16:28:39.190000
2022-12-07T23:42:59
2022-12-07T23:42:59
82,979,371
0
0
MIT
false
2023-04-03T19:23:40
2017-02-23T22:54:29
2021-11-21T21:11:39
2023-04-03T19:23:36
4,363
0
0
1
Python
false
false
package com.dorr.chopperdropper.view; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.dorr.chopperdropper.model.Grid; import com.dorr.chopperdropper.model.Model; public abstract class Camera { /** Update the internal state of the camera (called just before drawing). */ public abstract void update(float viewportWidth, float viewportHeight); /** Get the world->screen transform matrix to use to render the scene. */ public abstract Matrix4 transform(); /** Get the bounding rectangle of visible elements in the world. */ public abstract Rectangle worldBounds(); public static Camera fixed(final Grid grid) { return new Camera() { float mScale = Float.NaN; float mBoundsX = Float.NaN, mBoundsY = Float.NaN; @Override public void update(float viewportWidth, float viewportHeight) { mScale = Math.min(viewportWidth / grid.worldWidth(), viewportHeight / grid.worldHeight()); mBoundsX = viewportWidth / mScale; mBoundsY = viewportHeight / mScale; } @Override public Matrix4 transform() { return new Matrix4(new float[]{ mScale, 0, 0, 0, 0, mScale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}); } @Override public Rectangle worldBounds() { return new Rectangle(0, 0, mBoundsX, mBoundsY); } }; } public static Camera lookingAt(final Model.HasPosition model, final float yMin, final float minWorldWidth, final float maxHeightFraction) { return new Camera() { private float mScale = Float.NaN; private float mXMin = Float.NaN, mXMax = Float.NaN, mYMax = Float.NaN; @Override public void update(float viewportWidth, float viewportHeight) { Vector2 p = model.position(); float h = p.y - yMin; mScale = Math.min( viewportWidth / minWorldWidth, 0 < h ? (viewportHeight * maxHeightFraction / h) : Float.MAX_VALUE ); float halfWidth = viewportWidth / mScale / 2; mXMin = p.x - halfWidth; mXMax = p.x + halfWidth; mYMax = yMin + viewportHeight / mScale; } @Override public Matrix4 transform() { float translateX = -mScale * mXMin; float translateY = -mScale * yMin; return new Matrix4(new float[]{ mScale, 0, 0, 0, 0, mScale, 0, 0, 0, 0, 1, 0, translateX, translateY, 0, 1}); } @Override public Rectangle worldBounds() { return new Rectangle(mXMin, yMin, mXMax - mXMin, mYMax - yMin); } }; } }
UTF-8
Java
3,208
java
Camera.java
Java
[]
null
[]
package com.dorr.chopperdropper.view; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.dorr.chopperdropper.model.Grid; import com.dorr.chopperdropper.model.Model; public abstract class Camera { /** Update the internal state of the camera (called just before drawing). */ public abstract void update(float viewportWidth, float viewportHeight); /** Get the world->screen transform matrix to use to render the scene. */ public abstract Matrix4 transform(); /** Get the bounding rectangle of visible elements in the world. */ public abstract Rectangle worldBounds(); public static Camera fixed(final Grid grid) { return new Camera() { float mScale = Float.NaN; float mBoundsX = Float.NaN, mBoundsY = Float.NaN; @Override public void update(float viewportWidth, float viewportHeight) { mScale = Math.min(viewportWidth / grid.worldWidth(), viewportHeight / grid.worldHeight()); mBoundsX = viewportWidth / mScale; mBoundsY = viewportHeight / mScale; } @Override public Matrix4 transform() { return new Matrix4(new float[]{ mScale, 0, 0, 0, 0, mScale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}); } @Override public Rectangle worldBounds() { return new Rectangle(0, 0, mBoundsX, mBoundsY); } }; } public static Camera lookingAt(final Model.HasPosition model, final float yMin, final float minWorldWidth, final float maxHeightFraction) { return new Camera() { private float mScale = Float.NaN; private float mXMin = Float.NaN, mXMax = Float.NaN, mYMax = Float.NaN; @Override public void update(float viewportWidth, float viewportHeight) { Vector2 p = model.position(); float h = p.y - yMin; mScale = Math.min( viewportWidth / minWorldWidth, 0 < h ? (viewportHeight * maxHeightFraction / h) : Float.MAX_VALUE ); float halfWidth = viewportWidth / mScale / 2; mXMin = p.x - halfWidth; mXMax = p.x + halfWidth; mYMax = yMin + viewportHeight / mScale; } @Override public Matrix4 transform() { float translateX = -mScale * mXMin; float translateY = -mScale * yMin; return new Matrix4(new float[]{ mScale, 0, 0, 0, 0, mScale, 0, 0, 0, 0, 1, 0, translateX, translateY, 0, 1}); } @Override public Rectangle worldBounds() { return new Rectangle(mXMin, yMin, mXMax - mXMin, mYMax - yMin); } }; } }
3,208
0.518703
0.506858
86
36.302326
25.006079
106
false
false
0
0
0
0
0
0
0.906977
false
false
7
92e9f6c2ca8ca8a2f8ffe0d2a2be44420cb42d15
28,140,625,748,116
f06e6205b285743d630197bda5daebca6aec002e
/src/main/java/com/example/secondkill/config/ZooKeeperConfig.java
52904b46eea4ce1ee6e57e1999befa11d998dcba
[]
no_license
dengjili/secondkill
https://github.com/dengjili/secondkill
a7a44d616557d6f334238cd3d60ba279e2b73d0a
49fe0ffcc3bc785cceb382d1412c01716a18c9b5
refs/heads/main
2023-05-14T03:08:05.938000
2021-06-03T02:15:57
2021-06-03T02:15:57
373,355,522
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <p>Title: SpringConfig.java</p> * <p>Description: </p> * @author dengjili * @date 2021年5月26日 */ package com.example.secondkill.config; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.ZooKeeper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.secondkill.zk.ZookeeperWatcher; /** * <p>Title: SpringConfig.java</p> * <p>Description: </p> * @author dengjili * @date 2021年5月26日 */ @Configuration public class ZooKeeperConfig { @Value("${spring.zookeeper.addr}") private String zookeeperAddr; private CountDownLatch connectSemaphore = new CountDownLatch(1); @Bean public ZooKeeper createZooKeeper() throws Exception { ZookeeperWatcher watcher = new ZookeeperWatcher(connectSemaphore); ZooKeeper zooKeeper = new ZooKeeper(zookeeperAddr, 20000, watcher); watcher.setZookeeper(zooKeeper); // connectSemaphore.await(); return zooKeeper; } }
UTF-8
Java
1,117
java
ZooKeeperConfig.java
Java
[ { "context": "g.java</p>\r\n * <p>Description: </p>\r\n * @author dengjili\r\n * @date 2021年5月26日 \r\n */\r\npackage com.exa", "end": 88, "score": 0.9582114815711975, "start": 80, "tag": "USERNAME", "value": "dengjili" }, { "context": "va</p> \r\n * <p>Description: </p> \r\n * @author dengjili\r\n * @date 2021年5月26日 \r\n */\r\n@Configuration\r", "end": 576, "score": 0.9837507009506226, "start": 568, "tag": "USERNAME", "value": "dengjili" } ]
null
[]
/** * <p>Title: SpringConfig.java</p> * <p>Description: </p> * @author dengjili * @date 2021年5月26日 */ package com.example.secondkill.config; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.ZooKeeper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.secondkill.zk.ZookeeperWatcher; /** * <p>Title: SpringConfig.java</p> * <p>Description: </p> * @author dengjili * @date 2021年5月26日 */ @Configuration public class ZooKeeperConfig { @Value("${spring.zookeeper.addr}") private String zookeeperAddr; private CountDownLatch connectSemaphore = new CountDownLatch(1); @Bean public ZooKeeper createZooKeeper() throws Exception { ZookeeperWatcher watcher = new ZookeeperWatcher(connectSemaphore); ZooKeeper zooKeeper = new ZooKeeper(zookeeperAddr, 20000, watcher); watcher.setZookeeper(zooKeeper); // connectSemaphore.await(); return zooKeeper; } }
1,117
0.720362
0.702262
40
25.625
21.629478
69
false
false
0
0
0
0
0
0
0.875
false
false
7
a79b88670f6da31133e134fec5920fb7cff39300
23,252,952,981,602
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/33/33_ae13779090a121f3ad241a390bfbdc08c48a5877/ID3v23TagTest/33_ae13779090a121f3ad241a390bfbdc08c48a5877_ID3v23TagTest_s.java
217f88c1d6cd8dcd9b6bef55e19b5a99879df85b
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package org.jaudiotagger.tag; import org.jaudiotagger.audio.mp3.MP3AudioHeader; import org.jaudiotagger.audio.mp3.MPEGFrameHeader; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.AbstractTestCase; import java.io.File; /** */ public class ID3v23TagTest extends AbstractTestCase { public void testReadID3v1ID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v1v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNotNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v1Tag()); } public void testReadID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); } public void testReadPaddedID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v2pad.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); } public void testDeleteID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v1v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNotNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); mp3File.setID3v1Tag(null); mp3File.setID3v2Tag(null); try { mp3File.save(); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNull(mp3File.getID3v2Tag()); } }
UTF-8
Java
2,692
java
33_ae13779090a121f3ad241a390bfbdc08c48a5877_ID3v23TagTest_s.java
Java
[]
null
[]
package org.jaudiotagger.tag; import org.jaudiotagger.audio.mp3.MP3AudioHeader; import org.jaudiotagger.audio.mp3.MPEGFrameHeader; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.AbstractTestCase; import java.io.File; /** */ public class ID3v23TagTest extends AbstractTestCase { public void testReadID3v1ID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v1v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNotNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v1Tag()); } public void testReadID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); } public void testReadPaddedID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v2pad.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); } public void testDeleteID3v23Tag() { Exception exceptionCaught = null; File testFile = copyAudioToTmp("testV1Cbr128ID3v1v2.mp3"); MP3File mp3File = null; try { mp3File = new MP3File(testFile); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNotNull(mp3File.getID3v1Tag()); assertNotNull(mp3File.getID3v2Tag()); mp3File.setID3v1Tag(null); mp3File.setID3v2Tag(null); try { mp3File.save(); } catch (Exception e) { exceptionCaught = e; } assertNull(exceptionCaught); assertNull(mp3File.getID3v1Tag()); assertNull(mp3File.getID3v2Tag()); } }
2,692
0.554235
0.51523
119
21.613445
19.020603
68
false
false
0
0
0
0
0
0
0.378151
false
false
7
f1edb153d8c9c42a71b10581db17c1f8b129fc49
26,800,595,968,006
1b3eaa409dda25b83517bd391757b3931e706065
/src/org/usfirst/frc/team1389/systems/FancyLightSystem.java
1f5636ba1406b71595ddbdf2df41bd86c9e92c0b
[]
no_license
itri45/Dashiel-2017
https://github.com/itri45/Dashiel-2017
d10a2c655dd2b79ae939400eb1fc21c5f18cdbfd
8a47e5e50e7098853f2487046b603a6df3b10054
refs/heads/master
2020-04-15T19:32:53.814000
2019-01-10T00:37:34
2019-01-10T00:37:34
164,954,644
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.usfirst.frc.team1389.systems; import java.util.function.Consumer; import java.util.function.Supplier; import com.team1389.system.Subsystem; import com.team1389.util.Color; import com.team1389.util.list.AddList; import com.team1389.watch.Watchable; import com.team1389.watch.info.StringInfo; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStation.Alliance; public class FancyLightSystem extends Subsystem { private Consumer<Color> lightController; private Supplier<GearIntakeSystem.State> intakeState; private Alliance alliance; private Color lastSetColor; public FancyLightSystem(Consumer<Color> lightController, Supplier<GearIntakeSystem.State> intakeState) { this.lightController = lightController; this.intakeState = intakeState; } @Override public AddList<Watchable> getSubWatchables(AddList<Watchable> stem) { return stem.put(new StringInfo("Color", lastSetColor::toString)); } @Override public String getName() { return "Lights"; } @Override public void init() { alliance = DriverStation.getInstance().getAlliance(); lastSetColor = getAllianceColor(alliance); lightController.accept(lastSetColor); } @Override public void update() { lastSetColor = getAllianceColor(alliance); switch (intakeState.get()) { case CARRYING: lastSetColor = Color.green; break; case INTAKING: lastSetColor = Color.orange; break; default: break; } lightController.accept(lastSetColor); } public static Color getAllianceColor(Alliance alliance) { return alliance == Alliance.Blue ? Color.blue : Color.red; } }
UTF-8
Java
1,611
java
FancyLightSystem.java
Java
[]
null
[]
package org.usfirst.frc.team1389.systems; import java.util.function.Consumer; import java.util.function.Supplier; import com.team1389.system.Subsystem; import com.team1389.util.Color; import com.team1389.util.list.AddList; import com.team1389.watch.Watchable; import com.team1389.watch.info.StringInfo; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStation.Alliance; public class FancyLightSystem extends Subsystem { private Consumer<Color> lightController; private Supplier<GearIntakeSystem.State> intakeState; private Alliance alliance; private Color lastSetColor; public FancyLightSystem(Consumer<Color> lightController, Supplier<GearIntakeSystem.State> intakeState) { this.lightController = lightController; this.intakeState = intakeState; } @Override public AddList<Watchable> getSubWatchables(AddList<Watchable> stem) { return stem.put(new StringInfo("Color", lastSetColor::toString)); } @Override public String getName() { return "Lights"; } @Override public void init() { alliance = DriverStation.getInstance().getAlliance(); lastSetColor = getAllianceColor(alliance); lightController.accept(lastSetColor); } @Override public void update() { lastSetColor = getAllianceColor(alliance); switch (intakeState.get()) { case CARRYING: lastSetColor = Color.green; break; case INTAKING: lastSetColor = Color.orange; break; default: break; } lightController.accept(lastSetColor); } public static Color getAllianceColor(Alliance alliance) { return alliance == Alliance.Blue ? Color.blue : Color.red; } }
1,611
0.77095
0.756052
63
24.571428
22.572433
105
false
false
0
0
0
0
0
0
1.52381
false
false
7
d8a8d5a3e6f05ddc235fa488843ff056795746ef
19,215,683,714,788
1204c2a42be27cf3a6c58b852e5a17a59708dd85
/projects/src/br/com/objectware/projects/wizards/msx/MSXDOSWizardIterator.java
bdc1ef70958043a75ebb2b7ba5762c30a6900641
[]
no_license
Christofoletti/OpCode-IDE
https://github.com/Christofoletti/OpCode-IDE
39795442636221bdbc9419055e0220ca1befb089
305f1eb06bc28b626ece0052ee0f88ef5819b64b
refs/heads/master
2021-01-01T06:47:33.528000
2017-10-17T01:12:05
2017-10-17T01:12:05
97,514,996
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.objectware.projects.wizards.msx; import br.com.objectware.domain.BuildType; import br.com.objectware.domain.enums.MsxBuildType; import org.netbeans.api.templates.TemplateRegistration; /** * MSX DOS project type template registration. * * @author Luciano M. Christofoletti * @since 25/may/2015 */ @TemplateRegistration(folder = "Project/MSX", position = 200, displayName = "#msx.dos.type", targetName = "msx-dos-project", description = "msx-dos-description.html", iconBase = "resources/msx.project.icon.png", content = "msx-dos-project.zip") public class MSXDOSWizardIterator extends MSXWizardIterator { public static MSXDOSWizardIterator createIterator() { return new MSXDOSWizardIterator(); } @Override protected BuildType getBuildType() { return MsxBuildType.MSX_DOS; } }
UTF-8
Java
1,102
java
MSXDOSWizardIterator.java
Java
[ { "context": "oject type template registration.\r\n * \r\n * @author Luciano M. Christofoletti\r\n * @since 25/may/2015\r\n */\r\n@TemplateRegistratio", "end": 491, "score": 0.9998611807823181, "start": 466, "tag": "NAME", "value": "Luciano M. Christofoletti" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.objectware.projects.wizards.msx; import br.com.objectware.domain.BuildType; import br.com.objectware.domain.enums.MsxBuildType; import org.netbeans.api.templates.TemplateRegistration; /** * MSX DOS project type template registration. * * @author <NAME> * @since 25/may/2015 */ @TemplateRegistration(folder = "Project/MSX", position = 200, displayName = "#msx.dos.type", targetName = "msx-dos-project", description = "msx-dos-description.html", iconBase = "resources/msx.project.icon.png", content = "msx-dos-project.zip") public class MSXDOSWizardIterator extends MSXWizardIterator { public static MSXDOSWizardIterator createIterator() { return new MSXDOSWizardIterator(); } @Override protected BuildType getBuildType() { return MsxBuildType.MSX_DOS; } }
1,083
0.686933
0.678766
34
30.411764
23.219055
79
false
false
0
0
0
0
0
0
0.441176
false
false
7
e15aee2391f853fa1a360f5317f59e52872191b0
31,877,247,317,569
9a3314c4a5344b21542d8ee5e4bef2ce060f8f12
/Modelo/BoletoInternacional.java
9c8961e0cbae4a9248b896ed9bcc493ab14a981e
[]
no_license
DannyMannn/ProyectoFinal
https://github.com/DannyMannn/ProyectoFinal
5c1a4eee873075800eba97b2df9cfdad44ef8b6b
df68c9571d8d043bf87f422376426dd14342fdc9
refs/heads/master
2023-01-23T04:21:05.949000
2020-12-07T05:27:26
2020-12-07T05:27:26
318,662,701
0
0
null
true
2020-12-07T01:27:35
2020-12-04T23:55:44
2020-12-07T01:17:06
2020-12-07T01:27:34
121
0
0
0
Java
false
false
/** * Representa un Boleto de clase Internacional. * * @author Ervey Guerrero Gómez * @author David Hernandéz López * @author Daniel Sánchez Vázquez * @author Alejandro Tonatiuh García Espinoza */ package Modelo; public class BoletoInternacional extends Boleto { private final EnumVisa tipoVisa; private final int numPasaporte; private final int añosVigenciaVisa; /** * Constructor de la clase. * * @param nombrePasajero el nombre del pasajero. * @param edadPasajero la edad del pasajero. * @param generoPasajero el género del pasajero. * @param clasePasajero la clase en la que vuela el pasajero. * @param numAsiento el asiento asignado al pasajero. * @param numVuelo el número de vuelo. * @param aerolinea la aerolínea. * @param destino el destino del pasajero. * @param numPasaporte el número de pasaporte del pasajero. * @param tipoVisa el tipo de visa del pasajero. * @param añosVigenciaVisa la vigencia en años de la visa del pasajero. */ public BoletoInternacional(String nombrePasajero, int edadPasajero, String generoPasajero, EnumClase clasePasajero, int numAsiento, int numVuelo, String aerolinea, String destino, int numPasaporte, EnumVisa tipoVisa, int añosVigenciaVisa) { super(nombrePasajero, edadPasajero, generoPasajero, clasePasajero, numAsiento, numVuelo, aerolinea, destino); this.numPasaporte = numPasaporte; this.tipoVisa = tipoVisa; this.añosVigenciaVisa = añosVigenciaVisa; this.tipoVuelo = EnumVuelo.INTERNACIONAL; } /** * Obtiene el número de pasaporte del pasajero. * * @return el número de pasaporte del pasajero. */ public int getNumPasaporte() { return this.numPasaporte; } /** * Obtiene el tipo de visa del pasajero. * * @return el tipo de visa del pasajero. */ public EnumVisa getTipoVisa() { return this.tipoVisa; } /** * Obtiene los años de vigencia de la visa del pasajero. * * @return los años de vigencia de la visa del pasajero. */ public int getAñosVigenciaVisa() { return this.añosVigenciaVisa; } /** * Da formato a los datos del boleto para su impresión. * * @return una cadena con formato conteniendo los datos a mostrar. */ public String mostrar() { String linea = "-------------------------------------------------------------------------------------------------------------------------------------------------\n"; String encabezado = "\t\t\t\t\t\t\t\t\tBoleto\n"; //String datosFormato = "%10s%10s%10s%10s%15s%10s%10s%10s%25s\n"; String datosFormato = "%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n"; return String.format( linea + encabezado + linea + datosFormato, "Nombre", this.nombrePasajero, "Edad", this.edadPasajero, "Genero", this.generoPasajero, "Clase", this.clasePasajero, "No. Asiento", this.numAsiento, "No. Vuelo", this.numAsiento, "Aerolínea", this.aerolinea, "Destino", this.destino, "Tipo de VISA", this.tipoVisa, "No. Pasaporte", this.numPasaporte, "Años de Vigencia de VISA", this.añosVigenciaVisa, "SU FOLIO", this.folio); } }
UTF-8
Java
4,135
java
BoletoInternacional.java
Java
[ { "context": "ta un Boleto de clase Internacional.\n *\n * @author Ervey Guerrero Gómez\n * @author David Hernandéz López\n * @author Danie", "end": 86, "score": 0.9998804330825806, "start": 66, "tag": "NAME", "value": "Ervey Guerrero Gómez" }, { "context": "nal.\n *\n * @author Ervey Guerrero Gómez\n * @author David Hernandéz López\n * @author Daniel Sánchez Vázquez \n * @author Ale", "end": 119, "score": 0.999873161315918, "start": 98, "tag": "NAME", "value": "David Hernandéz López" }, { "context": " Gómez\n * @author David Hernandéz López\n * @author Daniel Sánchez Vázquez \n * @author Alejandro Tonatiuh García Espinoza \n ", "end": 153, "score": 0.9998725056648254, "start": 131, "tag": "NAME", "value": "Daniel Sánchez Vázquez" }, { "context": "ópez\n * @author Daniel Sánchez Vázquez \n * @author Alejandro Tonatiuh García Espinoza \n */\n\npackage Modelo;\n\npublic cla", "end": 184, "score": 0.9992691874504089, "start": 166, "tag": "NAME", "value": "Alejandro Tonatiuh" }, { "context": "iel Sánchez Vázquez \n * @author Alejandro Tonatiuh García Espinoza \n */\n\npackage Modelo;\n\npublic class BoletoInterna", "end": 200, "score": 0.9998306632041931, "start": 185, "tag": "NAME", "value": "García Espinoza" } ]
null
[]
/** * Representa un Boleto de clase Internacional. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> <NAME> */ package Modelo; public class BoletoInternacional extends Boleto { private final EnumVisa tipoVisa; private final int numPasaporte; private final int añosVigenciaVisa; /** * Constructor de la clase. * * @param nombrePasajero el nombre del pasajero. * @param edadPasajero la edad del pasajero. * @param generoPasajero el género del pasajero. * @param clasePasajero la clase en la que vuela el pasajero. * @param numAsiento el asiento asignado al pasajero. * @param numVuelo el número de vuelo. * @param aerolinea la aerolínea. * @param destino el destino del pasajero. * @param numPasaporte el número de pasaporte del pasajero. * @param tipoVisa el tipo de visa del pasajero. * @param añosVigenciaVisa la vigencia en años de la visa del pasajero. */ public BoletoInternacional(String nombrePasajero, int edadPasajero, String generoPasajero, EnumClase clasePasajero, int numAsiento, int numVuelo, String aerolinea, String destino, int numPasaporte, EnumVisa tipoVisa, int añosVigenciaVisa) { super(nombrePasajero, edadPasajero, generoPasajero, clasePasajero, numAsiento, numVuelo, aerolinea, destino); this.numPasaporte = numPasaporte; this.tipoVisa = tipoVisa; this.añosVigenciaVisa = añosVigenciaVisa; this.tipoVuelo = EnumVuelo.INTERNACIONAL; } /** * Obtiene el número de pasaporte del pasajero. * * @return el número de pasaporte del pasajero. */ public int getNumPasaporte() { return this.numPasaporte; } /** * Obtiene el tipo de visa del pasajero. * * @return el tipo de visa del pasajero. */ public EnumVisa getTipoVisa() { return this.tipoVisa; } /** * Obtiene los años de vigencia de la visa del pasajero. * * @return los años de vigencia de la visa del pasajero. */ public int getAñosVigenciaVisa() { return this.añosVigenciaVisa; } /** * Da formato a los datos del boleto para su impresión. * * @return una cadena con formato conteniendo los datos a mostrar. */ public String mostrar() { String linea = "-------------------------------------------------------------------------------------------------------------------------------------------------\n"; String encabezado = "\t\t\t\t\t\t\t\t\tBoleto\n"; //String datosFormato = "%10s%10s%10s%10s%15s%10s%10s%10s%25s\n"; String datosFormato = "%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n%s: %s\n"; return String.format( linea + encabezado + linea + datosFormato, "Nombre", this.nombrePasajero, "Edad", this.edadPasajero, "Genero", this.generoPasajero, "Clase", this.clasePasajero, "No. Asiento", this.numAsiento, "No. Vuelo", this.numAsiento, "Aerolínea", this.aerolinea, "Destino", this.destino, "Tipo de VISA", this.tipoVisa, "No. Pasaporte", this.numPasaporte, "Años de Vigencia de VISA", this.añosVigenciaVisa, "SU FOLIO", this.folio); } }
4,063
0.5101
0.505719
121
32.958679
24.623579
173
false
false
0
0
0
0
0
0
0.586777
false
false
7
753e5398043b63a28f139563c1ffcd724b5b0050
10,222,022,204,014
8cad1421a654ae26aa14b8b6d6a797db67897f45
/src/test/java/org/example/TestMadison.java
59e0934318800023b2facb1c6c1ac17b42044c4c
[]
no_license
logadrian/SeleniumEvozon
https://github.com/logadrian/SeleniumEvozon
493c78516d16cef80359902a0ae9d9988afe7bc4
6501a139c53c89702f79eb19d1312f55f5bf8e77
refs/heads/master
2021-01-26T16:22:40.654000
2020-02-27T07:24:16
2020-02-27T07:24:16
243,456,936
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import java.util.Iterator; import java.util.List; public class TestMadison { @Test public void testMadisonHomepage() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); System.out.println(driver.getTitle()); System.out.println(driver.getCurrentUrl()); driver.findElement(By.className("logo")).click(); driver.navigate().to("http://qa2.dev.evozon.com/men.html"); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); driver.quit(); } @Test public void testMadisonAccount() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); driver.findElement(By.cssSelector(".skip-link.skip-account")).click(); driver.quit(); } @Test public void testMadisonLanguages() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); // List list = driver.findElements(By.cssSelector("#select-language > option")); // System.out.println(list.size()); WebElement languageDropDown = driver.findElement(By.cssSelector("#select-language")); languageDropDown.click(); Select selectDropDown = new Select(languageDropDown); selectDropDown.selectByIndex(1); driver.quit(); } @Test public void testMadisonSearch(){ System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); driver.findElement(By.id("search")).clear(); WebElement searchBox = driver.findElement(By.id("search")); searchBox.sendKeys("woman"); searchBox.submit(); driver.quit(); } @Test public void testMadisonNewProductList() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); List<WebElement> list = driver.findElements(By.cssSelector(".item.last")); System.out.println(list.size()); for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getText()); } driver.quit(); } @Test public void testMadisonNavigation() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); List<WebElement> list = driver.findElements(By.cssSelector(".level0.parent")); for(int i = 0; i <list.size(); i++) { System.out.println(list.get(i).getText()); } WebElement saleCategory = driver.findElement(By.cssSelector("#nav > ol > li.level0.nav-5.parent")); saleCategory.click(); } }
UTF-8
Java
3,508
java
TestMadison.java
Java
[ { "context": "ent(By.id(\"search\"));\n searchBox.sendKeys(\"woman\");\n searchBox.submit();\n\n driver.qu", "end": 2328, "score": 0.7823351621627808, "start": 2323, "tag": "NAME", "value": "woman" } ]
null
[]
package org.example; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import java.util.Iterator; import java.util.List; public class TestMadison { @Test public void testMadisonHomepage() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); System.out.println(driver.getTitle()); System.out.println(driver.getCurrentUrl()); driver.findElement(By.className("logo")).click(); driver.navigate().to("http://qa2.dev.evozon.com/men.html"); driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); driver.quit(); } @Test public void testMadisonAccount() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); driver.findElement(By.cssSelector(".skip-link.skip-account")).click(); driver.quit(); } @Test public void testMadisonLanguages() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); // List list = driver.findElements(By.cssSelector("#select-language > option")); // System.out.println(list.size()); WebElement languageDropDown = driver.findElement(By.cssSelector("#select-language")); languageDropDown.click(); Select selectDropDown = new Select(languageDropDown); selectDropDown.selectByIndex(1); driver.quit(); } @Test public void testMadisonSearch(){ System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); driver.findElement(By.id("search")).clear(); WebElement searchBox = driver.findElement(By.id("search")); searchBox.sendKeys("woman"); searchBox.submit(); driver.quit(); } @Test public void testMadisonNewProductList() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); List<WebElement> list = driver.findElements(By.cssSelector(".item.last")); System.out.println(list.size()); for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getText()); } driver.quit(); } @Test public void testMadisonNavigation() { System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Driver\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("http://qa2.dev.evozon.com"); List<WebElement> list = driver.findElements(By.cssSelector(".level0.parent")); for(int i = 0; i <list.size(); i++) { System.out.println(list.get(i).getText()); } WebElement saleCategory = driver.findElement(By.cssSelector("#nav > ol > li.level0.nav-5.parent")); saleCategory.click(); } }
3,508
0.638541
0.634835
115
29.504349
29.543592
107
false
false
0
0
0
0
0
0
0.582609
false
false
7
ea0e115d831eaea1d97988e17c6a3e5fa4cec95f
10,222,022,206,169
d7294a19e7018f3a8022905e837d0d23554179b2
/bcamp2017-web/src/main/java/curs/events/BookAddedEvent.java
4f17a1bdd827eeb6bec36330a9881f9ab84e0aa2
[]
no_license
Mujuthejuju/Bootcamp-Book-Store-Project
https://github.com/Mujuthejuju/Bootcamp-Book-Store-Project
a529a0e44a84e76ec6a51f4de32e3f5be125579e
8f7db1bcc7da40c6c7a3f43ad454c81b99c8f0a4
refs/heads/branchy
2021-01-19T04:10:24.949000
2017-04-05T19:52:30
2017-04-05T19:52:30
87,106,637
0
0
null
true
2017-04-03T18:24:14
2017-04-03T18:24:14
2017-04-01T05:38:12
2017-04-03T18:17:55
209
0
0
0
null
null
null
package curs.events; import curs.model.Book; public class BookAddedEvent { private Book mBook; public BookAddedEvent(Book pBook) { mBook = pBook; } @Override public String toString() { return "BookAddedEvent [mBook=" + mBook + "]"; } }
UTF-8
Java
251
java
BookAddedEvent.java
Java
[]
null
[]
package curs.events; import curs.model.Book; public class BookAddedEvent { private Book mBook; public BookAddedEvent(Book pBook) { mBook = pBook; } @Override public String toString() { return "BookAddedEvent [mBook=" + mBook + "]"; } }
251
0.693227
0.693227
16
14.6875
14.606157
48
false
false
0
0
0
0
0
0
1
false
false
7
fc82fee693904086b1eb1d7bc77ff14276922ad0
22,153,441,342,888
dcc48c6ffcae5615c7cc1347a23411b0732244ab
/src/main/java/kaptainwutax/minemap/ui/component/WorldTabs.java
52e0f8028aa4849423995eaa580ac0d25aff10b3
[]
no_license
MineCube472/MineMap
https://github.com/MineCube472/MineMap
46949398f4061650214074af34e89850aa967fd3
317c2829f01e5109ad90e83dc7281d28b17a68b3
refs/heads/master
2023-01-04T20:35:48.808000
2020-10-23T21:52:58
2020-10-23T21:52:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kaptainwutax.minemap.ui.component; import kaptainwutax.minemap.MineMap; import kaptainwutax.minemap.ui.map.MapPanel; import kaptainwutax.seedutils.mc.Dimension; import kaptainwutax.seedutils.mc.MCVersion; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class WorldTabs extends JTabbedPane { public static final Color BACKGROUND_COLOR = new Color(60, 63, 65); protected final List<TabGroup> tabGroups = new ArrayList<>(); public WorldTabs() { //Copy seed to clipboard. KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(e -> { if (e.getKeyCode() != KeyEvent.VK_C || (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) == 0) return false; MapPanel map = this.getSelectedMapPanel(); if (map == null) return false; Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new StringSelection(String.valueOf(map.getContext().worldSeed)), null); return true; }); } public void load(MCVersion version, String worldSeed, int threadCount, Collection<Dimension> dimensions) { TabGroup tabGroup = new TabGroup(version, worldSeed, threadCount, dimensions); this.tabGroups.add(tabGroup); tabGroup.add(this); } @Override public void remove(Component component) { if (component instanceof MapPanel) { this.tabGroups.forEach(tabGroup -> tabGroup.removeIfPresent((MapPanel) component)); this.tabGroups.removeIf(TabGroup::isEmpty); } super.remove(component); } public void remove(TabGroup tabGroup) { for (MapPanel mapPanel : tabGroup.getMapPanels()) { super.remove(mapPanel); } this.tabGroups.remove(tabGroup); } public Component getSelectedComponent() { if (this.getSelectedIndex() < 0) return null; return this.getComponentAt(this.getSelectedIndex()); } public MapPanel getSelectedMapPanel() { Component component = this.getSelectedComponent(); return component instanceof MapPanel ? (MapPanel) component : null; } public TabHeader getSelectedHeader() { if (this.getSelectedIndex() < 0) return null; Component c = this.getTabComponentAt(this.getSelectedIndex()); return c instanceof TabHeader ? (TabHeader) c : null; } @Override public void paintComponent(Graphics g) { if (MineMap.DARCULA) { g.setColor(BACKGROUND_COLOR); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } super.paintComponent(g); } public synchronized void invalidateAll() { this.tabGroups.forEach(TabGroup::invalidateAll); } public int addTabAndGetIndex(String title, Component component) { super.addTab(title, component); return this.getTabCount() - 1; } @Override public void addTab(String title, Component component) { this.setTabComponentAt(this.addTabAndGetIndex(title, component), new TabHeader(title, e -> { this.remove(component); })); } public void addMapTab(String title, TabGroup tabGroup, MapPanel mapPanel) { this.setTabComponentAt(this.addTabAndGetIndex(title, mapPanel), new TabHeader(title, e -> { if (e.isShiftDown()) this.remove(tabGroup); else this.remove(mapPanel); })); } }
UTF-8
Java
3,636
java
WorldTabs.java
Java
[]
null
[]
package kaptainwutax.minemap.ui.component; import kaptainwutax.minemap.MineMap; import kaptainwutax.minemap.ui.map.MapPanel; import kaptainwutax.seedutils.mc.Dimension; import kaptainwutax.seedutils.mc.MCVersion; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class WorldTabs extends JTabbedPane { public static final Color BACKGROUND_COLOR = new Color(60, 63, 65); protected final List<TabGroup> tabGroups = new ArrayList<>(); public WorldTabs() { //Copy seed to clipboard. KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(e -> { if (e.getKeyCode() != KeyEvent.VK_C || (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) == 0) return false; MapPanel map = this.getSelectedMapPanel(); if (map == null) return false; Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new StringSelection(String.valueOf(map.getContext().worldSeed)), null); return true; }); } public void load(MCVersion version, String worldSeed, int threadCount, Collection<Dimension> dimensions) { TabGroup tabGroup = new TabGroup(version, worldSeed, threadCount, dimensions); this.tabGroups.add(tabGroup); tabGroup.add(this); } @Override public void remove(Component component) { if (component instanceof MapPanel) { this.tabGroups.forEach(tabGroup -> tabGroup.removeIfPresent((MapPanel) component)); this.tabGroups.removeIf(TabGroup::isEmpty); } super.remove(component); } public void remove(TabGroup tabGroup) { for (MapPanel mapPanel : tabGroup.getMapPanels()) { super.remove(mapPanel); } this.tabGroups.remove(tabGroup); } public Component getSelectedComponent() { if (this.getSelectedIndex() < 0) return null; return this.getComponentAt(this.getSelectedIndex()); } public MapPanel getSelectedMapPanel() { Component component = this.getSelectedComponent(); return component instanceof MapPanel ? (MapPanel) component : null; } public TabHeader getSelectedHeader() { if (this.getSelectedIndex() < 0) return null; Component c = this.getTabComponentAt(this.getSelectedIndex()); return c instanceof TabHeader ? (TabHeader) c : null; } @Override public void paintComponent(Graphics g) { if (MineMap.DARCULA) { g.setColor(BACKGROUND_COLOR); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } super.paintComponent(g); } public synchronized void invalidateAll() { this.tabGroups.forEach(TabGroup::invalidateAll); } public int addTabAndGetIndex(String title, Component component) { super.addTab(title, component); return this.getTabCount() - 1; } @Override public void addTab(String title, Component component) { this.setTabComponentAt(this.addTabAndGetIndex(title, component), new TabHeader(title, e -> { this.remove(component); })); } public void addMapTab(String title, TabGroup tabGroup, MapPanel mapPanel) { this.setTabComponentAt(this.addTabAndGetIndex(title, mapPanel), new TabHeader(title, e -> { if (e.isShiftDown()) this.remove(tabGroup); else this.remove(mapPanel); })); } }
3,636
0.661166
0.657866
107
32.981308
29.349323
116
false
false
0
0
0
0
0
0
0.663551
false
false
7
34a9b909f9fa6cbaa8492a5dd8ad2c8d373163ae
7,310,034,365,986
1fe55b934304ae94ed12cae67283b30da15e5f71
/rest-automation/src/test/java/fruz/udemy/test/PetsTests.java
d53a0189975732fc34612ed92132bfec692032c1
[]
no_license
SPetrovski1/API-Testing
https://github.com/SPetrovski1/API-Testing
95753c7a75dae2ce7fb2b94b43546722c10ad12d
87840e3bea1e83e76afe668af8b019e2879acd7e
refs/heads/master
2021-08-07T16:59:26.936000
2017-11-08T15:12:21
2017-11-08T15:12:21
109,991,226
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fruz.udemy.test; import static com.jayway.restassured.RestAssured.given; import static fruz.udemy.model.MyStrings.strings; import static org.hamcrest.Matchers.*; import static org.testng.Assert.*; import java.util.ArrayList; import java.util.List; import EndpointHelpers.PetHelper; import EndpointHelpers.UserHelper; import fruz.udemy.model.*; import org.testng.Assert; import org.testng.annotations.Test; import com.jayway.restassured.http.ContentType; import java.util.List; import java.util.Random; public class PetsTests extends BasicTest { String NAME_FOR_TESTING = "Tom"; PetHelper petHelper = new PetHelper(); @Test public void addPet() { //POST request at /pet Pet pet = setPayload(); given() .contentType(ContentType.JSON).log().all() .body(pet) .when() .post("/api/pet") .then() .statusCode(200); } @Test public void addPetAndCheckIfExists() { int petId = RandomDataGenerator.getRandomNumber(5, 10); Pet pet = setPayload(); pet.setId(petId); petHelper.createPet(pet); Pet pets = petHelper.getPetById(petId); assertEquals(petId, pets.getId()); } @Test public void checkPetExistsByName() { String name = "Tom"; Pet initial = setPayload(); initial.setName("zzzz"); for (int i = 0; i < 10; i++) { if(petHelper.getPetById(i).getName()==name){ initial = petHelper.getPetById(i); break; } else continue; } Assert.assertNotEquals(initial.getName(),"zzzz"); } @Test public void checkIfPetExistsByName(){ Pet tmp = setPayload(); Pet[] availablePets = petHelper.getByStatus("available"); for (Pet p : availablePets) { if (p.getName() == NAME_FOR_TESTING){ tmp.setName(p.getName()); break; } } Assert.assertEquals(NAME_FOR_TESTING,tmp.getName()); } @Test public void updatePet() { //PUT request to update an already existing pet int chosenId = 8; Pet pet = petHelper.getPetById(chosenId); pet.setName("Spike"); given() .contentType(ContentType.JSON).log().all() .body(pet) .when() .put("/api/pet") .then() .statusCode(200); } public Pet setPayload() { Pet payload = new Pet(); payload.setId(RandomDataGenerator.getRandomNumber(1, 10)); Category category = new Category(RandomDataGenerator.getRandomNumber(1, 10), RandomDataGenerator.randomAlphanumeric(10)); payload.setCategory(category); Random random = new Random(); payload.setStatus(strings[random.nextInt(strings.length)]); Tag tag1 = new Tag(1, RandomDataGenerator.randomAlphanumeric(10)); Tag tag2 = new Tag(2, RandomDataGenerator.randomAlphanumeric(10)); Tag tag3 = new Tag(3, RandomDataGenerator.randomAlphanumeric(10)); Tag tag4 = new Tag(4, RandomDataGenerator.randomAlphanumeric(10)); ArrayList<Tag> tags = new ArrayList<Tag>(); tags.add(tag1); tags.add(tag2); tags.add(tag3); tags.add(tag4); List<Tag> newTags = tags; Tag[] finalTags = new Tag[4]; for (int i = 0; i < newTags.size(); i++) { finalTags[i] = newTags.get(i); } payload.setTag(finalTags); payload.setName(RandomDataGenerator.randomAlphanumeric(10)); ArrayList<String> photoURL = new ArrayList<String>(); int numberOfPhotos = RandomDataGenerator.getRandomNumber(1, 10); for (int i = 0; i < numberOfPhotos; i++) { String tmp = RandomDataGenerator.randomAlphanumeric(10); photoURL.add(tmp); } String[] photos = new String[numberOfPhotos]; for (int j = 0; j < photoURL.size(); j++) { photos[j] = photoURL.get(j); } payload.setPhotoUrl(photos); return payload; } }
UTF-8
Java
4,322
java
PetsTests.java
Java
[ { "context": "nds BasicTest {\r\n\r\n String NAME_FOR_TESTING = \"Tom\";\r\n PetHelper petHelper = new PetHelper();\r\n\r\n", "end": 619, "score": 0.997255802154541, "start": 616, "tag": "NAME", "value": "Tom" }, { "context": " checkPetExistsByName() {\r\n String name = \"Tom\";\r\n Pet initial = setPayload();\r\n i", "end": 1403, "score": 0.9985259175300598, "start": 1400, "tag": "NAME", "value": "Tom" }, { "context": "elper.getPetById(chosenId);\r\n pet.setName(\"Spike\");\r\n given()\r\n .contentType", "end": 2380, "score": 0.9318081140518188, "start": 2375, "tag": "NAME", "value": "Spike" } ]
null
[]
package fruz.udemy.test; import static com.jayway.restassured.RestAssured.given; import static fruz.udemy.model.MyStrings.strings; import static org.hamcrest.Matchers.*; import static org.testng.Assert.*; import java.util.ArrayList; import java.util.List; import EndpointHelpers.PetHelper; import EndpointHelpers.UserHelper; import fruz.udemy.model.*; import org.testng.Assert; import org.testng.annotations.Test; import com.jayway.restassured.http.ContentType; import java.util.List; import java.util.Random; public class PetsTests extends BasicTest { String NAME_FOR_TESTING = "Tom"; PetHelper petHelper = new PetHelper(); @Test public void addPet() { //POST request at /pet Pet pet = setPayload(); given() .contentType(ContentType.JSON).log().all() .body(pet) .when() .post("/api/pet") .then() .statusCode(200); } @Test public void addPetAndCheckIfExists() { int petId = RandomDataGenerator.getRandomNumber(5, 10); Pet pet = setPayload(); pet.setId(petId); petHelper.createPet(pet); Pet pets = petHelper.getPetById(petId); assertEquals(petId, pets.getId()); } @Test public void checkPetExistsByName() { String name = "Tom"; Pet initial = setPayload(); initial.setName("zzzz"); for (int i = 0; i < 10; i++) { if(petHelper.getPetById(i).getName()==name){ initial = petHelper.getPetById(i); break; } else continue; } Assert.assertNotEquals(initial.getName(),"zzzz"); } @Test public void checkIfPetExistsByName(){ Pet tmp = setPayload(); Pet[] availablePets = petHelper.getByStatus("available"); for (Pet p : availablePets) { if (p.getName() == NAME_FOR_TESTING){ tmp.setName(p.getName()); break; } } Assert.assertEquals(NAME_FOR_TESTING,tmp.getName()); } @Test public void updatePet() { //PUT request to update an already existing pet int chosenId = 8; Pet pet = petHelper.getPetById(chosenId); pet.setName("Spike"); given() .contentType(ContentType.JSON).log().all() .body(pet) .when() .put("/api/pet") .then() .statusCode(200); } public Pet setPayload() { Pet payload = new Pet(); payload.setId(RandomDataGenerator.getRandomNumber(1, 10)); Category category = new Category(RandomDataGenerator.getRandomNumber(1, 10), RandomDataGenerator.randomAlphanumeric(10)); payload.setCategory(category); Random random = new Random(); payload.setStatus(strings[random.nextInt(strings.length)]); Tag tag1 = new Tag(1, RandomDataGenerator.randomAlphanumeric(10)); Tag tag2 = new Tag(2, RandomDataGenerator.randomAlphanumeric(10)); Tag tag3 = new Tag(3, RandomDataGenerator.randomAlphanumeric(10)); Tag tag4 = new Tag(4, RandomDataGenerator.randomAlphanumeric(10)); ArrayList<Tag> tags = new ArrayList<Tag>(); tags.add(tag1); tags.add(tag2); tags.add(tag3); tags.add(tag4); List<Tag> newTags = tags; Tag[] finalTags = new Tag[4]; for (int i = 0; i < newTags.size(); i++) { finalTags[i] = newTags.get(i); } payload.setTag(finalTags); payload.setName(RandomDataGenerator.randomAlphanumeric(10)); ArrayList<String> photoURL = new ArrayList<String>(); int numberOfPhotos = RandomDataGenerator.getRandomNumber(1, 10); for (int i = 0; i < numberOfPhotos; i++) { String tmp = RandomDataGenerator.randomAlphanumeric(10); photoURL.add(tmp); } String[] photos = new String[numberOfPhotos]; for (int j = 0; j < photoURL.size(); j++) { photos[j] = photoURL.get(j); } payload.setPhotoUrl(photos); return payload; } }
4,322
0.568255
0.556224
137
29.547445
23.169943
129
false
false
0
0
0
0
0
0
0.649635
false
false
7
33d904a1f88a52262cd99973edb88e57758d439b
31,404,800,921,279
3c030192d42d24c835b9f2bb31ad0cf65872bd1a
/UzayOyunuProjesi/src/Oyun.java
b5e6bc696f42fb75daee64d09c2feeb05a84b7a9
[]
no_license
onuryalcin-1/RaffleAplication
https://github.com/onuryalcin-1/RaffleAplication
b71d147512e32395cfba2e3d99b6552ebd5e0506
80d791a39d398d6088140b1f1bea80ce2ef1dda6
refs/heads/master
2023-02-13T13:29:14.483000
2020-12-21T13:32:39
2020-12-21T13:32:39
323,345,533
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; class Ates{ //Ateşimizin bir x, y koordinatı olacak ve her actionPerformed çalıştığında ateşimiz bir ileri gitmeye çalışacak private int x; //X Koordinatı private int y; //Y Koordinatı public Ates(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } public class Oyun extends JPanel implements KeyListener,ActionListener{ //KeyListener interface klavyeden bir tuşa basıldığında gerekli metodları kullanabilmemizi sağlar //ActionListener interface nesnelere hareket kazandırmak için kullanılır Timer timer = new Timer(5, this); private int gecen_sure = 0; private int harcanan_ates = 0; private BufferedImage image;//proje içerisindeki .png dosyasını alarak JPanel üzerinde kullanmamız için obje oluşturduk private ArrayList<Ates> atesler = new ArrayList<Ates>(); //Ateşlerimiz yukarı doğru gidiyor sağa sola gitmiyor. Ateşleri her timer çalıştığında 1 ileri götürmek için atesdirY = 1 olur //sağa sola hareket etmediği için topX = 0 tanımlarız private int atesdirY = 1; //Ateşler oluşacak ve bu ates her actionPerformed çalıştığında o ateşleri Y koordinatına ekleyeceğiz ve böylelikle ateşlerimiz hareket edecek private int topX = 0; //Sağa sola gitmeyi ayarlar ve ilk başta top 0,0 noktasından başlar bu top'ı sürekli bir artıracağız böylece tpumuz sürekli hareket edecek private int topdirX = 2;// topdirX sürekli topX e eklenecek, böylece topX sağda belli bir limite çarptığı zaman sola dönecek private int uzayGemisiX = 0; // Uzay Gemisinin ilk olarak hangi noktadan başlayacağını gösterir private int dirUZayX = 20; // Bu sayede sağ veya sol yön tuşuna bastığımızda uzay gemisi 20 birim hareket edecek public boolean kontrolEt(){ for(Ates ates : atesler){ if(new Rectangle(ates.getX(), ates.getY(), 10, 20).intersects(new Rectangle(topX, 0,20,20))){ //Intersects iki karenin birbirine çarpıp çarpmadığını kontrol etmek için kullanılır return true; } } return false; } public Oyun(){ try { image = ImageIO.read(new FileInputStream(new File("uzaygemisi.png"))); //image nesnesini ImageIO clasından okutarak uzaygemisi.png ekleyerek oluşturduk } catch (FileNotFoundException ex) { Logger.getLogger(Oyun.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Oyun.class.getName()).log(Level.SEVERE, null, ex); } setBackground(Color.black);//JPanel arka plan rengi siyah yapıldı. timer.start(); } @Override public void paint(Graphics g) { super.paint(g); //To change body of generated methods, choose Tools | Templates. gecen_sure += 5; g.setColor(Color.red); g.fillOval(topX, 0, 20, 20); //Başlangıç noktası 0,0 Y hiç hareket etmeyeceği için direk 0 yazıldı. topX güncellendikçe top X-X yönünde hareket edecek. //20,20 topun çapı g.drawImage(image, uzayGemisiX, 490, image.getWidth()/10,image.getHeight()/10,this); for(Ates ates : atesler){ if(ates.getY() < 0){ atesler.remove(ates); } } g.setColor(Color.blue); for(Ates ates : atesler){ g.fillRect(ates.getX(), ates.getY(), 10, 20); } if(kontrolEt()){ timer.stop(); String message = "Kazandınıız \n"+ "Harcanan Ateş : " + harcanan_ates +"\n"+ "Geçen süre : " + gecen_sure / 1000.0; JOptionPane.showMessageDialog(this, message); System.exit(0); } } @Override public void repaint() { super.repaint(); //To change body of generated methods, choose Tools | Templates. //aslında Repaint çağrıldığında paintte birlikte çağrılır //repaint() oyunlarda kesin yazılmalıdır //ActionPerformed fonksiyonu yazıldığında bu metot en sonda yazılacak ve şekillerimizi yeniden çizme işlemini yapacak //Bu metot sayesinde paint yeniden çalıştırıl ve şekiller çizilir } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); if(c == KeyEvent.VK_LEFT){ if(uzayGemisiX <= 0){ uzayGemisiX = 0; }else{ uzayGemisiX -= dirUZayX; } } if(c == KeyEvent.VK_RIGHT){ if(uzayGemisiX >= 750){ uzayGemisiX = 750; }else{ uzayGemisiX += dirUZayX; } } else if(c == KeyEvent.VK_CONTROL){ atesler.add(new Ates(uzayGemisiX+15,470)); harcanan_ates++; } } @Override public void keyReleased(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { //ActionListener interface içerisinde ki bu actionPerformed metodu timer her çalıştığı zaman bu metot harekete geçer ve topları hareket ettirmeyi sağla for(Ates ates : atesler){ ates.setY(ates.getY() - atesdirY); } topX += topdirX; if(topX >= 750){ topdirX = -topdirX; } if(topX <=0){ topdirX = -topdirX; } repaint(); } }
UTF-8
Java
6,879
java
Oyun.java
Java
[]
null
[]
import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; class Ates{ //Ateşimizin bir x, y koordinatı olacak ve her actionPerformed çalıştığında ateşimiz bir ileri gitmeye çalışacak private int x; //X Koordinatı private int y; //Y Koordinatı public Ates(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } public class Oyun extends JPanel implements KeyListener,ActionListener{ //KeyListener interface klavyeden bir tuşa basıldığında gerekli metodları kullanabilmemizi sağlar //ActionListener interface nesnelere hareket kazandırmak için kullanılır Timer timer = new Timer(5, this); private int gecen_sure = 0; private int harcanan_ates = 0; private BufferedImage image;//proje içerisindeki .png dosyasını alarak JPanel üzerinde kullanmamız için obje oluşturduk private ArrayList<Ates> atesler = new ArrayList<Ates>(); //Ateşlerimiz yukarı doğru gidiyor sağa sola gitmiyor. Ateşleri her timer çalıştığında 1 ileri götürmek için atesdirY = 1 olur //sağa sola hareket etmediği için topX = 0 tanımlarız private int atesdirY = 1; //Ateşler oluşacak ve bu ates her actionPerformed çalıştığında o ateşleri Y koordinatına ekleyeceğiz ve böylelikle ateşlerimiz hareket edecek private int topX = 0; //Sağa sola gitmeyi ayarlar ve ilk başta top 0,0 noktasından başlar bu top'ı sürekli bir artıracağız böylece tpumuz sürekli hareket edecek private int topdirX = 2;// topdirX sürekli topX e eklenecek, böylece topX sağda belli bir limite çarptığı zaman sola dönecek private int uzayGemisiX = 0; // Uzay Gemisinin ilk olarak hangi noktadan başlayacağını gösterir private int dirUZayX = 20; // Bu sayede sağ veya sol yön tuşuna bastığımızda uzay gemisi 20 birim hareket edecek public boolean kontrolEt(){ for(Ates ates : atesler){ if(new Rectangle(ates.getX(), ates.getY(), 10, 20).intersects(new Rectangle(topX, 0,20,20))){ //Intersects iki karenin birbirine çarpıp çarpmadığını kontrol etmek için kullanılır return true; } } return false; } public Oyun(){ try { image = ImageIO.read(new FileInputStream(new File("uzaygemisi.png"))); //image nesnesini ImageIO clasından okutarak uzaygemisi.png ekleyerek oluşturduk } catch (FileNotFoundException ex) { Logger.getLogger(Oyun.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Oyun.class.getName()).log(Level.SEVERE, null, ex); } setBackground(Color.black);//JPanel arka plan rengi siyah yapıldı. timer.start(); } @Override public void paint(Graphics g) { super.paint(g); //To change body of generated methods, choose Tools | Templates. gecen_sure += 5; g.setColor(Color.red); g.fillOval(topX, 0, 20, 20); //Başlangıç noktası 0,0 Y hiç hareket etmeyeceği için direk 0 yazıldı. topX güncellendikçe top X-X yönünde hareket edecek. //20,20 topun çapı g.drawImage(image, uzayGemisiX, 490, image.getWidth()/10,image.getHeight()/10,this); for(Ates ates : atesler){ if(ates.getY() < 0){ atesler.remove(ates); } } g.setColor(Color.blue); for(Ates ates : atesler){ g.fillRect(ates.getX(), ates.getY(), 10, 20); } if(kontrolEt()){ timer.stop(); String message = "Kazandınıız \n"+ "Harcanan Ateş : " + harcanan_ates +"\n"+ "Geçen süre : " + gecen_sure / 1000.0; JOptionPane.showMessageDialog(this, message); System.exit(0); } } @Override public void repaint() { super.repaint(); //To change body of generated methods, choose Tools | Templates. //aslında Repaint çağrıldığında paintte birlikte çağrılır //repaint() oyunlarda kesin yazılmalıdır //ActionPerformed fonksiyonu yazıldığında bu metot en sonda yazılacak ve şekillerimizi yeniden çizme işlemini yapacak //Bu metot sayesinde paint yeniden çalıştırıl ve şekiller çizilir } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); if(c == KeyEvent.VK_LEFT){ if(uzayGemisiX <= 0){ uzayGemisiX = 0; }else{ uzayGemisiX -= dirUZayX; } } if(c == KeyEvent.VK_RIGHT){ if(uzayGemisiX >= 750){ uzayGemisiX = 750; }else{ uzayGemisiX += dirUZayX; } } else if(c == KeyEvent.VK_CONTROL){ atesler.add(new Ates(uzayGemisiX+15,470)); harcanan_ates++; } } @Override public void keyReleased(KeyEvent e) { } @Override public void actionPerformed(ActionEvent e) { //ActionListener interface içerisinde ki bu actionPerformed metodu timer her çalıştığı zaman bu metot harekete geçer ve topları hareket ettirmeyi sağla for(Ates ates : atesler){ ates.setY(ates.getY() - atesdirY); } topX += topdirX; if(topX >= 750){ topdirX = -topdirX; } if(topX <=0){ topdirX = -topdirX; } repaint(); } }
6,879
0.581967
0.571088
207
30.405798
33.412651
171
false
false
0
0
0
0
0
0
0.502415
false
false
7
c281f3bb8daac66991fa61430523cf034d8ce676
9,174,050,209,333
681d8300b964b72b83e16131158fab1987b9fab2
/generator/src/main/java/groove/GrooveGxlHelper.java
f729453bea6e06ed02cc7038791cea61d361f401
[]
no_license
timKraeuter/Rewrite_Rule_Generation
https://github.com/timKraeuter/Rewrite_Rule_Generation
65793dbeaa2b273f1e0ba07d5c63f4d2c6bf1835
b082ec1e6ee9bf48243f5f90f0ac3bbff511be53
refs/heads/master
2023-08-19T00:26:27.830000
2023-08-14T10:01:14
2023-08-14T10:01:14
421,366,814
2
0
null
false
2023-08-02T13:38:19
2021-10-26T09:45:33
2023-05-24T17:21:58
2023-08-02T13:37:31
229,434
2
0
0
Java
false
false
package groove; import groove.gxl.Attr; import groove.gxl.Edge; import groove.gxl.Graph; import groove.gxl.Gxl; import groove.gxl.Node; import java.util.HashMap; import java.util.Map; import org.eclipse.elk.core.RecursiveGraphLayoutEngine; import org.eclipse.elk.core.util.BasicProgressMonitor; import org.eclipse.elk.graph.ElkNode; import org.eclipse.elk.graph.util.ElkGraphUtil; public class GrooveGxlHelper { private static final int XY_SHIFT_GROOVE_LAYOUT = 50; private static final String LABEL = "label"; private static final String FLAG = "flag:"; private GrooveGxlHelper() { // Helper methods. } public static Graph createStandardGxlGraph(String id, Gxl gxl) { Graph graph = new Graph(); gxl.getGraph().add(graph); graph.setRole("rule"); graph.setEdgeids("false"); graph.setEdgemode("directed"); graph.setId(id); return graph; } public static Node createNodeWithName(String nodeId, String nodeName, Graph graph) { Node gxlNode = new groove.gxl.Node(); gxlNode.setId(nodeId); groove.gxl.Edge nameEdge = new groove.gxl.Edge(); nameEdge.setFrom(gxlNode); nameEdge.setTo(gxlNode); Attr nameAttr = createLabelAttribute(nodeName); nameEdge.getAttr().add(nameAttr); graph.getNodeOrEdgeOrRel().add(gxlNode); graph.getNodeOrEdgeOrRel().add(nameEdge); return gxlNode; } public static void createEdgeWithName( Graph graph, groove.gxl.Node sourceNode, groove.gxl.Node targetNode, String name) { groove.gxl.Edge gxledge = new groove.gxl.Edge(); gxledge.setFrom(sourceNode); gxledge.setTo(targetNode); Attr nameAttr = GrooveGxlHelper.createLabelAttribute(name); gxledge.getAttr().add(nameAttr); graph.getNodeOrEdgeOrRel().add(gxledge); } public static void addFlagToNode(Graph graph, groove.gxl.Node node, String flagValue) { groove.gxl.Edge gxledge = new groove.gxl.Edge(); gxledge.setFrom(node); gxledge.setTo(node); Attr flagAttr = createLabelAttribute(FLAG + flagValue); gxledge.getAttr().add(flagAttr); graph.getNodeOrEdgeOrRel().add(gxledge); } public static Attr createLabelAttribute(String value) { return createAttribute(LABEL, value); } private static Attr createAttribute(String attrName, String attrValue) { Attr nameAttr = new Attr(); groove.gxl.String name = new groove.gxl.String(); name.setvalue(attrValue); nameAttr.getLocatorOrBoolOrIntOrFloatOrStringOrEnumOrSeqOrSetOrBagOrTup().add(name); nameAttr.setName(attrName); return nameAttr; } public static void layoutGraph(Graph graph, Map<String, String> nodeLabels) { Map<String, ElkNode> layoutNodes = new HashMap<>(); ElkNode layoutGraph = createElkGraph(graph, nodeLabels, layoutNodes); RecursiveGraphLayoutEngine recursiveGraphLayoutEngine = new RecursiveGraphLayoutEngine(); recursiveGraphLayoutEngine.layout(layoutGraph, new BasicProgressMonitor()); // Add layout info to gxl graph .getNodeOrEdgeOrRel() .forEach( nodeOrEdge -> { if (nodeOrEdge instanceof groove.gxl.Node gxlNode) { final ElkNode layoutNode = layoutNodes.get(gxlNode.getId()); GrooveGxlHelper.addLayoutToNode( gxlNode, layoutNode.getX() + XY_SHIFT_GROOVE_LAYOUT, layoutNode.getY() + XY_SHIFT_GROOVE_LAYOUT); } }); } private static void addLayoutToNode(Node gxlNode, double x, double y) { Attr layoutAttr = createAttribute("layout", String.format("%.0f %.0f 0 0", x, y)); gxlNode.getAttr().add(layoutAttr); } private static ElkNode createElkGraph( Graph graph, Map<String, String> nodeLabels, Map<String, ElkNode> layoutNodes) { ElkNode layoutGraph = ElkGraphUtil.createGraph(); graph .getNodeOrEdgeOrRel() .forEach( nodeOrEdge -> { if (nodeOrEdge instanceof groove.gxl.Node gxlNode) { createNodeIfNeeded(layoutNodes, layoutGraph, gxlNode.getId(), nodeLabels); } if (nodeOrEdge instanceof Edge edge) { final String fromId = ((groove.gxl.Node) edge.getFrom()).getId(); final String toId = ((groove.gxl.Node) edge.getTo()).getId(); final ElkNode sourceLayoutNode = createNodeIfNeeded(layoutNodes, layoutGraph, fromId, nodeLabels); final ElkNode targetLayoutNode = createNodeIfNeeded(layoutNodes, layoutGraph, toId, nodeLabels); ElkGraphUtil.createSimpleEdge(sourceLayoutNode, targetLayoutNode); } }); return layoutGraph; } private static ElkNode createNodeIfNeeded( Map<String, ElkNode> layoutNodes, ElkNode layoutGraph, String id, Map<String, String> nodeLabels) { return layoutNodes.computeIfAbsent( id, key -> { ElkNode node = ElkGraphUtil.createNode(layoutGraph); node.setHeight(50d); node.setWidth(nodeLabels.get(key).length() * 15d); return node; }); } }
UTF-8
Java
5,153
java
GrooveGxlHelper.java
Java
[]
null
[]
package groove; import groove.gxl.Attr; import groove.gxl.Edge; import groove.gxl.Graph; import groove.gxl.Gxl; import groove.gxl.Node; import java.util.HashMap; import java.util.Map; import org.eclipse.elk.core.RecursiveGraphLayoutEngine; import org.eclipse.elk.core.util.BasicProgressMonitor; import org.eclipse.elk.graph.ElkNode; import org.eclipse.elk.graph.util.ElkGraphUtil; public class GrooveGxlHelper { private static final int XY_SHIFT_GROOVE_LAYOUT = 50; private static final String LABEL = "label"; private static final String FLAG = "flag:"; private GrooveGxlHelper() { // Helper methods. } public static Graph createStandardGxlGraph(String id, Gxl gxl) { Graph graph = new Graph(); gxl.getGraph().add(graph); graph.setRole("rule"); graph.setEdgeids("false"); graph.setEdgemode("directed"); graph.setId(id); return graph; } public static Node createNodeWithName(String nodeId, String nodeName, Graph graph) { Node gxlNode = new groove.gxl.Node(); gxlNode.setId(nodeId); groove.gxl.Edge nameEdge = new groove.gxl.Edge(); nameEdge.setFrom(gxlNode); nameEdge.setTo(gxlNode); Attr nameAttr = createLabelAttribute(nodeName); nameEdge.getAttr().add(nameAttr); graph.getNodeOrEdgeOrRel().add(gxlNode); graph.getNodeOrEdgeOrRel().add(nameEdge); return gxlNode; } public static void createEdgeWithName( Graph graph, groove.gxl.Node sourceNode, groove.gxl.Node targetNode, String name) { groove.gxl.Edge gxledge = new groove.gxl.Edge(); gxledge.setFrom(sourceNode); gxledge.setTo(targetNode); Attr nameAttr = GrooveGxlHelper.createLabelAttribute(name); gxledge.getAttr().add(nameAttr); graph.getNodeOrEdgeOrRel().add(gxledge); } public static void addFlagToNode(Graph graph, groove.gxl.Node node, String flagValue) { groove.gxl.Edge gxledge = new groove.gxl.Edge(); gxledge.setFrom(node); gxledge.setTo(node); Attr flagAttr = createLabelAttribute(FLAG + flagValue); gxledge.getAttr().add(flagAttr); graph.getNodeOrEdgeOrRel().add(gxledge); } public static Attr createLabelAttribute(String value) { return createAttribute(LABEL, value); } private static Attr createAttribute(String attrName, String attrValue) { Attr nameAttr = new Attr(); groove.gxl.String name = new groove.gxl.String(); name.setvalue(attrValue); nameAttr.getLocatorOrBoolOrIntOrFloatOrStringOrEnumOrSeqOrSetOrBagOrTup().add(name); nameAttr.setName(attrName); return nameAttr; } public static void layoutGraph(Graph graph, Map<String, String> nodeLabels) { Map<String, ElkNode> layoutNodes = new HashMap<>(); ElkNode layoutGraph = createElkGraph(graph, nodeLabels, layoutNodes); RecursiveGraphLayoutEngine recursiveGraphLayoutEngine = new RecursiveGraphLayoutEngine(); recursiveGraphLayoutEngine.layout(layoutGraph, new BasicProgressMonitor()); // Add layout info to gxl graph .getNodeOrEdgeOrRel() .forEach( nodeOrEdge -> { if (nodeOrEdge instanceof groove.gxl.Node gxlNode) { final ElkNode layoutNode = layoutNodes.get(gxlNode.getId()); GrooveGxlHelper.addLayoutToNode( gxlNode, layoutNode.getX() + XY_SHIFT_GROOVE_LAYOUT, layoutNode.getY() + XY_SHIFT_GROOVE_LAYOUT); } }); } private static void addLayoutToNode(Node gxlNode, double x, double y) { Attr layoutAttr = createAttribute("layout", String.format("%.0f %.0f 0 0", x, y)); gxlNode.getAttr().add(layoutAttr); } private static ElkNode createElkGraph( Graph graph, Map<String, String> nodeLabels, Map<String, ElkNode> layoutNodes) { ElkNode layoutGraph = ElkGraphUtil.createGraph(); graph .getNodeOrEdgeOrRel() .forEach( nodeOrEdge -> { if (nodeOrEdge instanceof groove.gxl.Node gxlNode) { createNodeIfNeeded(layoutNodes, layoutGraph, gxlNode.getId(), nodeLabels); } if (nodeOrEdge instanceof Edge edge) { final String fromId = ((groove.gxl.Node) edge.getFrom()).getId(); final String toId = ((groove.gxl.Node) edge.getTo()).getId(); final ElkNode sourceLayoutNode = createNodeIfNeeded(layoutNodes, layoutGraph, fromId, nodeLabels); final ElkNode targetLayoutNode = createNodeIfNeeded(layoutNodes, layoutGraph, toId, nodeLabels); ElkGraphUtil.createSimpleEdge(sourceLayoutNode, targetLayoutNode); } }); return layoutGraph; } private static ElkNode createNodeIfNeeded( Map<String, ElkNode> layoutNodes, ElkNode layoutGraph, String id, Map<String, String> nodeLabels) { return layoutNodes.computeIfAbsent( id, key -> { ElkNode node = ElkGraphUtil.createNode(layoutGraph); node.setHeight(50d); node.setWidth(nodeLabels.get(key).length() * 15d); return node; }); } }
5,153
0.670677
0.668737
152
32.901318
26.601038
93
false
false
0
0
0
0
0
0
0.769737
false
false
7
033205e3eaedad0b123639e7964c13f4b7cb2519
6,674,379,239,008
06ee020ef1ff50a7048adc720c42e8823021b493
/src/main/java/com/herokuapp/frs/service/UserSessionService.java
f3b7c6d60d1d37072d6d7ec06b15ff9d6bf4035c
[]
no_license
amauris-f/recommender-system
https://github.com/amauris-f/recommender-system
e1f579b44020a143ea77e7f1b854a3117431114b
af4d8a1e4767c3def98fddd01ba3afcca769deb7
refs/heads/master
2022-12-16T13:43:11.390000
2019-09-23T22:58:08
2019-09-23T22:58:08
150,381,005
0
0
null
false
2022-12-08T14:37:24
2018-09-26T06:48:31
2019-09-23T22:58:39
2022-12-08T14:37:24
4,146
0
0
9
Java
false
false
package com.herokuapp.frs.service; import com.herokuapp.frs.entity.User; import com.herokuapp.frs.entity.UserSession; public interface UserSessionService { public void createUserSession(User user, String uuid, int expiry); public void updateUserSession(User user, String uuid, int expiry); public void deleteUserSession(User user, String uuid); public UserSession getUserSessionBySessionId(String uuid); public UserSession getUserSessionByUserId(int userId); }
UTF-8
Java
473
java
UserSessionService.java
Java
[]
null
[]
package com.herokuapp.frs.service; import com.herokuapp.frs.entity.User; import com.herokuapp.frs.entity.UserSession; public interface UserSessionService { public void createUserSession(User user, String uuid, int expiry); public void updateUserSession(User user, String uuid, int expiry); public void deleteUserSession(User user, String uuid); public UserSession getUserSessionBySessionId(String uuid); public UserSession getUserSessionByUserId(int userId); }
473
0.811839
0.811839
13
35.46154
25.725222
68
false
false
0
0
0
0
0
0
1
false
false
7
604b74e54082a46fd1783402510ff775357bd504
8,839,042,763,179
da7fd83ad13d0cd205ba9ad1cd74d754ad284a89
/src/chess/ChessTimer.java
ddb6a2f8319e7357c1d29cbb48170995d918c021
[]
no_license
BrainyZombie/javaSwingsChess
https://github.com/BrainyZombie/javaSwingsChess
f8ff692171aa03c00b5aca53fea5938a6c2ab385
dd39c56035cd41793a8eddb58c72e32eff2bc938
refs/heads/master
2021-05-09T12:45:04.946000
2018-04-06T19:11:04
2018-04-06T19:11:04
119,017,543
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chess; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.time.Duration; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JLabel; import javax.swing.JPanel; /** * * @author pranav */ public class ChessTimer extends JPanel { Timer timer = new Timer(); int secondsLeft = 20 * 60; JLabel time = new JLabel("20:00"); Color timerColor = new Color(170, 170, 170); Font timerFont = new Font("Verdana", Font.PLAIN, 35); Duration duration; public ChessTimer(int size) { this.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 40)); this.setBackground(Color.black); time.setFont(timerFont); time.setForeground(timerColor); this.setPreferredSize(new Dimension(size * 3, size * 3)); this.add(time); } public void startTimer() { timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { duration = Duration.ofSeconds(secondsLeft); if (--secondsLeft < 0) timer.cancel(); else time.setText("" + duration.toMinutes() + ":" + (secondsLeft - duration.toMinutes() * 60 + 1)); } }, 0, 1000); } public void pauseTimer() { timer.cancel(); } }
UTF-8
Java
1,664
java
ChessTimer.java
Java
[ { "context": "bel;\nimport javax.swing.JPanel;\n\n/**\n *\n * @author pranav\n */\npublic class ChessTimer extends JPanel {\n ", "end": 524, "score": 0.9890149235725403, "start": 518, "tag": "USERNAME", "value": "pranav" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package chess; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.time.Duration; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JLabel; import javax.swing.JPanel; /** * * @author pranav */ public class ChessTimer extends JPanel { Timer timer = new Timer(); int secondsLeft = 20 * 60; JLabel time = new JLabel("20:00"); Color timerColor = new Color(170, 170, 170); Font timerFont = new Font("Verdana", Font.PLAIN, 35); Duration duration; public ChessTimer(int size) { this.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 40)); this.setBackground(Color.black); time.setFont(timerFont); time.setForeground(timerColor); this.setPreferredSize(new Dimension(size * 3, size * 3)); this.add(time); } public void startTimer() { timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { duration = Duration.ofSeconds(secondsLeft); if (--secondsLeft < 0) timer.cancel(); else time.setText("" + duration.toMinutes() + ":" + (secondsLeft - duration.toMinutes() * 60 + 1)); } }, 0, 1000); } public void pauseTimer() { timer.cancel(); } }
1,664
0.61238
0.591947
59
27.20339
21.694942
114
false
false
0
0
0
0
0
0
0.711864
false
false
7
394bbc8e36676e000cd16cfb479ee26781f69cd8
4,544,075,466,262
a5fb2c0f4daa9551c90feb3bc4d30a01382e6996
/trechnocraft/common/Trechnocraft.java
534b226725bca1fe220b1bf4bb4a1279b544e4b8
[]
no_license
Trek3/Trechnocraft
https://github.com/Trek3/Trechnocraft
1bf95e2eaadca9ac6f9494caaf50e514c26a691b
632b398938b30ddbe738f0d1f141c72e7a57cb79
refs/heads/master
2016-09-05T18:39:46.255000
2013-05-03T12:58:32
2013-05-03T12:58:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mods.trechnocraft.common; import java.util.HashMap; import java.util.Map; import mods.trechnocraft.client.ClientProxyTrechnocraft; import mods.trechnocraft.common.biome.ColdWoodBiome; import mods.trechnocraft.common.biome.MoonBiome; import mods.trechnocraft.common.biome.RedHotBiome; import mods.trechnocraft.common.biome.SavanaBiome; import mods.trechnocraft.common.blocks.BlockAmazzoniteOre; import mods.trechnocraft.common.blocks.BlockBrass; import mods.trechnocraft.common.blocks.BlockCarbonOre; import mods.trechnocraft.common.blocks.BlockChestBlock; import mods.trechnocraft.common.blocks.BlockCopperOre; import mods.trechnocraft.common.blocks.BlockFoundry; import mods.trechnocraft.common.blocks.BlockLeadOre; import mods.trechnocraft.common.blocks.BlockNickelOre; import mods.trechnocraft.common.blocks.BlockPewter; import mods.trechnocraft.common.blocks.BlockRegolite; import mods.trechnocraft.common.blocks.BlockTinOre; import mods.trechnocraft.common.blocks.BlockTitaniumOre; import mods.trechnocraft.common.blocks.BlockTungstenOre; import mods.trechnocraft.common.blocks.BlockUraniumOre; import mods.trechnocraft.common.blocks.BlockZincOre; import mods.trechnocraft.common.entity.EntityElephant; import mods.trechnocraft.common.entity.EntityTroll; import mods.trechnocraft.common.gui.GuiChestBlock; import mods.trechnocraft.common.blocks.BlockTecnezioOre; import mods.trechnocraft.common.items.ItemAmazzonite; import mods.trechnocraft.common.items.ItemBronzeAxe; import mods.trechnocraft.common.items.ItemBronzeHoe; import mods.trechnocraft.common.items.ItemBronzeIngot; import mods.trechnocraft.common.items.ItemBronzePickaxe; import mods.trechnocraft.common.items.ItemBronzeShovel; import mods.trechnocraft.common.items.ItemBronzeSword; import mods.trechnocraft.common.items.ItemCarbon; import mods.trechnocraft.common.items.ItemCopperAxe; import mods.trechnocraft.common.items.ItemCopperHoe; import mods.trechnocraft.common.items.ItemCopperIngot; import mods.trechnocraft.common.items.ItemCopperPickaxe; import mods.trechnocraft.common.items.ItemCopperShovel; import mods.trechnocraft.common.items.ItemCopperSword; import mods.trechnocraft.common.items.ItemIvoryArmor; import mods.trechnocraft.common.items.ItemIvoryBoots; import mods.trechnocraft.common.items.ItemIvoryHelmet; import mods.trechnocraft.common.items.ItemIvoryHorn; import mods.trechnocraft.common.items.ItemIvoryLeggins; import mods.trechnocraft.common.items.ItemLeadIngot; import mods.trechnocraft.common.items.ItemNickelIngot; import mods.trechnocraft.common.items.ItemSteelAxe; import mods.trechnocraft.common.items.ItemSteelHoe; import mods.trechnocraft.common.items.ItemSteelIngot; import mods.trechnocraft.common.items.ItemSteelPickaxe; import mods.trechnocraft.common.items.ItemSteelShovel; import mods.trechnocraft.common.items.ItemSteelSword; import mods.trechnocraft.common.items.ItemTecnezio; import mods.trechnocraft.common.items.ItemTinAxe; import mods.trechnocraft.common.items.ItemTinHoe; import mods.trechnocraft.common.items.ItemTinIngot; import mods.trechnocraft.common.items.ItemTinPickaxe; import mods.trechnocraft.common.items.ItemTinShovel; import mods.trechnocraft.common.items.ItemTinSword; import mods.trechnocraft.common.items.ItemTitaniumAxe; import mods.trechnocraft.common.items.ItemTitaniumHoe; import mods.trechnocraft.common.items.ItemTitaniumIngot; import mods.trechnocraft.common.items.ItemTitaniumPickaxe; import mods.trechnocraft.common.items.ItemTitaniumShovel; import mods.trechnocraft.common.items.ItemTitaniumSword; import mods.trechnocraft.common.items.ItemTrechnocraftLogo; import mods.trechnocraft.common.items.ItemTungstenIngot; import mods.trechnocraft.common.items.ItemUraniumIngot; import mods.trechnocraft.common.items.ItemZincIngot; import mods.trechnocraft.common.models.ModelElephant; import mods.trechnocraft.common.tileentity.TileEntityFoundry; import net.minecraft.block.Block; import net.minecraft.block.BlockStone; import net.minecraft.block.StepSound; import net.minecraft.block.material.Material; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.network.*; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import net.minecraft.block.*; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.entity.RenderBiped; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EnumCreatureType; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.src.BaseMod; import net.minecraft.src.ModLoader; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenDesert; import net.minecraftforge.common.EnumHelper; import net.minecraftforge.liquids.IBlockLiquid; @Mod(modid = "Trechnocraft", name = "Trechnocraft", version = "1.0") @NetworkMod(clientSideRequired = true, serverSideRequired = false) public class Trechnocraft{ @Instance("Trechnocraft") public static Trechnocraft instance; @SidedProxy(clientSide="mods.trechnocraft.client.ClientProxyTrechnocraft",serverSide="mods.trechnocraft.common.CommonProxyTrechnocraft") public static ClientProxyTrechnocraft proxy = new ClientProxyTrechnocraft(); public BiomeGenBase trechnocraftBiome = new RedHotBiome(40); public BiomeGenBase trechnocraftBiome1 = new ColdWoodBiome(41); public BiomeGenBase trechnocraftBiome2 = (new SavanaBiome(42)).setColor(2552550).setBiomeName("Savana").setTemperatureRainfall(2.0F, 0.0F).setMinMaxHeight(0.1F, 0.2F); public BiomeGenBase trechnocraftBiome3 = new MoonBiome(44); public static CreativeTabs TrechnoTab = new CustomCreativeTabs("TrechnoTab"); public static Block chestBlock; public static Block foundryBlock; public static Block foundryBlockActive; public static TrechnocaftGuiHandler guiHandler = new TrechnocaftGuiHandler(); //materials public static EnumToolMaterial titanium = EnumHelper.addToolMaterial("Titanio", 2, 150, 9.0F, 6, 10); public static EnumToolMaterial bronze = EnumHelper.addToolMaterial("Bronzo", 2 , 120, 6.0F, 6, 6); public static EnumToolMaterial tin = EnumHelper.addToolMaterial("Stagno", 2 , 100, 5.0F, 6, 6); public static EnumToolMaterial copper = EnumHelper.addToolMaterial("Rame", 2 , 90, 4.0F, 6, 6); public static EnumToolMaterial steel = EnumHelper.addToolMaterial("Acciaio", 2 , 130, 7.5F, 6, 8); public static EnumToolMaterial ivory = EnumHelper.addToolMaterial("Avorio", 2 , 130, 6.5F, 6, 8); public static EnumArmorMaterial ivory1 = EnumHelper.addArmorMaterial("Avorio",50,new int[]{8,20,14,8},10); public static Material petroleum = new MaterialPetroleum(MaterialPetroleum.petroleumColor); //blocks public static Block titaniumOre; public static Block copperOre; public static Block tinOre; public static Block carbonOre; public static Block regolite; public static Block amazzoniteOre; public static Block tecnezioOre; public static Block uraniumOre; public static Block zincOre; public static Block tungstenOre; public static Block leadOre; public static Block nickelOre; public static Block pewter; public static Block brass; public static Block petroleumStill; public static Block petroleumFlowing; //items public static Item steelIngot; public static Item titaniumIngot; public static Item copperIngot; public static Item tinIngot; public static Item bronzeIngot; public static Item uraniumIngot; public static Item zincIngot; public static Item leadIngot; public static Item tungstenIngot; public static Item nickelIngot; public static Item ivoryHorn; public static Item carbon; public static Item amazzonite; public static Item tecnezio; public static Item trechnocraftLogo; public static Item ivoryHelmet; public static Item ivoryPlate; public static Item ivoryLeggins; public static Item ivoryBoots; //tool sets public static Item titaniumPickaxe; public static Item steelPickaxe; public static Item bronzePickaxe; public static Item tinPickaxe; public static Item copperPickaxe; public static Item titaniumAxe; public static Item steelAxe; public static Item bronzeAxe; public static Item tinAxe; public static Item copperAxe; public static Item titaniumShovel; public static Item steelShovel; public static Item bronzeShovel; public static Item tinShovel; public static Item copperShovel; public static Item titaniumHoe; public static Item steelHoe; public static Item bronzeHoe; public static Item tinHoe; public static Item copperHoe; public static Item titaniumSword; public static Item steelSword; public static Item bronzeSword; public static Item tinSword; public static Item copperSword; //step sounds public static final StepSound soundStoneFootstep = new StepSound("stone", 1.0F, 1.0F); static int titaniumOreID = 500; static int copperOreID = 501; static int tinOreID = 502; static int carbonOreID = 503; static int regoliteID = 504; static int amazzoniteOreID = 505; static int tecnezioOreID = 506; static int uraniumOreID = 507; static int zincOreID = 508; static int leadOreID = 509; static int nickelOreID = 510; static int tungstenOreID = 511; static int pewterID = 512; static int brassID = 513; static int petroleumStillID = 514; static int petroleumFlowingID = 515; static int titaniumIngotID = 700; static int copperIngotID = 701; static int tinIngotID = 702; static int bronzeIngotID = 703; static int ivoryHornID = 705; static int carbonID = 706; static int steelIngotID = 707; static int amazzoniteID = 708; static int tecnezioID = 709; static int trechnocraftLogoID = 732; static int uraniumIngotID = 733; static int zincIngotID = 734; static int leadIngotID = 735; static int tungstenIngotID = 736; static int nickelIngotID = 737; static int ivoryHelmetID = 729; static int ivoryPlateID = 730; static int ivoryLegginsID = 731; static int ivoryBootsID = 728; static int titaniumPickaxeID = 708; static int steelPickaxeID = 726; static int bronzePickaxeID = 712; static int tinPickaxeID = 713; static int copperPickaxeID = 714; static int titaniumAxeID = 720; static int steelAxeID = 727; static int bronzeAxeID =721; static int tinAxeID = 722; static int copperAxeID = 723; static int titaniumShovelID = 738; static int steelShovelID = 739; static int bronzeShovelID =740; static int tinShovelID = 741; static int copperShovelID = 742; static int titaniumHoeID = 743; static int steelHoeID = 744; static int bronzeHoeID =745; static int tinHoeID = 746; static int copperHoeID = 747; static int titaniumSwordID = 748; static int steelSwordID = 749; static int bronzeSwordID =750; static int tinSwordID = 751; static int copperSwordID = 752; static int foundryBlockID = 710; static int foundryBlockActiveID = 711; @Init public void load(FMLInitializationEvent event){ proxy.init(); titaniumOre = new BlockTitaniumOre(titaniumOreID, Material.iron).setHardness(3.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Titanio"); copperOre = new BlockCopperOre(copperOreID, Material.iron).setHardness(2.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Rame"); tinOre = new BlockTinOre(tinOreID, Material.iron).setHardness(1.5F).setStepSound(soundStoneFootstep).setUnlocalizedName("Stagno"); carbonOre = new BlockCarbonOre(carbonOreID, Material.iron).setHardness(2.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Carbonio"); regolite = new BlockRegolite(regoliteID, Material.sand).setHardness(6F).setResistance(7.0F).setUnlocalizedName("Regolite"); amazzoniteOre = new BlockAmazzoniteOre(amazzoniteOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Amazzonite"); tecnezioOre = new BlockTecnezioOre(tecnezioOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Tecnezio"); uraniumOre = new BlockUraniumOre(uraniumOreID, Material.iron).setLightValue(0.5F).setHardness(1.5F).setUnlocalizedName("Uranio"); zincOre = new BlockZincOre(zincOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Zinco"); nickelOre = new BlockNickelOre(nickelOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Nichel"); tungstenOre = new BlockTungstenOre(tungstenOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Tungsteno"); leadOre = new BlockLeadOre(leadOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Piombo"); pewter = new BlockPewter(pewterID, Material.iron).setHardness(1.5F).setUnlocalizedName("Peltro"); brass = new BlockBrass(brassID, Material.iron).setHardness(1.5F).setUnlocalizedName("Ottone"); foundryBlock= new BlockFoundry(foundryBlockID, false).setUnlocalizedName("Fonderia"); foundryBlockActive= new BlockFoundry(foundryBlockActiveID, true).setUnlocalizedName("Fonderia"); petroleumStill = new BlockPetroleumStill(petroleumStillID).setUnlocalizedName("Petrolio"); petroleumFlowing = new BlockPetroleumFlowing(petroleumFlowingID).setUnlocalizedName("Petrolio"); steelIngot = new ItemSteelIngot(steelIngotID).setUnlocalizedName("Acciaio"); titaniumIngot = new ItemTitaniumIngot(titaniumIngotID).setUnlocalizedName("LingottodiTitanio"); copperIngot = new ItemCopperIngot(copperIngotID).setUnlocalizedName("LingottodiRame"); tinIngot = new ItemTinIngot(tinIngotID).setUnlocalizedName("LingottodiStagno"); bronzeIngot = new ItemBronzeIngot(bronzeIngotID).setUnlocalizedName("LingottodiBronzo"); uraniumIngot = new ItemUraniumIngot(uraniumIngotID).setUnlocalizedName("LingottodiUranio"); zincIngot = new ItemZincIngot(zincIngotID).setUnlocalizedName("LingottodiZinco"); leadIngot = new ItemLeadIngot(leadIngotID).setUnlocalizedName("LingottodiPiombo"); tungstenIngot = new ItemTungstenIngot(tungstenIngotID).setUnlocalizedName("LingottodiTungsteno"); nickelIngot = new ItemNickelIngot(nickelIngotID).setUnlocalizedName("LingottodiNichel"); ivoryHorn = new ItemIvoryHorn(ivoryHornID).setUnlocalizedName("Corno d'Avorio"); carbon = new ItemCarbon(carbonID).setUnlocalizedName("CarbonioRaffinato"); amazzonite = new ItemAmazzonite(amazzoniteID).setUnlocalizedName("AmazzoniteRaffinata"); tecnezio = new ItemTecnezio(tecnezioID).setUnlocalizedName("TecnezioRaffinato"); trechnocraftLogo = new ItemTrechnocraftLogo(trechnocraftLogoID).setUnlocalizedName("Trechnocraft Logo"); ivoryHelmet=new ItemIvoryArmor(ivoryHelmetID,ivory1,(proxy).addArmor("Avorio"),0).setUnlocalizedName("ElmodAvorio"); ivoryPlate=new ItemIvoryArmor(ivoryPlateID,ivory1,proxy.addArmor("Avorio"),1).setUnlocalizedName("CorazzadAvorio"); ivoryLeggins=new ItemIvoryArmor(ivoryLegginsID,ivory1,proxy.addArmor("Avorio"),2).setUnlocalizedName("GambalidAvorio"); ivoryBoots=new ItemIvoryArmor(ivoryBootsID,ivory1,proxy.addArmor("Avorio"),3).setUnlocalizedName("StivalidAvorio"); titaniumPickaxe = new ItemTitaniumPickaxe(titaniumPickaxeID, titanium).setUnlocalizedName("PicconeTitanio"); steelPickaxe = new ItemSteelPickaxe(steelPickaxeID, steel).setUnlocalizedName("PicconeAcciaio"); bronzePickaxe = new ItemBronzePickaxe(bronzePickaxeID, bronze).setUnlocalizedName("PicconeBronzo"); tinPickaxe = new ItemTinPickaxe(tinPickaxeID, tin).setUnlocalizedName("PicconeStagno"); copperPickaxe = new ItemCopperPickaxe(copperPickaxeID, copper).setUnlocalizedName("PicconeRame"); titaniumAxe = new ItemTitaniumAxe(titaniumAxeID, titanium).setUnlocalizedName("AsciaTitanio"); steelAxe = new ItemSteelAxe(steelAxeID, steel).setUnlocalizedName("AsciaAcciaio"); bronzeAxe = new ItemBronzeAxe(bronzeAxeID, bronze).setUnlocalizedName("AsciaBronzo"); tinAxe = new ItemTinAxe(tinAxeID, tin).setUnlocalizedName("AsciaStagno"); copperAxe = new ItemCopperAxe(copperAxeID, copper).setUnlocalizedName("AsciaRame"); titaniumShovel = new ItemTitaniumShovel(titaniumShovelID, titanium).setUnlocalizedName("PalaTitanio"); steelShovel = new ItemSteelShovel(steelShovelID, steel).setUnlocalizedName("PalaAcciaio"); bronzeShovel = new ItemBronzeShovel(bronzeShovelID, bronze).setUnlocalizedName("PalaBronzo"); tinShovel = new ItemTinShovel(tinShovelID, tin).setUnlocalizedName("PalaStagno"); copperShovel = new ItemCopperShovel(copperShovelID, copper).setUnlocalizedName("PalaRame"); titaniumHoe = new ItemTitaniumHoe(titaniumHoeID, titanium).setUnlocalizedName("ZappaTitanio"); steelHoe = new ItemSteelHoe(steelHoeID, steel).setUnlocalizedName("ZappaAcciaio"); bronzeHoe = new ItemBronzeHoe(bronzeHoeID, bronze).setUnlocalizedName("ZappaBronzo"); tinHoe = new ItemTinHoe(tinHoeID, tin).setUnlocalizedName("ZappaStagno"); copperHoe = new ItemCopperHoe(copperHoeID, copper).setUnlocalizedName("ZappaRame"); titaniumSword = new ItemTitaniumSword(titaniumSwordID, titanium).setUnlocalizedName("SpadaTitanio"); steelSword = new ItemSteelSword(steelSwordID, steel).setUnlocalizedName("SpadaAcciaio"); bronzeSword = new ItemBronzeSword(bronzeSwordID, bronze).setUnlocalizedName("SpadaBronzo"); tinSword = new ItemTinSword(tinSwordID, tin).setUnlocalizedName("SpadaStagno"); copperSword = new ItemCopperSword(copperSwordID, copper).setUnlocalizedName("SpadaRame"); chestBlock = new BlockChestBlock(499, Material.wood, null).setUnlocalizedName("Cesta"); GameRegistry.addBiome(trechnocraftBiome); GameRegistry.addBiome(trechnocraftBiome1); GameRegistry.addBiome(trechnocraftBiome2); GameRegistry.addBiome(trechnocraftBiome3); gameRegisters(); languageRegisters(); craftingRecipes(); proxy.registerRenders(); GameRegistry.addSmelting(titaniumOre.blockID, new ItemStack(Trechnocraft.titaniumIngot,1),0.5F); GameRegistry.addSmelting(copperOre.blockID, new ItemStack(Trechnocraft.copperIngot,1),0.5F); GameRegistry.addSmelting(tinOre.blockID, new ItemStack(Trechnocraft.tinIngot,1),0.5F); GameRegistry.addSmelting(amazzoniteOre.blockID, new ItemStack(Trechnocraft.amazzonite, 1), 0.5F); GameRegistry.addSmelting(Item.ingotIron.itemID, new ItemStack(Trechnocraft.steelIngot,1), 0.5F); GameRegistry.addSmelting(Trechnocraft.tinIngot.itemID, new ItemStack(Trechnocraft.bronzeIngot,1), 1.5F); GameRegistry.addSmelting(Trechnocraft.copperIngotID, new ItemStack(Trechnocraft.brass,1), 1.0F); GameRegistry.registerWorldGenerator(new WorldGeneratorTrechnocraft()); GameRegistry.registerWorldGenerator(new WorldGeneratorStructures()); GameRegistry.registerFuelHandler(new TrechnocraftFuelHandler()); GameRegistry.registerTileEntity(TileEntityFoundry.class, "tileEntityFoundry"); NetworkRegistry.instance().registerGuiHandler(this, guiHandler); EntityRegistry.registerGlobalEntityID(EntityElephant.class, "Elefante", EntityRegistry.findGlobalUniqueEntityId(),3515848,12102); EntityRegistry.registerGlobalEntityID(EntityTroll.class,"Troll",EntityRegistry.findGlobalUniqueEntityId(),16777215,9474208); EntityRegistry.addSpawn(EntityElephant.class, 40, 6, 12, EnumCreatureType.creature, trechnocraftBiome2); EntityRegistry.addSpawn(EntityTroll.class, 50, 2, 5, EnumCreatureType.monster, trechnocraftBiome); } private static void gameRegisters(){ GameRegistry.registerBlock(titaniumOre, "Titanio"); GameRegistry.registerBlock(copperOre, "Rame"); GameRegistry.registerBlock(tinOre, "Stagno"); GameRegistry.registerBlock(carbonOre, "Carbonio"); GameRegistry.registerBlock(regolite, "Regolite"); GameRegistry.registerBlock(amazzoniteOre, "Amazzonite"); GameRegistry.registerBlock(tecnezioOre, "Tecnezio"); GameRegistry.registerBlock(uraniumOre, "Uranio"); GameRegistry.registerBlock(zincOre, "Zinco"); GameRegistry.registerBlock(tungstenOre, "Tungsteno"); GameRegistry.registerBlock(leadOre, "Piombo"); GameRegistry.registerBlock(nickelOre, "Nichel"); GameRegistry.registerBlock(pewter, "Peltro"); GameRegistry.registerBlock(brass, "Ottone"); GameRegistry.registerBlock(foundryBlock, "Fonderia"); GameRegistry.registerBlock(petroleumStill, "PetrolioFermo"); GameRegistry.registerBlock(petroleumFlowing, "PetrolioInMovimento"); GameRegistry.registerItem(titaniumIngot, "Lingotto di Titanio"); GameRegistry.registerItem(copperIngot, "Lingotto di Rame"); GameRegistry.registerItem(tinIngot, "Lingotto di Stagno"); GameRegistry.registerItem(bronzeIngot, "Lingotto di Bronzo"); GameRegistry.registerItem(steelIngot, "Lingotto di Acciaio"); GameRegistry.registerItem(uraniumIngot, "Lingotto di Uranio"); GameRegistry.registerItem(zincIngot, "Lingotto di Zinco"); GameRegistry.registerItem(leadIngot, "Lingotto di Piombo"); GameRegistry.registerItem(tungstenIngot, "Lingotto di Tungsteno"); GameRegistry.registerItem(nickelIngot, "Lingotto di Nichel"); GameRegistry.registerItem(amazzonite, "Amazzonite Raffinata"); GameRegistry.registerItem(tecnezio, "Tecnezio Raffinato"); GameRegistry.registerItem(titaniumPickaxe, "Piccone di Titanio"); GameRegistry.registerItem(steelPickaxe, "Piccone d'Acciaio"); GameRegistry.registerItem(bronzePickaxe, "Piccone di Bronzo"); GameRegistry.registerItem(tinPickaxe, "Piccone di Stagno"); GameRegistry.registerItem(copperPickaxe, "Piccone di Rame"); GameRegistry.registerItem(titaniumAxe, "Ascia di Titanio"); GameRegistry.registerItem(steelAxe, "Ascia d'Acciaio"); GameRegistry.registerItem(bronzeAxe, "Ascia di Bronzo"); GameRegistry.registerItem(tinAxe, "Ascia di Stagno"); GameRegistry.registerItem(copperAxe, "Ascia di Rame"); GameRegistry.registerItem(titaniumShovel, "Pala di Titanio"); GameRegistry.registerItem(steelShovel, "Pala d'Acciaio"); GameRegistry.registerItem(bronzeShovel, "Pala di Bronzo"); GameRegistry.registerItem(tinShovel, "Pala di Stagno"); GameRegistry.registerItem(copperShovel, "Pala di Rame"); GameRegistry.registerItem(titaniumHoe, "Zappa di Titanio"); GameRegistry.registerItem(steelHoe, "Zappa d'Acciaio"); GameRegistry.registerItem(bronzeHoe, "Zappa di Bronzo"); GameRegistry.registerItem(tinHoe, "Zappa di Stagno"); GameRegistry.registerItem(copperHoe, "Zappa di Rame"); GameRegistry.registerItem(titaniumSword, "Spada di Titanio"); GameRegistry.registerItem(steelSword, "Spada d'Acciaio"); GameRegistry.registerItem(bronzeSword, "Spada di Bronzo"); GameRegistry.registerItem(tinSword, "Spada di Stagno"); GameRegistry.registerItem(copperSword, "Spada di Rame"); GameRegistry.registerItem(ivoryPlate, "Corazza d'Avorio"); GameRegistry.registerItem(ivoryHelmet, "Elmo d'Avorio"); GameRegistry.registerItem(ivoryBoots, "Stivali d'Avorio"); GameRegistry.registerItem(ivoryLeggins, "Gambali d'Avorio"); GameRegistry.registerItem(carbon, "Grafite"); GameRegistry.registerItem(ivoryHorn, "Corno d'Avorio"); } private static void languageRegisters(){ LanguageRegistry.addName(titaniumOre, "Titanio"); LanguageRegistry.addName(copperOre, "Rame"); LanguageRegistry.addName(tinOre, "Stagno"); LanguageRegistry.addName(carbonOre, "Carbonio"); LanguageRegistry.addName(regolite, "Regolite"); LanguageRegistry.addName(amazzoniteOre, "Amazzonite"); LanguageRegistry.addName(tecnezioOre, "Tecnezio"); LanguageRegistry.addName(uraniumOre, "Uranio"); LanguageRegistry.addName(zincOre, "Zinco"); LanguageRegistry.addName(tungstenOre, "Tungsteno"); LanguageRegistry.addName(leadOre, "Piombo"); LanguageRegistry.addName(nickelOre, "Nichel"); LanguageRegistry.addName(pewter, "Peltro"); LanguageRegistry.addName(brass, "Ottone"); LanguageRegistry.addName(foundryBlock, "Fonderia"); LanguageRegistry.addName(petroleumStill, "Petrolio Fermo"); LanguageRegistry.addName(petroleumFlowing, "Petrolio in Movimento"); LanguageRegistry.addName(titaniumIngot, "Lingotto di Titanio"); LanguageRegistry.addName(copperIngot, "Lingotto di Rame"); LanguageRegistry.addName(tinIngot, "Lingotto di Stagno"); LanguageRegistry.addName(bronzeIngot, "Lingotto di Bronzo"); LanguageRegistry.addName(steelIngot, "Lingotto di Acciaio"); LanguageRegistry.addName(uraniumIngot, "Lingotto di Uranio"); LanguageRegistry.addName(zincIngot, "Lingotto di Zinco"); LanguageRegistry.addName(leadIngot, "Lingotto di Piombo"); LanguageRegistry.addName(tungstenIngot, "Lingotto di Tungsteno"); LanguageRegistry.addName(nickelIngot, "Lingotto di Nichel"); LanguageRegistry.addName(amazzonite, "Amazzonite Raffinata"); LanguageRegistry.addName(tecnezio, "Tecnezio Raffinato"); LanguageRegistry.addName(titaniumPickaxe, "Piccone di Titanio"); LanguageRegistry.addName(steelPickaxe, "Piccone d'Acciaio"); LanguageRegistry.addName(bronzePickaxe, "Piccone di Bronzo"); LanguageRegistry.addName(tinPickaxe, "Piccone di Stagno"); LanguageRegistry.addName(copperPickaxe, "Piccone di Rame"); LanguageRegistry.addName(titaniumAxe, "Ascia di Titanio"); LanguageRegistry.addName(steelAxe, "Ascia d'Acciaio"); LanguageRegistry.addName(bronzeAxe, "Ascia di Bronzo"); LanguageRegistry.addName(tinAxe, "Ascia di Stagno"); LanguageRegistry.addName(copperAxe, "Ascia di Rame"); LanguageRegistry.addName(titaniumShovel, "Pala di Titanio"); LanguageRegistry.addName(steelShovel, "Pala d'Acciaio"); LanguageRegistry.addName(bronzeShovel, "Pala di Bronzo"); LanguageRegistry.addName(tinShovel, "Pala di Stagno"); LanguageRegistry.addName(copperShovel, "Pala di Rame"); LanguageRegistry.addName(titaniumHoe, "Zappa di Titanio"); LanguageRegistry.addName(steelHoe, "Zappa d'Acciaio"); LanguageRegistry.addName(bronzeHoe, "Zappa di Bronzo"); LanguageRegistry.addName(tinHoe, "Zappa di Stagno"); LanguageRegistry.addName(copperHoe, "Zappa di Rame"); LanguageRegistry.addName(titaniumSword, "Spada di Titanio"); LanguageRegistry.addName(steelSword, "Spada d'Acciaio"); LanguageRegistry.addName(bronzeSword, "Spada di Bronzo"); LanguageRegistry.addName(tinSword, "Spada di Stagno"); LanguageRegistry.addName(copperSword, "Spada di Rame"); LanguageRegistry.addName(ivoryBoots, "Stivali d'Avorio"); LanguageRegistry.addName(ivoryHelmet, "Elmo d'Avorio"); LanguageRegistry.addName(ivoryLeggins, "Gambali d'Avorio"); LanguageRegistry.addName(ivoryPlate, "Corazza d'Avorio"); LanguageRegistry.addName(carbon, "Grafite"); LanguageRegistry.addName(ivoryHorn, "Corno d'Avorio"); } public void craftingRecipes(){ GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumPickaxe), new Object[]{ "TTT"," S "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelPickaxe), new Object[]{ "sss"," S "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzePickaxe), new Object[]{ "BBB"," S "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinPickaxe), new Object[]{ "ttt"," S "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperPickaxe), new Object[]{ "CCC"," S "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumAxe), new Object[]{ "TT ","TS "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelAxe), new Object[]{ "ss ","sS "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeAxe), new Object[]{ "BB ","BS "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinAxe), new Object[]{ "tt ","tS "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperAxe), new Object[]{ "CC ","CS "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryHelmet), new Object[]{ " ","III","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryBoots), new Object[]{ " ","I I","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryPlate), new Object[]{ "I I","III","III", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryLeggins), new Object[]{ "III","I I","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumShovel), new Object[]{ " T "," S "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeShovel), new Object[]{ " B "," S "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinShovel), new Object[]{ " t "," S "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperShovel), new Object[]{ " C "," S "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelShovel), new Object[]{ " s "," S "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumSword), new Object[]{ " T "," T "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeSword), new Object[]{ " B "," B "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinSword), new Object[]{ " t "," t "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperSword), new Object[]{ " C "," C "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelSword), new Object[]{ " s "," s "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.foundryBlock), new Object[]{ "ccc","cfc","ccc", 'c', Block.cobblestone, 'f', Block.furnaceIdle, }); } }
UTF-8
Java
31,263
java
Trechnocraft.java
Java
[ { "context": "iombo\");\n\t\tGameRegistry.registerBlock(nickelOre, \"Nichel\");\n\t\tGameRegistry.registerBlock(pewter, \"Peltro\")", "end": 20440, "score": 0.8958957195281982, "start": 20434, "tag": "NAME", "value": "Nichel" }, { "context": "ameRegistry.registerItem(nickelIngot, \"Lingotto di Nichel\");\n\t\tGameRegistry.registerItem(amazzonite, \"Amazz", "end": 21370, "score": 0.7902143001556396, "start": 21364, "tag": "NAME", "value": "Nichel" }, { "context": "LanguageRegistry.addName(nickelIngot, \"Lingotto di Nichel\");\n\t\tLanguageRegistry.addName(amazzonite, \"Amazzo", "end": 24926, "score": 0.6582704782485962, "start": 24920, "tag": "NAME", "value": "Nichel" } ]
null
[]
package mods.trechnocraft.common; import java.util.HashMap; import java.util.Map; import mods.trechnocraft.client.ClientProxyTrechnocraft; import mods.trechnocraft.common.biome.ColdWoodBiome; import mods.trechnocraft.common.biome.MoonBiome; import mods.trechnocraft.common.biome.RedHotBiome; import mods.trechnocraft.common.biome.SavanaBiome; import mods.trechnocraft.common.blocks.BlockAmazzoniteOre; import mods.trechnocraft.common.blocks.BlockBrass; import mods.trechnocraft.common.blocks.BlockCarbonOre; import mods.trechnocraft.common.blocks.BlockChestBlock; import mods.trechnocraft.common.blocks.BlockCopperOre; import mods.trechnocraft.common.blocks.BlockFoundry; import mods.trechnocraft.common.blocks.BlockLeadOre; import mods.trechnocraft.common.blocks.BlockNickelOre; import mods.trechnocraft.common.blocks.BlockPewter; import mods.trechnocraft.common.blocks.BlockRegolite; import mods.trechnocraft.common.blocks.BlockTinOre; import mods.trechnocraft.common.blocks.BlockTitaniumOre; import mods.trechnocraft.common.blocks.BlockTungstenOre; import mods.trechnocraft.common.blocks.BlockUraniumOre; import mods.trechnocraft.common.blocks.BlockZincOre; import mods.trechnocraft.common.entity.EntityElephant; import mods.trechnocraft.common.entity.EntityTroll; import mods.trechnocraft.common.gui.GuiChestBlock; import mods.trechnocraft.common.blocks.BlockTecnezioOre; import mods.trechnocraft.common.items.ItemAmazzonite; import mods.trechnocraft.common.items.ItemBronzeAxe; import mods.trechnocraft.common.items.ItemBronzeHoe; import mods.trechnocraft.common.items.ItemBronzeIngot; import mods.trechnocraft.common.items.ItemBronzePickaxe; import mods.trechnocraft.common.items.ItemBronzeShovel; import mods.trechnocraft.common.items.ItemBronzeSword; import mods.trechnocraft.common.items.ItemCarbon; import mods.trechnocraft.common.items.ItemCopperAxe; import mods.trechnocraft.common.items.ItemCopperHoe; import mods.trechnocraft.common.items.ItemCopperIngot; import mods.trechnocraft.common.items.ItemCopperPickaxe; import mods.trechnocraft.common.items.ItemCopperShovel; import mods.trechnocraft.common.items.ItemCopperSword; import mods.trechnocraft.common.items.ItemIvoryArmor; import mods.trechnocraft.common.items.ItemIvoryBoots; import mods.trechnocraft.common.items.ItemIvoryHelmet; import mods.trechnocraft.common.items.ItemIvoryHorn; import mods.trechnocraft.common.items.ItemIvoryLeggins; import mods.trechnocraft.common.items.ItemLeadIngot; import mods.trechnocraft.common.items.ItemNickelIngot; import mods.trechnocraft.common.items.ItemSteelAxe; import mods.trechnocraft.common.items.ItemSteelHoe; import mods.trechnocraft.common.items.ItemSteelIngot; import mods.trechnocraft.common.items.ItemSteelPickaxe; import mods.trechnocraft.common.items.ItemSteelShovel; import mods.trechnocraft.common.items.ItemSteelSword; import mods.trechnocraft.common.items.ItemTecnezio; import mods.trechnocraft.common.items.ItemTinAxe; import mods.trechnocraft.common.items.ItemTinHoe; import mods.trechnocraft.common.items.ItemTinIngot; import mods.trechnocraft.common.items.ItemTinPickaxe; import mods.trechnocraft.common.items.ItemTinShovel; import mods.trechnocraft.common.items.ItemTinSword; import mods.trechnocraft.common.items.ItemTitaniumAxe; import mods.trechnocraft.common.items.ItemTitaniumHoe; import mods.trechnocraft.common.items.ItemTitaniumIngot; import mods.trechnocraft.common.items.ItemTitaniumPickaxe; import mods.trechnocraft.common.items.ItemTitaniumShovel; import mods.trechnocraft.common.items.ItemTitaniumSword; import mods.trechnocraft.common.items.ItemTrechnocraftLogo; import mods.trechnocraft.common.items.ItemTungstenIngot; import mods.trechnocraft.common.items.ItemUraniumIngot; import mods.trechnocraft.common.items.ItemZincIngot; import mods.trechnocraft.common.models.ModelElephant; import mods.trechnocraft.common.tileentity.TileEntityFoundry; import net.minecraft.block.Block; import net.minecraft.block.BlockStone; import net.minecraft.block.StepSound; import net.minecraft.block.material.Material; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.network.*; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import net.minecraft.block.*; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.entity.RenderBiped; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EnumCreatureType; import net.minecraft.item.EnumArmorMaterial; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.src.BaseMod; import net.minecraft.src.ModLoader; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenDesert; import net.minecraftforge.common.EnumHelper; import net.minecraftforge.liquids.IBlockLiquid; @Mod(modid = "Trechnocraft", name = "Trechnocraft", version = "1.0") @NetworkMod(clientSideRequired = true, serverSideRequired = false) public class Trechnocraft{ @Instance("Trechnocraft") public static Trechnocraft instance; @SidedProxy(clientSide="mods.trechnocraft.client.ClientProxyTrechnocraft",serverSide="mods.trechnocraft.common.CommonProxyTrechnocraft") public static ClientProxyTrechnocraft proxy = new ClientProxyTrechnocraft(); public BiomeGenBase trechnocraftBiome = new RedHotBiome(40); public BiomeGenBase trechnocraftBiome1 = new ColdWoodBiome(41); public BiomeGenBase trechnocraftBiome2 = (new SavanaBiome(42)).setColor(2552550).setBiomeName("Savana").setTemperatureRainfall(2.0F, 0.0F).setMinMaxHeight(0.1F, 0.2F); public BiomeGenBase trechnocraftBiome3 = new MoonBiome(44); public static CreativeTabs TrechnoTab = new CustomCreativeTabs("TrechnoTab"); public static Block chestBlock; public static Block foundryBlock; public static Block foundryBlockActive; public static TrechnocaftGuiHandler guiHandler = new TrechnocaftGuiHandler(); //materials public static EnumToolMaterial titanium = EnumHelper.addToolMaterial("Titanio", 2, 150, 9.0F, 6, 10); public static EnumToolMaterial bronze = EnumHelper.addToolMaterial("Bronzo", 2 , 120, 6.0F, 6, 6); public static EnumToolMaterial tin = EnumHelper.addToolMaterial("Stagno", 2 , 100, 5.0F, 6, 6); public static EnumToolMaterial copper = EnumHelper.addToolMaterial("Rame", 2 , 90, 4.0F, 6, 6); public static EnumToolMaterial steel = EnumHelper.addToolMaterial("Acciaio", 2 , 130, 7.5F, 6, 8); public static EnumToolMaterial ivory = EnumHelper.addToolMaterial("Avorio", 2 , 130, 6.5F, 6, 8); public static EnumArmorMaterial ivory1 = EnumHelper.addArmorMaterial("Avorio",50,new int[]{8,20,14,8},10); public static Material petroleum = new MaterialPetroleum(MaterialPetroleum.petroleumColor); //blocks public static Block titaniumOre; public static Block copperOre; public static Block tinOre; public static Block carbonOre; public static Block regolite; public static Block amazzoniteOre; public static Block tecnezioOre; public static Block uraniumOre; public static Block zincOre; public static Block tungstenOre; public static Block leadOre; public static Block nickelOre; public static Block pewter; public static Block brass; public static Block petroleumStill; public static Block petroleumFlowing; //items public static Item steelIngot; public static Item titaniumIngot; public static Item copperIngot; public static Item tinIngot; public static Item bronzeIngot; public static Item uraniumIngot; public static Item zincIngot; public static Item leadIngot; public static Item tungstenIngot; public static Item nickelIngot; public static Item ivoryHorn; public static Item carbon; public static Item amazzonite; public static Item tecnezio; public static Item trechnocraftLogo; public static Item ivoryHelmet; public static Item ivoryPlate; public static Item ivoryLeggins; public static Item ivoryBoots; //tool sets public static Item titaniumPickaxe; public static Item steelPickaxe; public static Item bronzePickaxe; public static Item tinPickaxe; public static Item copperPickaxe; public static Item titaniumAxe; public static Item steelAxe; public static Item bronzeAxe; public static Item tinAxe; public static Item copperAxe; public static Item titaniumShovel; public static Item steelShovel; public static Item bronzeShovel; public static Item tinShovel; public static Item copperShovel; public static Item titaniumHoe; public static Item steelHoe; public static Item bronzeHoe; public static Item tinHoe; public static Item copperHoe; public static Item titaniumSword; public static Item steelSword; public static Item bronzeSword; public static Item tinSword; public static Item copperSword; //step sounds public static final StepSound soundStoneFootstep = new StepSound("stone", 1.0F, 1.0F); static int titaniumOreID = 500; static int copperOreID = 501; static int tinOreID = 502; static int carbonOreID = 503; static int regoliteID = 504; static int amazzoniteOreID = 505; static int tecnezioOreID = 506; static int uraniumOreID = 507; static int zincOreID = 508; static int leadOreID = 509; static int nickelOreID = 510; static int tungstenOreID = 511; static int pewterID = 512; static int brassID = 513; static int petroleumStillID = 514; static int petroleumFlowingID = 515; static int titaniumIngotID = 700; static int copperIngotID = 701; static int tinIngotID = 702; static int bronzeIngotID = 703; static int ivoryHornID = 705; static int carbonID = 706; static int steelIngotID = 707; static int amazzoniteID = 708; static int tecnezioID = 709; static int trechnocraftLogoID = 732; static int uraniumIngotID = 733; static int zincIngotID = 734; static int leadIngotID = 735; static int tungstenIngotID = 736; static int nickelIngotID = 737; static int ivoryHelmetID = 729; static int ivoryPlateID = 730; static int ivoryLegginsID = 731; static int ivoryBootsID = 728; static int titaniumPickaxeID = 708; static int steelPickaxeID = 726; static int bronzePickaxeID = 712; static int tinPickaxeID = 713; static int copperPickaxeID = 714; static int titaniumAxeID = 720; static int steelAxeID = 727; static int bronzeAxeID =721; static int tinAxeID = 722; static int copperAxeID = 723; static int titaniumShovelID = 738; static int steelShovelID = 739; static int bronzeShovelID =740; static int tinShovelID = 741; static int copperShovelID = 742; static int titaniumHoeID = 743; static int steelHoeID = 744; static int bronzeHoeID =745; static int tinHoeID = 746; static int copperHoeID = 747; static int titaniumSwordID = 748; static int steelSwordID = 749; static int bronzeSwordID =750; static int tinSwordID = 751; static int copperSwordID = 752; static int foundryBlockID = 710; static int foundryBlockActiveID = 711; @Init public void load(FMLInitializationEvent event){ proxy.init(); titaniumOre = new BlockTitaniumOre(titaniumOreID, Material.iron).setHardness(3.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Titanio"); copperOre = new BlockCopperOre(copperOreID, Material.iron).setHardness(2.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Rame"); tinOre = new BlockTinOre(tinOreID, Material.iron).setHardness(1.5F).setStepSound(soundStoneFootstep).setUnlocalizedName("Stagno"); carbonOre = new BlockCarbonOre(carbonOreID, Material.iron).setHardness(2.0F).setStepSound(soundStoneFootstep).setUnlocalizedName("Carbonio"); regolite = new BlockRegolite(regoliteID, Material.sand).setHardness(6F).setResistance(7.0F).setUnlocalizedName("Regolite"); amazzoniteOre = new BlockAmazzoniteOre(amazzoniteOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Amazzonite"); tecnezioOre = new BlockTecnezioOre(tecnezioOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Tecnezio"); uraniumOre = new BlockUraniumOre(uraniumOreID, Material.iron).setLightValue(0.5F).setHardness(1.5F).setUnlocalizedName("Uranio"); zincOre = new BlockZincOre(zincOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Zinco"); nickelOre = new BlockNickelOre(nickelOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Nichel"); tungstenOre = new BlockTungstenOre(tungstenOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Tungsteno"); leadOre = new BlockLeadOre(leadOreID, Material.iron).setHardness(1.5F).setUnlocalizedName("Piombo"); pewter = new BlockPewter(pewterID, Material.iron).setHardness(1.5F).setUnlocalizedName("Peltro"); brass = new BlockBrass(brassID, Material.iron).setHardness(1.5F).setUnlocalizedName("Ottone"); foundryBlock= new BlockFoundry(foundryBlockID, false).setUnlocalizedName("Fonderia"); foundryBlockActive= new BlockFoundry(foundryBlockActiveID, true).setUnlocalizedName("Fonderia"); petroleumStill = new BlockPetroleumStill(petroleumStillID).setUnlocalizedName("Petrolio"); petroleumFlowing = new BlockPetroleumFlowing(petroleumFlowingID).setUnlocalizedName("Petrolio"); steelIngot = new ItemSteelIngot(steelIngotID).setUnlocalizedName("Acciaio"); titaniumIngot = new ItemTitaniumIngot(titaniumIngotID).setUnlocalizedName("LingottodiTitanio"); copperIngot = new ItemCopperIngot(copperIngotID).setUnlocalizedName("LingottodiRame"); tinIngot = new ItemTinIngot(tinIngotID).setUnlocalizedName("LingottodiStagno"); bronzeIngot = new ItemBronzeIngot(bronzeIngotID).setUnlocalizedName("LingottodiBronzo"); uraniumIngot = new ItemUraniumIngot(uraniumIngotID).setUnlocalizedName("LingottodiUranio"); zincIngot = new ItemZincIngot(zincIngotID).setUnlocalizedName("LingottodiZinco"); leadIngot = new ItemLeadIngot(leadIngotID).setUnlocalizedName("LingottodiPiombo"); tungstenIngot = new ItemTungstenIngot(tungstenIngotID).setUnlocalizedName("LingottodiTungsteno"); nickelIngot = new ItemNickelIngot(nickelIngotID).setUnlocalizedName("LingottodiNichel"); ivoryHorn = new ItemIvoryHorn(ivoryHornID).setUnlocalizedName("Corno d'Avorio"); carbon = new ItemCarbon(carbonID).setUnlocalizedName("CarbonioRaffinato"); amazzonite = new ItemAmazzonite(amazzoniteID).setUnlocalizedName("AmazzoniteRaffinata"); tecnezio = new ItemTecnezio(tecnezioID).setUnlocalizedName("TecnezioRaffinato"); trechnocraftLogo = new ItemTrechnocraftLogo(trechnocraftLogoID).setUnlocalizedName("Trechnocraft Logo"); ivoryHelmet=new ItemIvoryArmor(ivoryHelmetID,ivory1,(proxy).addArmor("Avorio"),0).setUnlocalizedName("ElmodAvorio"); ivoryPlate=new ItemIvoryArmor(ivoryPlateID,ivory1,proxy.addArmor("Avorio"),1).setUnlocalizedName("CorazzadAvorio"); ivoryLeggins=new ItemIvoryArmor(ivoryLegginsID,ivory1,proxy.addArmor("Avorio"),2).setUnlocalizedName("GambalidAvorio"); ivoryBoots=new ItemIvoryArmor(ivoryBootsID,ivory1,proxy.addArmor("Avorio"),3).setUnlocalizedName("StivalidAvorio"); titaniumPickaxe = new ItemTitaniumPickaxe(titaniumPickaxeID, titanium).setUnlocalizedName("PicconeTitanio"); steelPickaxe = new ItemSteelPickaxe(steelPickaxeID, steel).setUnlocalizedName("PicconeAcciaio"); bronzePickaxe = new ItemBronzePickaxe(bronzePickaxeID, bronze).setUnlocalizedName("PicconeBronzo"); tinPickaxe = new ItemTinPickaxe(tinPickaxeID, tin).setUnlocalizedName("PicconeStagno"); copperPickaxe = new ItemCopperPickaxe(copperPickaxeID, copper).setUnlocalizedName("PicconeRame"); titaniumAxe = new ItemTitaniumAxe(titaniumAxeID, titanium).setUnlocalizedName("AsciaTitanio"); steelAxe = new ItemSteelAxe(steelAxeID, steel).setUnlocalizedName("AsciaAcciaio"); bronzeAxe = new ItemBronzeAxe(bronzeAxeID, bronze).setUnlocalizedName("AsciaBronzo"); tinAxe = new ItemTinAxe(tinAxeID, tin).setUnlocalizedName("AsciaStagno"); copperAxe = new ItemCopperAxe(copperAxeID, copper).setUnlocalizedName("AsciaRame"); titaniumShovel = new ItemTitaniumShovel(titaniumShovelID, titanium).setUnlocalizedName("PalaTitanio"); steelShovel = new ItemSteelShovel(steelShovelID, steel).setUnlocalizedName("PalaAcciaio"); bronzeShovel = new ItemBronzeShovel(bronzeShovelID, bronze).setUnlocalizedName("PalaBronzo"); tinShovel = new ItemTinShovel(tinShovelID, tin).setUnlocalizedName("PalaStagno"); copperShovel = new ItemCopperShovel(copperShovelID, copper).setUnlocalizedName("PalaRame"); titaniumHoe = new ItemTitaniumHoe(titaniumHoeID, titanium).setUnlocalizedName("ZappaTitanio"); steelHoe = new ItemSteelHoe(steelHoeID, steel).setUnlocalizedName("ZappaAcciaio"); bronzeHoe = new ItemBronzeHoe(bronzeHoeID, bronze).setUnlocalizedName("ZappaBronzo"); tinHoe = new ItemTinHoe(tinHoeID, tin).setUnlocalizedName("ZappaStagno"); copperHoe = new ItemCopperHoe(copperHoeID, copper).setUnlocalizedName("ZappaRame"); titaniumSword = new ItemTitaniumSword(titaniumSwordID, titanium).setUnlocalizedName("SpadaTitanio"); steelSword = new ItemSteelSword(steelSwordID, steel).setUnlocalizedName("SpadaAcciaio"); bronzeSword = new ItemBronzeSword(bronzeSwordID, bronze).setUnlocalizedName("SpadaBronzo"); tinSword = new ItemTinSword(tinSwordID, tin).setUnlocalizedName("SpadaStagno"); copperSword = new ItemCopperSword(copperSwordID, copper).setUnlocalizedName("SpadaRame"); chestBlock = new BlockChestBlock(499, Material.wood, null).setUnlocalizedName("Cesta"); GameRegistry.addBiome(trechnocraftBiome); GameRegistry.addBiome(trechnocraftBiome1); GameRegistry.addBiome(trechnocraftBiome2); GameRegistry.addBiome(trechnocraftBiome3); gameRegisters(); languageRegisters(); craftingRecipes(); proxy.registerRenders(); GameRegistry.addSmelting(titaniumOre.blockID, new ItemStack(Trechnocraft.titaniumIngot,1),0.5F); GameRegistry.addSmelting(copperOre.blockID, new ItemStack(Trechnocraft.copperIngot,1),0.5F); GameRegistry.addSmelting(tinOre.blockID, new ItemStack(Trechnocraft.tinIngot,1),0.5F); GameRegistry.addSmelting(amazzoniteOre.blockID, new ItemStack(Trechnocraft.amazzonite, 1), 0.5F); GameRegistry.addSmelting(Item.ingotIron.itemID, new ItemStack(Trechnocraft.steelIngot,1), 0.5F); GameRegistry.addSmelting(Trechnocraft.tinIngot.itemID, new ItemStack(Trechnocraft.bronzeIngot,1), 1.5F); GameRegistry.addSmelting(Trechnocraft.copperIngotID, new ItemStack(Trechnocraft.brass,1), 1.0F); GameRegistry.registerWorldGenerator(new WorldGeneratorTrechnocraft()); GameRegistry.registerWorldGenerator(new WorldGeneratorStructures()); GameRegistry.registerFuelHandler(new TrechnocraftFuelHandler()); GameRegistry.registerTileEntity(TileEntityFoundry.class, "tileEntityFoundry"); NetworkRegistry.instance().registerGuiHandler(this, guiHandler); EntityRegistry.registerGlobalEntityID(EntityElephant.class, "Elefante", EntityRegistry.findGlobalUniqueEntityId(),3515848,12102); EntityRegistry.registerGlobalEntityID(EntityTroll.class,"Troll",EntityRegistry.findGlobalUniqueEntityId(),16777215,9474208); EntityRegistry.addSpawn(EntityElephant.class, 40, 6, 12, EnumCreatureType.creature, trechnocraftBiome2); EntityRegistry.addSpawn(EntityTroll.class, 50, 2, 5, EnumCreatureType.monster, trechnocraftBiome); } private static void gameRegisters(){ GameRegistry.registerBlock(titaniumOre, "Titanio"); GameRegistry.registerBlock(copperOre, "Rame"); GameRegistry.registerBlock(tinOre, "Stagno"); GameRegistry.registerBlock(carbonOre, "Carbonio"); GameRegistry.registerBlock(regolite, "Regolite"); GameRegistry.registerBlock(amazzoniteOre, "Amazzonite"); GameRegistry.registerBlock(tecnezioOre, "Tecnezio"); GameRegistry.registerBlock(uraniumOre, "Uranio"); GameRegistry.registerBlock(zincOre, "Zinco"); GameRegistry.registerBlock(tungstenOre, "Tungsteno"); GameRegistry.registerBlock(leadOre, "Piombo"); GameRegistry.registerBlock(nickelOre, "Nichel"); GameRegistry.registerBlock(pewter, "Peltro"); GameRegistry.registerBlock(brass, "Ottone"); GameRegistry.registerBlock(foundryBlock, "Fonderia"); GameRegistry.registerBlock(petroleumStill, "PetrolioFermo"); GameRegistry.registerBlock(petroleumFlowing, "PetrolioInMovimento"); GameRegistry.registerItem(titaniumIngot, "Lingotto di Titanio"); GameRegistry.registerItem(copperIngot, "Lingotto di Rame"); GameRegistry.registerItem(tinIngot, "Lingotto di Stagno"); GameRegistry.registerItem(bronzeIngot, "Lingotto di Bronzo"); GameRegistry.registerItem(steelIngot, "Lingotto di Acciaio"); GameRegistry.registerItem(uraniumIngot, "Lingotto di Uranio"); GameRegistry.registerItem(zincIngot, "Lingotto di Zinco"); GameRegistry.registerItem(leadIngot, "Lingotto di Piombo"); GameRegistry.registerItem(tungstenIngot, "Lingotto di Tungsteno"); GameRegistry.registerItem(nickelIngot, "Lingotto di Nichel"); GameRegistry.registerItem(amazzonite, "Amazzonite Raffinata"); GameRegistry.registerItem(tecnezio, "Tecnezio Raffinato"); GameRegistry.registerItem(titaniumPickaxe, "Piccone di Titanio"); GameRegistry.registerItem(steelPickaxe, "Piccone d'Acciaio"); GameRegistry.registerItem(bronzePickaxe, "Piccone di Bronzo"); GameRegistry.registerItem(tinPickaxe, "Piccone di Stagno"); GameRegistry.registerItem(copperPickaxe, "Piccone di Rame"); GameRegistry.registerItem(titaniumAxe, "Ascia di Titanio"); GameRegistry.registerItem(steelAxe, "Ascia d'Acciaio"); GameRegistry.registerItem(bronzeAxe, "Ascia di Bronzo"); GameRegistry.registerItem(tinAxe, "Ascia di Stagno"); GameRegistry.registerItem(copperAxe, "Ascia di Rame"); GameRegistry.registerItem(titaniumShovel, "Pala di Titanio"); GameRegistry.registerItem(steelShovel, "Pala d'Acciaio"); GameRegistry.registerItem(bronzeShovel, "Pala di Bronzo"); GameRegistry.registerItem(tinShovel, "Pala di Stagno"); GameRegistry.registerItem(copperShovel, "Pala di Rame"); GameRegistry.registerItem(titaniumHoe, "Zappa di Titanio"); GameRegistry.registerItem(steelHoe, "Zappa d'Acciaio"); GameRegistry.registerItem(bronzeHoe, "Zappa di Bronzo"); GameRegistry.registerItem(tinHoe, "Zappa di Stagno"); GameRegistry.registerItem(copperHoe, "Zappa di Rame"); GameRegistry.registerItem(titaniumSword, "Spada di Titanio"); GameRegistry.registerItem(steelSword, "Spada d'Acciaio"); GameRegistry.registerItem(bronzeSword, "Spada di Bronzo"); GameRegistry.registerItem(tinSword, "Spada di Stagno"); GameRegistry.registerItem(copperSword, "Spada di Rame"); GameRegistry.registerItem(ivoryPlate, "Corazza d'Avorio"); GameRegistry.registerItem(ivoryHelmet, "Elmo d'Avorio"); GameRegistry.registerItem(ivoryBoots, "Stivali d'Avorio"); GameRegistry.registerItem(ivoryLeggins, "Gambali d'Avorio"); GameRegistry.registerItem(carbon, "Grafite"); GameRegistry.registerItem(ivoryHorn, "Corno d'Avorio"); } private static void languageRegisters(){ LanguageRegistry.addName(titaniumOre, "Titanio"); LanguageRegistry.addName(copperOre, "Rame"); LanguageRegistry.addName(tinOre, "Stagno"); LanguageRegistry.addName(carbonOre, "Carbonio"); LanguageRegistry.addName(regolite, "Regolite"); LanguageRegistry.addName(amazzoniteOre, "Amazzonite"); LanguageRegistry.addName(tecnezioOre, "Tecnezio"); LanguageRegistry.addName(uraniumOre, "Uranio"); LanguageRegistry.addName(zincOre, "Zinco"); LanguageRegistry.addName(tungstenOre, "Tungsteno"); LanguageRegistry.addName(leadOre, "Piombo"); LanguageRegistry.addName(nickelOre, "Nichel"); LanguageRegistry.addName(pewter, "Peltro"); LanguageRegistry.addName(brass, "Ottone"); LanguageRegistry.addName(foundryBlock, "Fonderia"); LanguageRegistry.addName(petroleumStill, "Petrolio Fermo"); LanguageRegistry.addName(petroleumFlowing, "Petrolio in Movimento"); LanguageRegistry.addName(titaniumIngot, "Lingotto di Titanio"); LanguageRegistry.addName(copperIngot, "Lingotto di Rame"); LanguageRegistry.addName(tinIngot, "Lingotto di Stagno"); LanguageRegistry.addName(bronzeIngot, "Lingotto di Bronzo"); LanguageRegistry.addName(steelIngot, "Lingotto di Acciaio"); LanguageRegistry.addName(uraniumIngot, "Lingotto di Uranio"); LanguageRegistry.addName(zincIngot, "Lingotto di Zinco"); LanguageRegistry.addName(leadIngot, "Lingotto di Piombo"); LanguageRegistry.addName(tungstenIngot, "Lingotto di Tungsteno"); LanguageRegistry.addName(nickelIngot, "Lingotto di Nichel"); LanguageRegistry.addName(amazzonite, "Amazzonite Raffinata"); LanguageRegistry.addName(tecnezio, "Tecnezio Raffinato"); LanguageRegistry.addName(titaniumPickaxe, "Piccone di Titanio"); LanguageRegistry.addName(steelPickaxe, "Piccone d'Acciaio"); LanguageRegistry.addName(bronzePickaxe, "Piccone di Bronzo"); LanguageRegistry.addName(tinPickaxe, "Piccone di Stagno"); LanguageRegistry.addName(copperPickaxe, "Piccone di Rame"); LanguageRegistry.addName(titaniumAxe, "Ascia di Titanio"); LanguageRegistry.addName(steelAxe, "Ascia d'Acciaio"); LanguageRegistry.addName(bronzeAxe, "Ascia di Bronzo"); LanguageRegistry.addName(tinAxe, "Ascia di Stagno"); LanguageRegistry.addName(copperAxe, "Ascia di Rame"); LanguageRegistry.addName(titaniumShovel, "Pala di Titanio"); LanguageRegistry.addName(steelShovel, "Pala d'Acciaio"); LanguageRegistry.addName(bronzeShovel, "Pala di Bronzo"); LanguageRegistry.addName(tinShovel, "Pala di Stagno"); LanguageRegistry.addName(copperShovel, "Pala di Rame"); LanguageRegistry.addName(titaniumHoe, "Zappa di Titanio"); LanguageRegistry.addName(steelHoe, "Zappa d'Acciaio"); LanguageRegistry.addName(bronzeHoe, "Zappa di Bronzo"); LanguageRegistry.addName(tinHoe, "Zappa di Stagno"); LanguageRegistry.addName(copperHoe, "Zappa di Rame"); LanguageRegistry.addName(titaniumSword, "Spada di Titanio"); LanguageRegistry.addName(steelSword, "Spada d'Acciaio"); LanguageRegistry.addName(bronzeSword, "Spada di Bronzo"); LanguageRegistry.addName(tinSword, "Spada di Stagno"); LanguageRegistry.addName(copperSword, "Spada di Rame"); LanguageRegistry.addName(ivoryBoots, "Stivali d'Avorio"); LanguageRegistry.addName(ivoryHelmet, "Elmo d'Avorio"); LanguageRegistry.addName(ivoryLeggins, "Gambali d'Avorio"); LanguageRegistry.addName(ivoryPlate, "Corazza d'Avorio"); LanguageRegistry.addName(carbon, "Grafite"); LanguageRegistry.addName(ivoryHorn, "Corno d'Avorio"); } public void craftingRecipes(){ GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumPickaxe), new Object[]{ "TTT"," S "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelPickaxe), new Object[]{ "sss"," S "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzePickaxe), new Object[]{ "BBB"," S "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinPickaxe), new Object[]{ "ttt"," S "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperPickaxe), new Object[]{ "CCC"," S "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumAxe), new Object[]{ "TT ","TS "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelAxe), new Object[]{ "ss ","sS "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeAxe), new Object[]{ "BB ","BS "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinAxe), new Object[]{ "tt ","tS "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperAxe), new Object[]{ "CC ","CS "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryHelmet), new Object[]{ " ","III","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryBoots), new Object[]{ " ","I I","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryPlate), new Object[]{ "I I","III","III", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.ivoryLeggins), new Object[]{ "III","I I","I I", 'I', Trechnocraft.ivoryHorn, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumShovel), new Object[]{ " T "," S "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeShovel), new Object[]{ " B "," S "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinShovel), new Object[]{ " t "," S "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperShovel), new Object[]{ " C "," S "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelShovel), new Object[]{ " s "," S "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.titaniumSword), new Object[]{ " T "," T "," S ", 'T', Trechnocraft.titaniumIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.bronzeSword), new Object[]{ " B "," B "," S ", 'B', Trechnocraft.bronzeIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.tinSword), new Object[]{ " t "," t "," S ", 't', Trechnocraft.tinIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.copperSword), new Object[]{ " C "," C "," S ", 'C', Trechnocraft.copperIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.steelSword), new Object[]{ " s "," s "," S ", 's', Trechnocraft.steelIngot, 'S', Item.stick, }); GameRegistry.addRecipe(new ItemStack(Trechnocraft.foundryBlock), new Object[]{ "ccc","cfc","ccc", 'c', Block.cobblestone, 'f', Block.furnaceIdle, }); } }
31,263
0.770336
0.758181
668
45.797905
30.349455
168
false
false
0
0
0
0
0
0
3.297904
false
false
7
29c7288a9e526043b95dee7de0c848b97bd34410
6,433,861,076,403
8df0553905ff0503e705c29e37a7fe588e7e332d
/hljkefulibrary/src/main/java/com/hunliji/hljkefulibrary/moudles/TransferToKefu.java
0cc2c648e0f80b5de7c1f0be9722fd12e642d742
[]
no_license
Catfeeds/myWorkspace
https://github.com/Catfeeds/myWorkspace
9cd0af10597af9d28f8d8189ca0245894d270feb
3c0932e626e72301613334fd19c5432494f198d2
refs/heads/master
2020-04-11T12:19:27.141000
2018-04-04T08:14:31
2018-04-04T08:14:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hunliji.hljkefulibrary.moudles; import com.google.gson.annotations.SerializedName; /** * Created by wangtao on 2017/10/25. */ public class TransferToKefu { @SerializedName("id") private String uuid; @SerializedName("serviceSessionId") private String serviceSessionId; @SerializedName("label") private String btnLabel; public String getBtnLabel() { return btnLabel; } public String getServiceSessionId() { return serviceSessionId; } public String getUuid() { return uuid; } }
UTF-8
Java
567
java
TransferToKefu.java
Java
[ { "context": "son.annotations.SerializedName;\n\n/**\n * Created by wangtao on 2017/10/25.\n */\n\npublic class TransferToKefu {", "end": 122, "score": 0.9995675683021545, "start": 115, "tag": "USERNAME", "value": "wangtao" } ]
null
[]
package com.hunliji.hljkefulibrary.moudles; import com.google.gson.annotations.SerializedName; /** * Created by wangtao on 2017/10/25. */ public class TransferToKefu { @SerializedName("id") private String uuid; @SerializedName("serviceSessionId") private String serviceSessionId; @SerializedName("label") private String btnLabel; public String getBtnLabel() { return btnLabel; } public String getServiceSessionId() { return serviceSessionId; } public String getUuid() { return uuid; } }
567
0.677249
0.663139
28
19.25
16.25824
50
false
false
0
0
0
0
0
0
0.285714
false
false
7
e9886c6c9f9c4bbc43ab25dbd2e7959ab2d0365f
6,442,450,944,041
3c4dd0cf7c1844c0680131df6d18dcb62fc26e92
/src/com/company/programs/MainFluentBuilder.java
39129735358f7d776732972dff035ca8f8e6a843
[]
no_license
saronqw/Java_TPU
https://github.com/saronqw/Java_TPU
6ad820f82f2d93d64d58660e4a860d7cceada24b
6625815043d7bd29e704485d3888e5e6f92d413d
refs/heads/master
2021-01-16T15:16:05.078000
2020-06-10T21:50:46
2020-06-10T21:50:46
243,162,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.programs; import com.company.WaterTransportFluentBuilder; public class MainFluentBuilder { public static void main(String[] args) { WaterTransportFluentBuilder waterTransportFluentBuilder = WaterTransportFluentBuilder.createBuilder() .setBonus("Крылья") .setCountPassengers(10) .build(); System.out.println(waterTransportFluentBuilder.showInfo()); waterTransportFluentBuilder = WaterTransportFluentBuilder.createBuilder() .setBonus("Крылья + Парашют") .setCountPassengers(30) .build(); System.out.println(waterTransportFluentBuilder.showInfo()); } }
UTF-8
Java
728
java
MainFluentBuilder.java
Java
[]
null
[]
package com.company.programs; import com.company.WaterTransportFluentBuilder; public class MainFluentBuilder { public static void main(String[] args) { WaterTransportFluentBuilder waterTransportFluentBuilder = WaterTransportFluentBuilder.createBuilder() .setBonus("Крылья") .setCountPassengers(10) .build(); System.out.println(waterTransportFluentBuilder.showInfo()); waterTransportFluentBuilder = WaterTransportFluentBuilder.createBuilder() .setBonus("Крылья + Парашют") .setCountPassengers(30) .build(); System.out.println(waterTransportFluentBuilder.showInfo()); } }
728
0.668547
0.662906
19
36.315788
28.964684
109
false
false
0
0
0
0
0
0
0.315789
false
false
7
5c31cffa3096b81ecfc87b0aa98de4363365e65b
8,512,625,248,138
3f3eb3acde241e9eb838423b193e21f1422cb62f
/src/main/java/ismetsandikci/hrmanagementsystem/api/controllers/ResumesController.java
9200bc21c8791de0f79afa1cb1a23be54acca111
[]
no_license
ismetsandikci/hr-management-system
https://github.com/ismetsandikci/hr-management-system
70b869c18e1411597b84e0d8966eea5e349804f1
51db15f3f73892b6fc35e1af3508644ae1f0300e
refs/heads/main
2023-06-08T11:15:38.869000
2021-06-27T06:01:44
2021-06-27T06:01:44
367,112,758
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ismetsandikci.hrmanagementsystem.api.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import ismetsandikci.hrmanagementsystem.business.abstracts.ResumeService; import ismetsandikci.hrmanagementsystem.core.utilities.results.DataResult; import ismetsandikci.hrmanagementsystem.core.utilities.results.Result; import ismetsandikci.hrmanagementsystem.entities.concretes.Resume; @RestController @RequestMapping("/api/resumes") @CrossOrigin public class ResumesController { private ResumeService resumeService; @Autowired public ResumesController(ResumeService resumeService) { super(); this.resumeService = resumeService; } @GetMapping("/getall") public ResponseEntity<DataResult<List<Resume>>> getAll() { return ResponseEntity.ok(this.resumeService.getAll()); } @GetMapping("/getById") public ResponseEntity<DataResult<Resume>> getById(@RequestParam int id) { return ResponseEntity.ok(this.resumeService.getById(id)); } @GetMapping("/getByCandidateId") public ResponseEntity<DataResult<List<Resume>>> getByCandidateId(@RequestParam int candidateId) { return ResponseEntity.ok(this.resumeService.getByCandidateId(candidateId)); } @PostMapping("/uploadPhoto") public Result uploadImage(@RequestParam int candidateId,@RequestBody MultipartFile file) { return this.resumeService.uploadPhoto(candidateId,file); } @PostMapping("/add") public ResponseEntity<Result> add(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.add(resume)); } @PostMapping("/update") public ResponseEntity<Result> update(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.update(resume)); } @PostMapping("/delete") public ResponseEntity<Result> delete(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.delete(resume)); } }
UTF-8
Java
2,443
java
ResumesController.java
Java
[]
null
[]
package ismetsandikci.hrmanagementsystem.api.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import ismetsandikci.hrmanagementsystem.business.abstracts.ResumeService; import ismetsandikci.hrmanagementsystem.core.utilities.results.DataResult; import ismetsandikci.hrmanagementsystem.core.utilities.results.Result; import ismetsandikci.hrmanagementsystem.entities.concretes.Resume; @RestController @RequestMapping("/api/resumes") @CrossOrigin public class ResumesController { private ResumeService resumeService; @Autowired public ResumesController(ResumeService resumeService) { super(); this.resumeService = resumeService; } @GetMapping("/getall") public ResponseEntity<DataResult<List<Resume>>> getAll() { return ResponseEntity.ok(this.resumeService.getAll()); } @GetMapping("/getById") public ResponseEntity<DataResult<Resume>> getById(@RequestParam int id) { return ResponseEntity.ok(this.resumeService.getById(id)); } @GetMapping("/getByCandidateId") public ResponseEntity<DataResult<List<Resume>>> getByCandidateId(@RequestParam int candidateId) { return ResponseEntity.ok(this.resumeService.getByCandidateId(candidateId)); } @PostMapping("/uploadPhoto") public Result uploadImage(@RequestParam int candidateId,@RequestBody MultipartFile file) { return this.resumeService.uploadPhoto(candidateId,file); } @PostMapping("/add") public ResponseEntity<Result> add(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.add(resume)); } @PostMapping("/update") public ResponseEntity<Result> update(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.update(resume)); } @PostMapping("/delete") public ResponseEntity<Result> delete(@RequestBody Resume resume){ return ResponseEntity.ok(this.resumeService.delete(resume)); } }
2,443
0.802292
0.802292
69
34.405796
29.294764
98
false
false
0
0
0
0
0
0
0.971014
false
false
7
898769583e4a29f84998c18f7dabc00ce9b6e2da
20,907,900,856,003
d9b14f351f668b004c4cb05a10d09e7e85243317
/src/BaekJoon/Math/P20499.java
2be8897070e0191d1e2b29548827a0cc4be2a55b
[]
no_license
nn98/Algorithm
https://github.com/nn98/Algorithm
262cbe20c71ff9b5de292c244b95a2a0c25e5bd7
55b6db19cb9f2aa5c5056f5cabd2b22715b682fd
refs/heads/main
2023-08-17T04:39:41.236000
2023-08-16T13:04:34
2023-08-16T13:04:34
178,701,901
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BaekJoon.Math; public class P20499 { public static void main(String[] args) { String[]a=new java.util.Scanner(System.in).next().split("/"); System.out.println(a[1].equals("0")|(Integer.parseInt(a[0])+Integer.parseInt(a[2])<Integer.parseInt(a[1]))?"hasu":"gosu"); } }
UTF-8
Java
284
java
P20499.java
Java
[]
null
[]
package BaekJoon.Math; public class P20499 { public static void main(String[] args) { String[]a=new java.util.Scanner(System.in).next().split("/"); System.out.println(a[1].equals("0")|(Integer.parseInt(a[0])+Integer.parseInt(a[2])<Integer.parseInt(a[1]))?"hasu":"gosu"); } }
284
0.676056
0.640845
10
27.4
38.011051
124
false
false
0
0
0
0
0
0
1
false
false
7
55afae3abde4806e050c451978fca54408ffc106
16,363,825,400,336
b5f0537be2f2e573247a06c373a1a9da32450ca7
/app/src/main/java/com/yezimm/gathering/htpp/SocketThread.java
1f5d74295bdf7385a5370b279ab56685dc79ae29
[]
no_license
yescofield/Gathering
https://github.com/yescofield/Gathering
2abb564e6bee50694465b02f2c4d2114fec4d019
9fa90c614bdb02b06adfd3ea2d611ec43660aee3
refs/heads/master
2021-01-10T01:13:14.583000
2015-11-11T12:58:56
2015-11-11T12:58:56
45,910,058
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yezimm.gathering.htpp; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; /** * Created by yezimm on 2015/11/11. */ public class SocketThread extends Thread{ Socket socket = null; public SocketThread() { try { this.socket = new Socket("10.141.54.22", 20155); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { super.run(); try { System.out.println("客户端开始连接"); //一直读取控制台 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true){ //包体 byte [] content = br.readLine().getBytes(); //包头,固定4个字节,包含包体长度信息 byte [] head = Tool.intToByteArray1(content.length); BufferedOutputStream bis = new BufferedOutputStream(socket.getOutputStream()); bis.write(head); bis.flush(); bis.write(content); bis.flush(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { socket.close(); }catch (Exception e){ e.printStackTrace(); } } } public static class Tool { //int 转字节数组 public static byte[] intToByteArray1(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF); result[1] = (byte)((i >> 16) & 0xFF); result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF); return result; } public static byte[] intToByteArray2(int i) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); out.writeInt(i); byte[] b = buf.toByteArray(); out.close(); buf.close(); return b; } //字节数组转int public static int byteArrayToInt(byte[] b) { int intValue=0; for(int i=0;i<b.length;i++){ intValue +=(b[i] & 0xFF)<<(8*(3-i)); } return intValue; } } }
UTF-8
Java
2,591
java
SocketThread.java
Java
[ { "context": "Reader;\nimport java.net.Socket;\n\n/**\n * Created by yezimm on 2015/11/11.\n */\npublic class SocketThread exte", "end": 286, "score": 0.9996508955955505, "start": 280, "tag": "USERNAME", "value": "yezimm" }, { "context": " try {\n this.socket = new Socket(\"10.141.54.22\", 20155);\n } catch (IOException e) {\n ", "end": 468, "score": 0.9977188110351562, "start": 456, "tag": "IP_ADDRESS", "value": "10.141.54.22" } ]
null
[]
package com.yezimm.gathering.htpp; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; /** * Created by yezimm on 2015/11/11. */ public class SocketThread extends Thread{ Socket socket = null; public SocketThread() { try { this.socket = new Socket("10.141.54.22", 20155); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { super.run(); try { System.out.println("客户端开始连接"); //一直读取控制台 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true){ //包体 byte [] content = br.readLine().getBytes(); //包头,固定4个字节,包含包体长度信息 byte [] head = Tool.intToByteArray1(content.length); BufferedOutputStream bis = new BufferedOutputStream(socket.getOutputStream()); bis.write(head); bis.flush(); bis.write(content); bis.flush(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { socket.close(); }catch (Exception e){ e.printStackTrace(); } } } public static class Tool { //int 转字节数组 public static byte[] intToByteArray1(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF); result[1] = (byte)((i >> 16) & 0xFF); result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF); return result; } public static byte[] intToByteArray2(int i) throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); out.writeInt(i); byte[] b = buf.toByteArray(); out.close(); buf.close(); return b; } //字节数组转int public static int byteArrayToInt(byte[] b) { int intValue=0; for(int i=0;i<b.length;i++){ intValue +=(b[i] & 0xFF)<<(8*(3-i)); } return intValue; } } }
2,591
0.510163
0.492228
90
26.877777
20.368727
94
false
false
0
0
0
0
0
0
0.5
false
false
7
8fca1e7c8e515efa6acfded1316cb5f5d4859b60
25,546,465,540,498
1d4374095b77edf934e15b7deef00c635825b7e6
/wronggou-pojo/src/main/java/com/wronggo/model/Specification.java
b7862ae7ed724da7d6817b6e9fcef12102dca013
[]
no_license
lifan-0974/online_retailers
https://github.com/lifan-0974/online_retailers
8ea2016e8fe1f72a32ea5fc3c158044c3ca9bedf
daa49342dd5a74fd635d6ff8628218eb12e07818
refs/heads/master
2023-02-21T12:59:18.986000
2021-01-27T09:58:36
2021-01-27T09:58:36
330,357,830
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wronggo.model; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class Specification implements Serializable { private TbSpecification specification; private List<TbSpecificationOption> specificationOptionList; }
UTF-8
Java
272
java
Specification.java
Java
[]
null
[]
package com.wronggo.model; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class Specification implements Serializable { private TbSpecification specification; private List<TbSpecificationOption> specificationOptionList; }
272
0.808824
0.808824
13
19.923077
21.003521
64
false
false
0
0
0
0
0
0
0.461538
false
false
7
1cefc9d213be83204f317b4f91349c272561c73f
5,360,119,251,928
f31422a5a267ab15f43dec129f7aa24c13e2eadd
/ClientChatQuixada/src/br/ufc/quixada/serializable/Serializable.java
24aff32e53cb07f57feacfb1e0f1061f79a3e702
[]
no_license
eleMonteiro/chat-quixada-api-client
https://github.com/eleMonteiro/chat-quixada-api-client
36baa7b5b8f0f323da2bec0240ecc349ef56da95
b618a2a4e2c89a12ef2f06a8cb3c7365c3997de5
refs/heads/master
2020-04-06T15:25:06
2018-11-21T13:43:46
2018-11-21T13:43:46
157,559,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufc.quixada.serializable; public interface Serializable { public String serialize(); public Serializable unserialize(String json); }
UTF-8
Java
152
java
Serializable.java
Java
[]
null
[]
package br.ufc.quixada.serializable; public interface Serializable { public String serialize(); public Serializable unserialize(String json); }
152
0.776316
0.776316
9
15.888889
17.741631
46
false
false
0
0
0
0
0
0
0.777778
false
false
7
c42b83fa17674178a4e3b1f106cb2ae76c20f7ba
28,853,590,298,468
9a6ea6087367965359d644665b8d244982d1b8b6
/src/main/java/X/C71943Qx.java
df61e3db2f2ea6050072fc63f09fe16c9ed48813
[]
no_license
technocode/com.wa_2.21.2
https://github.com/technocode/com.wa_2.21.2
a3dd842758ff54f207f1640531374d3da132b1d2
3c4b6f3c7bdef7c1523c06d5bd9a90b83acc80f9
refs/heads/master
2023-02-12T11:20:28.666000
2021-01-14T10:22:21
2021-01-14T10:22:21
329,578,591
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package X; import java.util.List; /* renamed from: X.3Qx reason: invalid class name and case insensitive filesystem */ public final /* synthetic */ class C71943Qx implements AbstractC63982xK { public final /* synthetic */ C71953Qy A00; public /* synthetic */ C71943Qx(C71953Qy r1) { this.A00 = r1; } @Override // X.AbstractC63982xK public final void AJt(List list) { this.A00.A00 = list; } }
UTF-8
Java
437
java
C71943Qx.java
Java
[]
null
[]
package X; import java.util.List; /* renamed from: X.3Qx reason: invalid class name and case insensitive filesystem */ public final /* synthetic */ class C71943Qx implements AbstractC63982xK { public final /* synthetic */ C71953Qy A00; public /* synthetic */ C71943Qx(C71953Qy r1) { this.A00 = r1; } @Override // X.AbstractC63982xK public final void AJt(List list) { this.A00.A00 = list; } }
437
0.659039
0.565217
17
24.705883
25.856539
85
false
false
0
0
0
0
0
0
0.294118
false
false
7
69fe2431545f04f2e5da528f4bee40ab68d5f0ca
14,963,666,062,082
0f81ab0c4e835006c8a4423923f9ec387d082323
/constructor/src/com/tyss/constructor/defautt/package-info.java
59edc89a459a1264bdd5691ae1865e20948bc50b
[]
no_license
ty-sneha-rb/core_java
https://github.com/ty-sneha-rb/core_java
4f7d1d504b4b214bf98c3242603d1f9d2650f49b
73e26ee8cd66260ed2dc0754ba08b69f12a3b032
refs/heads/main
2023-03-27T01:46:48.760000
2021-03-26T04:30:58
2021-03-26T04:30:58
351,416,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tyss.constructor.defautt;
UTF-8
Java
37
java
package-info.java
Java
[]
null
[]
package com.tyss.constructor.defautt;
37
0.864865
0.864865
1
37
0
37
false
false
0
0
0
0
0
0
1
false
false
7
28c4e681238df5f3260e16f7e884d81ec6eb6ddf
32,607,391,745,184
4ecbf5ce36a4c931efef729b2d1e9766ae5a980e
/app/src/main/java/com/example/hidarah42/yukprivat/Guru/Keahlianguru.java
84eb32466ae5622c2b59f21b0c126525abbd1f38
[]
no_license
hidarah42/Yuk-Privat
https://github.com/hidarah42/Yuk-Privat
1b5346dd985fb2621c42330007ffa57d4cea38ec
8219423e8458b767ca4e12b953a017d656c286da
refs/heads/master
2020-03-23T00:25:43.080000
2018-07-13T15:17:15
2018-07-13T15:17:15
140,862,533
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.hidarah42.yukprivat.Guru; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import com.example.hidarah42.yukprivat.Data.Data_guru; import com.example.hidarah42.yukprivat.R; 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; public class Keahlianguru extends AppCompatActivity { //variabel global private String UserID; private EditText KGKehalian1,KGWilayah1,KGHarga1,KGKehalian2,KGWilayah2,KGHarga2,KGKehalian3,KGWilayah3,KGHarga3; private FirebaseDatabase databasenya = FirebaseDatabase.getInstance(); private DatabaseReference databaserefrencenya = databasenya.getReference(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.keahlian); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //inisialisasi KGKehalian1 = (EditText)findViewById(R.id.edittextk1); KGWilayah1 = (EditText)findViewById(R.id.edittextw1); KGHarga1=(EditText)findViewById(R.id.edittexth1); KGKehalian2 = (EditText)findViewById(R.id.edittextk2); KGWilayah2 = (EditText)findViewById(R.id.edittextw2); KGHarga2=(EditText)findViewById(R.id.edittexth2); KGKehalian3 = (EditText)findViewById(R.id.edittextk3); KGWilayah3 = (EditText)findViewById(R.id.edittextw3); KGHarga3 =(EditText)findViewById(R.id.edittexth3); //membuat edittext tidak bisa diedit KGKehalian1.setFocusable(false); KGWilayah1.setFocusable(false); KGHarga1.setFocusable(false); KGKehalian2.setFocusable(false); KGWilayah2.setFocusable(false); KGHarga2.setFocusable(false); KGKehalian3.setFocusable(false); KGWilayah3.setFocusable(false); KGHarga3.setFocusable(false); //mengambil data UserID Intent i = this.getIntent(); UserID = i.getExtras().getString("UserID"); //mengambil databasenya databaserefrencenya.child("guru").child(UserID).getRef().addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Data_guru lol = dataSnapshot.getValue(Data_guru.class); KGKehalian1.setText(lol.getKeahlian_guru1()); KGWilayah1.setText(lol.getWilayah_guru1()); KGHarga1.setText(lol.getHarga_guru1()); KGKehalian2.setText(lol.getKeahlian_guru2()); KGWilayah2.setText(lol.getWilayah_guru2()); KGHarga2.setText(lol.getHarga_guru2()); KGKehalian3.setText(lol.getKeahlian_guru3()); KGWilayah3.setText(lol.getWilayah_guru3()); KGHarga3.setText(lol.getHarga_guru3()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
UTF-8
Java
3,335
java
Keahlianguru.java
Java
[ { "context": "2.yukprivat.Data.Data_guru;\nimport com.example.hidarah42.yukprivat.R;\nimport com.google.firebase.database", "end": 336, "score": 0.6593268513679504, "start": 331, "tag": "USERNAME", "value": "arah4" } ]
null
[]
package com.example.hidarah42.yukprivat.Guru; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import com.example.hidarah42.yukprivat.Data.Data_guru; import com.example.hidarah42.yukprivat.R; 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; public class Keahlianguru extends AppCompatActivity { //variabel global private String UserID; private EditText KGKehalian1,KGWilayah1,KGHarga1,KGKehalian2,KGWilayah2,KGHarga2,KGKehalian3,KGWilayah3,KGHarga3; private FirebaseDatabase databasenya = FirebaseDatabase.getInstance(); private DatabaseReference databaserefrencenya = databasenya.getReference(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.keahlian); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //inisialisasi KGKehalian1 = (EditText)findViewById(R.id.edittextk1); KGWilayah1 = (EditText)findViewById(R.id.edittextw1); KGHarga1=(EditText)findViewById(R.id.edittexth1); KGKehalian2 = (EditText)findViewById(R.id.edittextk2); KGWilayah2 = (EditText)findViewById(R.id.edittextw2); KGHarga2=(EditText)findViewById(R.id.edittexth2); KGKehalian3 = (EditText)findViewById(R.id.edittextk3); KGWilayah3 = (EditText)findViewById(R.id.edittextw3); KGHarga3 =(EditText)findViewById(R.id.edittexth3); //membuat edittext tidak bisa diedit KGKehalian1.setFocusable(false); KGWilayah1.setFocusable(false); KGHarga1.setFocusable(false); KGKehalian2.setFocusable(false); KGWilayah2.setFocusable(false); KGHarga2.setFocusable(false); KGKehalian3.setFocusable(false); KGWilayah3.setFocusable(false); KGHarga3.setFocusable(false); //mengambil data UserID Intent i = this.getIntent(); UserID = i.getExtras().getString("UserID"); //mengambil databasenya databaserefrencenya.child("guru").child(UserID).getRef().addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Data_guru lol = dataSnapshot.getValue(Data_guru.class); KGKehalian1.setText(lol.getKeahlian_guru1()); KGWilayah1.setText(lol.getWilayah_guru1()); KGHarga1.setText(lol.getHarga_guru1()); KGKehalian2.setText(lol.getKeahlian_guru2()); KGWilayah2.setText(lol.getWilayah_guru2()); KGHarga2.setText(lol.getHarga_guru2()); KGKehalian3.setText(lol.getKeahlian_guru3()); KGWilayah3.setText(lol.getWilayah_guru3()); KGHarga3.setText(lol.getHarga_guru3()); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
3,335
0.695352
0.676762
81
40.17284
25.077555
117
false
false
0
0
0
0
0
0
0.753086
false
false
7