blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
cda08c2e09f458825579355b68386e8c907631fe
|
Java
|
aistreb/itea
|
/src/test/java/page/LinkedinSuccessSubmitPasswordPage.java
|
UTF-8
| 949
| 2.03125
| 2
|
[] |
no_license
|
package page;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LinkedinSuccessSubmitPasswordPage extends LinkedinBasePage{
@FindBy(className = "flow-h1")
private WebElement infoMessage;
@FindBy(xpath = "btn-secondary-transparent")
private WebElement retearnToHomePageLink;
@FindBy(xpath = "secondary-form-action")
private WebElement addPhoneLink;
@FindBy(xpath = "secondary-form-action")
private WebElement retearnToSessionLink;
public LinkedinSuccessSubmitPasswordPage(WebDriver driver){
super(driver);
PageFactory.initElements(driver, this);
}
public boolean isLoaded() {
boolean isLoaded;
try {
isLoaded = retearnToHomePageLink.isDisplayed();
}
catch (NoSuchElementException e){
isLoaded = false;
}
return isLoaded;
}
}
| true
|
a009b1068f02a3b443590c9a3b22f0dd891ae1b0
|
Java
|
jgiles/android-tab-loader-crash
|
/src/com/colonialclub/example/crashexample/FooFragment.java
|
UTF-8
| 863
| 2.171875
| 2
|
[] |
no_license
|
package com.colonialclub.example.crashexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.util.Log;
public class FooFragment extends Fragment implements LoaderCallbacks<Foo> {
public FooFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Foo> onCreateLoader(int id, Bundle args) {
return new FooLoader(getActivity());
}
@Override
public void onLoadFinished(Loader<Foo> loader, Foo response) {
Log.d("FooFragment", "Finished loading.");
}
@Override
public void onLoaderReset(Loader<Foo> loader) {}
}
| true
|
1fb7d8686d0b88c7e434c2d802639f9360cc2efa
|
Java
|
onecipherhub/Notebox
|
/app/src/main/java/in/cipherhub/notebox/registration/ForgotPassword.java
|
UTF-8
| 3,884
| 2.078125
| 2
|
[] |
no_license
|
package in.cipherhub.notebox.registration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import in.cipherhub.notebox.R;
import in.cipherhub.notebox.utils.Internet;
public class ForgotPassword extends Fragment {
private String TAG = "ForgotPasswordOXET";
TextView back_B;
View email_V;
EditText email_ET;
Button send_B;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_forgot_password, container, false);
back_B = rootView.findViewById(R.id.back_B);
email_ET = rootView.findViewById(R.id.email_ET);
email_V = rootView.findViewById(R.id.email_V);
send_B = rootView.findViewById(R.id.send_B);
email_ET.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(!email_ET.getText().toString().equals(""))
email_V.setBackgroundColor(getResources().getColor(R.color.colorAppTheme));
else
email_V.setBackgroundColor(getResources().getColor(R.color.colorGray_777777));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
back_B.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
send_B.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String filledEmail = email_ET.getText().toString();
if (new Internet(getActivity()).isAvailable())
// have internet to use signup service
if (!TextUtils.isEmpty(filledEmail)
&& android.util.Patterns.EMAIL_ADDRESS.matcher(filledEmail).matches())
// email is valid
FirebaseAuth.getInstance().sendPasswordResetEmail(filledEmail)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
getActivity().onBackPressed();
Log.d(TAG, "E-mail sent for password recovery");
Toast.makeText(getActivity(), "Check your email to change the password!"
, Toast.LENGTH_LONG).show();
}
}
});
else
Toast.makeText(getActivity(), "Invalid E-mail address!", Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
| true
|
c77ea5a675c74a23287cf366fd6ca40aedadb4e1
|
Java
|
PujaJyoti/DemoRepo
|
/src/main/java/com/amzn/qa/pages/LoginPage.java
|
UTF-8
| 1,441
| 2.1875
| 2
|
[] |
no_license
|
package com.amzn.qa.pages;
import java.io.IOException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.amzn.qa.base.TestBase;
public class LoginPage extends TestBase {
//Object Repository --Page Factory
@FindBy(xpath="//input[@name='ctl00$MainContent$username']")
WebElement username;
@FindBy(xpath="//input[@name='ctl00$MainContent$password']")
WebElement continuebutton;
@FindBy(xpath="//input[@type='password']")
WebElement password;
@FindBy(xpath="//input[@type='submit']")
WebElement loginbutton;
@FindBy(xpath="//label[@for='ctl00_MainContent_username']")
WebElement usernamelable;
@FindBy(xpath="//label[@for='ctl00_MainContent_password']")
WebElement passwordlabel;
// initilization of Page Object
public LoginPage(){
PageFactory.initElements(driver, this);
}
//Actions
public String validateloginpagetitle(){
return driver.getTitle();
}
public boolean validateusernamelabel(){
return usernamelable.isDisplayed();
}
public boolean validatepasswordlabel(){
return passwordlabel.isDisplayed();
}
public HomePage login(String un ,String pwd){
username.sendKeys(un);
password.sendKeys(pwd);
loginbutton.click();
return new HomePage();
}
/*public HomePage login(){
username.sendKeys(p.getProperty("username"));
password.sendKeys(p.getProperty("password"));
loginbutton.click();
return new HomePage();
}
*/
}
| true
|
0cf650e3a2a2cb014a00b62b4ef0fc46c8a9f347
|
Java
|
wang-shun/pm
|
/com.sg.sales/src/com/sg/sales/model/dataset/ContractIncomeDataSet.java
|
UTF-8
| 480
| 2.078125
| 2
|
[] |
no_license
|
package com.sg.sales.model.dataset;
import com.sg.business.model.IModelConstants;
import com.sg.sales.Sales;
import com.sg.sales.model.Income;
import com.sg.widgets.commons.dataset.MasterDetailDataSetFactory;
public class ContractIncomeDataSet extends MasterDetailDataSetFactory {
public ContractIncomeDataSet() {
super(IModelConstants.DB, Sales.C_INCOME);
}
@Override
protected String getDetailCollectionKey() {
return Income.F_CONTRACT_ID;
}
}
| true
|
259e646796ae703ed243df955fa627344eba528b
|
Java
|
apache/felix-dev
|
/inventory/src/main/java/org/apache/felix/inventory/Format.java
|
UTF-8
| 3,094
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.inventory;
/**
* Java 1.4 compatible enumeration of formats used for inventory printing.
* <p>
* {@link InventoryPrinter} services indicate supported formats listing any of
* these values in their {@link InventoryPrinter#FORMAT} service
* properties.
* <p>
* Requestors of inventory printing indicate the desired output format by
* specifying the respective constant when calling the
* {@link InventoryPrinter#print(java.io.PrintWriter, Format, boolean)} method.
* <p>
* Round-tripping is guaranteed between the {@link #toString()} and
* {@link #valueOf(String)} methods.
*/
public final class Format
{
/**
* Inventory is printed in plain text format.
*/
public static Format TEXT = new Format("TEXT");
/**
* Inventory is printed in HTML format.
* <p>
* Technically the output is expected to be an HTML fragment which is
* intended to be inserted into any block element, such as {@code <div>},
* within a HTML {@code <body>}.
*/
public static Format HTML = new Format("HTML");
/**
* Inventory is printed in JSON format.
* <p>
* The output is expected to be a valid JSON object. That is, the output
* must start with an opening curly brace (<code>{</code>) and end with a
* closing curly brace (<code>}</code>).
*/
public static Format JSON = new Format("JSON");
private final String format;
private Format(final String format)
{
this.format = format;
}
/**
* Converts the given {@code format} string into an instance of
* this class.
*
* @param format The string value to be converted into a {@code Format}.
* @return One of the defined {@code Format} constants or {@code null}.
*/
public static Format valueOf(final String format)
{
if (TEXT.format.equalsIgnoreCase(format))
{
return TEXT;
}
else if (HTML.format.equalsIgnoreCase(format))
{
return HTML;
}
else if (JSON.format.equalsIgnoreCase(format))
{
return JSON;
}
return null;
}
/**
* Returns the string value of this format.
*/
public String toString()
{
return format;
}
}
| true
|
41ce53f04573ec05757197506a47212dff4dbe1e
|
Java
|
U46591/young-minds
|
/young-minds-services/young-minds-services-impl/src/main/java/com/youngminds/services/impl/camel/LoginRoutes.java
|
UTF-8
| 1,749
| 2.359375
| 2
|
[] |
no_license
|
package com.youngminds.services.impl.camel;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.youngminds.dao.UserDao;
import com.youngminds.services.modal.User;
@Component
public class LoginRoutes extends RouteBuilder{
private static final Logger LOGGER=Logger.getLogger(LoginRoutes.class);
public static final String VALIDATE_USER_ROUTE = "direct:validateUserRoute";
public static final String REGISTER_USER_ROUTE = "direct:registerUserRoute";
@Autowired
private UserDao userDao;
public LoginRoutes() {
LOGGER.debug("Login Route invoked ************** ");
}
@Override
public void configure() throws Exception {
from(VALIDATE_USER_ROUTE)
.routeId(VALIDATE_USER_ROUTE)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
User isUserExists = userDao.validateUser(exchange.getIn().getBody(User.class));
exchange.getIn().setBody(isUserExists);
}
})
.end();
from(REGISTER_USER_ROUTE)
.routeId(REGISTER_USER_ROUTE)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
// TODO Auto-generated method stub
LOGGER.debug("login route executed **********************");
String data="{\"message\":\" 'registered user details "+exchange.getIn().getBody(User.class);
userDao.inserUser(exchange.getIn().getBody(User.class));
//exchange.getIn().setBody(data);
}
})
.end();
}
}
| true
|
78b2f10503805c305b2b4603e89f62b8024820d8
|
Java
|
observadorxpl/Login001
|
/app/src/main/java/com/joseluis/login/ContainnerActivity.java
|
UTF-8
| 2,632
| 2.109375
| 2
|
[] |
no_license
|
package com.joseluis.login;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.joseluis.login.fragment.HomeFragment;
import com.joseluis.login.fragment.SearchFragment;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnTabSelectListener;
public class ContainnerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_containner);
BottomBar bottomBar = (BottomBar) findViewById(R.id.bottombar);
bottomBar.setDefaultTab(R.id.home);
BottomBarTab tab01 = bottomBar.getTabWithId(R.id.search);
BottomBarTab tab02 = bottomBar.getTabWithId(R.id.home);
BottomBarTab tab03 = bottomBar.getTabWithId(R.id.reports);
int nivel = getIntent().getIntExtra("nivel", 0);
if(nivel == 2){
tab03.setVisibility(View.INVISIBLE);
}else if(nivel == 3){
tab02.setVisibility(View.INVISIBLE);
tab03.setVisibility(View.INVISIBLE);
}
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelected(int tabId) {
switch (tabId){
case R.id.search:
SearchFragment searchFragment = new SearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, searchFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
break;
case R.id.home:
HomeFragment homeFragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, homeFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
break;
case R.id.reports:
SearchFragment profileFragment = new SearchFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, profileFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
break;
}
}
});
}
}
| true
|
1e394c0b2f91684463714494dcc0206694116f57
|
Java
|
zhaodayan/jubilant-octo-telegram
|
/src/main/java/cn/mazu/widget/HtmlTemplate.java
|
UTF-8
| 4,551
| 2.03125
| 2
|
[] |
no_license
|
package cn.mazu.widget;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.mazu.WApplication;
import cn.mazu.annotation.Bus;
import cn.mazu.util.Util.MainMenu;
import cn.mazu.utils.WString;
import cn.mazu.webkit.html.WCssStyleSheet;
import cn.mazu.webkit.html.WCssTextRule;
import cn.mazu.webkit.servlet.WebSession;
import cn.mazu.widget.kit.web.interact.Template;
public class HtmlTemplate extends Template {
static public Logger logger = LoggerFactory.getLogger(HtmlTemplate.class);
public String id_=UUID.randomUUID().toString();
private Map<String, Widget> modules_=null;
private List args_;
private Class[] parameterTypes = new Class[1];
public HtmlTemplate(){
// System.out.println("usedcMap.getClass in ht:"+usedcMap.toString());
}
public String getId(){
return id_;
}
/**
* Add the system module
* @param clsName
* @param template
*/
public void addModule(String clsName, Template template){
}
public Widget draw(Template parent, String ...args){
return this;
}
@Override
public void resolveString(String varName, List<WString> args, Writer result)
throws IOException {
parameterTypes = args.size()>0 ? new Class[2] : new Class[1];
if (args_ == null) {
args_ = new ArrayList<Object>();
} else {
args_.clear();
}
args_.add(this);
parameterTypes[0] = Template.class;
if (args.size() > 0) {
parameterTypes[1] = Array.newInstance(String.class, 0).getClass();
int i = 0;
Object ss = Array.newInstance(String.class, args.size());
while (i < args.size()) {
((String[])ss)[i]=args.get(i).getValue();
i++;
}
args_.add(ss);
}
if (varName.equals("base.path")) {
String basePath = tr("base.path").getValue();
result.append(basePath);
} else
super.resolveString(varName, args, result);
}
/**
* Decomposition of HTML, according to the variable name to generate the corresponding component
* @see cn.mazu.widget.kit.web.interact.Template#resolveWidget(java.lang.String)
* @param varName
* Naming rules: class_methodname
*/
@Override
public Widget resolveWidget(String varName) {
try {
String[] arr = varName.split("_");
if((arr.length>=1)&&(varName.contains("cn.mazu")||varName.contains("com.alipay"))){
Class<?> cls = Class.forName(arr[0]);//Class.forName("cn.mazu.factory."+arr[0]);
Method method = cls.getMethod(arr[1],(Class[]) parameterTypes);
Object clso = cls.newInstance();
ArrayList<String> params = new ArrayList<String>();
for(Method m : cls.getMethods()){
Annotation[][] an = m.getParameterAnnotations();
if(an.length>0){
for(Annotation[] a : an){
for(Annotation b : a){
params.add(getUrlParam(((Bus)b).value()));
}
}
if(params.size()>0){
m.invoke(clso, params.toArray());
params.clear();
}
}
}
for(Field f : cls.getDeclaredFields()){
if(f.isAnnotationPresent(Bus.class)){
Bus b = f.getAnnotation(Bus.class);
String bus = getUrlParam(((Bus)b).value());
if(bus!=null){
f.set(clso, bus);
}
}
}
for(Object o : args_.toArray()){
String str = String.valueOf(o);
if(str.contains("id"))
id_ = str.replace("id-", "");
}
return (Widget) method.invoke(clso,args_.toArray());
}
} catch (Exception e) {
}
return super.resolveWidget(varName);
}
public String getUrlParam(String name){
return WebSession.Handler.getInstance().getRequest().getParameter(name);
}
public Widget getChildWidget(String name){
if(modules_!=null)
return modules_.get(name);
return null;
}
public void setChildWidget(String name, Widget widget){
if(modules_==null)
modules_=new HashMap<String, Widget>();
modules_.put(name, widget);
}
@Override
protected WCssTextRule addCssRule(String selector, String declarations,
String ruleName) {
WCssStyleSheet sheet = WApplication.getInstance().getStyleSheet();
if(!sheet.isDefined(ruleName))
return super.addCssRule(selector, declarations, ruleName);
else
return null;
}
public void updateUI(){
}
}
| true
|
8a4a6b8a07594552b0d5a2f2572b413394ca3d31
|
Java
|
prios90/echobot-line-and-kakao
|
/src/main/java/com/examples/bot/lineapi/controller/LineMessageHandlerExample.java
|
UTF-8
| 1,898
| 2.53125
| 3
|
[] |
no_license
|
package com.examples.bot.lineapi.controller;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.ReplyMessage;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import com.linecorp.bot.model.message.Message;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.spring.boot.annotation.EventMapping;
import com.linecorp.bot.spring.boot.annotation.LineMessageHandler;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@LineMessageHandler
public class LineMessageHandlerExample {
@Autowired
private LineMessagingClient lineMessagingClient;
@EventMapping
public void handleTextMessageEvent(MessageEvent<TextMessageContent> event) {
replyText(event.getReplyToken(), "received! > "+ event.getMessage().getText());
}
private void replyText(@NonNull String replyToken, @NonNull String message) {
if (replyToken.isEmpty()) {
throw new IllegalArgumentException("replyToken must not be empty");
}
if (message.length() > 1000) {
message = message.substring(0, 1000 - 2) + "……";
}
this.reply(replyToken, new TextMessage(message));
}
private void reply(@NonNull String replyToken, @NonNull Message message) {
reply(replyToken, Collections.singletonList(message));
}
private void reply(@NonNull String replyToken, @NonNull List<Message> messages) {
try {
BotApiResponse apiResponse = lineMessagingClient.replyMessage(new ReplyMessage(replyToken, messages)).get();
log.debug("Sent messages: {}", apiResponse);
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
| true
|
e8fac8c23f4ef11cc7d44d38408798bd0190a7d2
|
Java
|
meicz/ShoppingStore
|
/ShoppingStore/src/com/shoppingstore/app/formcommon/main/PayOkFragment.java
|
UTF-8
| 3,737
| 2.03125
| 2
|
[] |
no_license
|
package com.shoppingstore.app.formcommon.main;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.shoppingstore.app.R;
import com.shoppingstore.app.common.global.GlobalData;
import com.shoppingstore.app.formcommon.utils.FragmentEx;
import com.shoppingstore.app.formcommon.utils.FragmentManagerEx;
public class PayOkFragment extends FragmentEx {
private String mItem = ""; //单号
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.payok_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
if(bundle != null){
mItem = bundle.getString("item");
}
View vl = setLeftLayout(R.id.include1, R.layout.header_back_layout);
vl.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
popBackStack();
}
});
TextView textView_item = (TextView) getView().findViewById(R.id.textView_item);
textView_item.setText("您的订单号:" + mItem);
Button button_dd = (Button) getView().findViewById(R.id.button_dd);
button_dd.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Bundle bund = new Bundle();
bund.putString("item", mItem);
OrderDetailFragment orderDstail = new OrderDetailFragment();
orderDstail.setArguments(bund);
mFragmentManagerEx.add(true, true, orderDstail, mItem+"order.");
}
});
Button button_jxgw = (Button) getView().findViewById(R.id.button_jxgw);
button_jxgw.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
Button button_fx = (Button) getView().findViewById(R.id.button_fx);
button_fx.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
//隐藏首页页页脚导航
getActivity().findViewById(R.id.inclue_footer_menu_layout).setVisibility(View.GONE);
}
@Override
public boolean onBackPressed() {
// TODO Auto-generated method stub
return false;
}
@Override
public void addFragment(Boolean isAddStack, int fragmentLayoutId,
Fragment fragment, String nowFragmentName) {
// TODO Auto-generated method stub
}
@Override
public void popBackStack() {
// TODO Auto-generated method stub
mBackHandledInterface.popBackStack();
FragmentHome nowFragment = new FragmentHome();
mFragmentManagerEx.add(false, false, nowFragment, FragmentHome.class.getName());
}
@Override
public void onHiddenChanged(boolean hidden){
super.onHiddenChanged(hidden);
if(hidden){
//隐藏界面
getActivity().findViewById(R.id.inclue_footer_menu_layout).setVisibility(View.VISIBLE);
}
else{
//显示界面
getActivity().findViewById(R.id.inclue_footer_menu_layout).setVisibility(View.GONE);
}
}
@Override
public void loadData() {
// TODO Auto-generated method stub
Thread thread = new Thread(new Runnable()
{
@Override
public void run(){
}
});
thread.start();
}
}
| true
|
c56ddf2aeb575e708bca52e420d6190cbaab8711
|
Java
|
singa-bio/singa
|
/singa-structure/src/main/java/bio/singa/structure/algorithms/superimposition/consensus/ConsensusAlignment.java
|
UTF-8
| 19,554
| 2.453125
| 2
|
[
"MIT",
"GPL-1.0-or-later",
"GPL-3.0-only"
] |
permissive
|
package bio.singa.structure.algorithms.superimposition.consensus;
import bio.singa.core.utility.Pair;
import bio.singa.mathematics.graphs.trees.BinaryTree;
import bio.singa.mathematics.graphs.trees.BinaryTreeNode;
import bio.singa.mathematics.matrices.LabeledSymmetricMatrix;
import bio.singa.structure.algorithms.superimposition.AlignmentMethod;
import bio.singa.structure.algorithms.superimposition.SubstructureSuperimposition;
import bio.singa.structure.model.interfaces.LeafSubstructure;
import bio.singa.structure.model.oak.StructuralMotif;
import bio.singa.structure.parser.pdb.structures.StructureWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
/**
* A consensus alignment of same-sized {@link StructuralMotif}s can be used to cluster them according their geometric
* similarity in a multi-structure alignment manner as described in:
* <pre>to be published</pre>
* <b>NOTE:</b> Copies of given {@link StructuralMotif}s will be used, so original structures are not altered.
*
* @author fk
*/
public class ConsensusAlignment extends AlignmentMethod {
private static final Logger logger = LoggerFactory.getLogger(ConsensusAlignment.class);
private final List<ConsensusContainer> input;
private final List<BinaryTree<ConsensusContainer>> consensusTrees;
private final List<Double> alignmentTrace;
private final List<Integer> alignmentCounts;
private final boolean alignWithinClusters;
private final double clusterCutoff;
private double consensusScore;
private int iterationCounter;
private TreeMap<SubstructureSuperimposition, Pair<ConsensusContainer>> alignments;
private LabeledSymmetricMatrix<ConsensusContainer> distanceMatrix;
private List<BinaryTreeNode<ConsensusContainer>> leaves;
private ConsensusContainer currentConsensus;
private List<BinaryTree<ConsensusContainer>> clusters;
ConsensusAlignment(ConsensusBuilder.Builder builder) {
// convertToSpheres given input structures to data model
input = builder.structuralMotifs.stream()
.map(ConsensusAlignment::toContainer)
.collect(Collectors.toList());
logger.info("consensus alignment initialized with {} structures", input.size());
clusterCutoff = builder.clusterCutoff;
alignWithinClusters = builder.alignWithinClusters;
setAtomFilter(builder.atomFilter);
// create representation scheme if given
setRepresentationSchemeFromType(builder.representationSchemeType);
setIdealSuperimposition(builder.idealSuperimposition);
// check if all substructures are of the same size
if (input.stream()
.map(ConsensusContainer::getStructuralMotif)
.map(StructuralMotif::getAllLeafSubstructures)
.map(List::size)
.collect(Collectors.toSet()).size() != 1) {
throw new ConsensusException("all substructures must contain the same number of leaf structures to " +
"calculate a consensus alignment");
}
iterationCounter = 0;
alignmentTrace = new ArrayList<>();
alignmentCounts = new ArrayList<>();
// initialize tree storage
consensusTrees = new ArrayList<>();
// calculate initial alignments
calculateInitialAlignments();
logger.info("{} initial alignment pairs were computed, in total we have to compute {} alignments",
alignments.size(), alignments.size() * (input.size() - 1));
// create initial tree leaves
createTreeLeaves();
// start calculating the consensus alignment
calculateConsensusAlignment();
// split top level tree
splitTopLevelTree();
// align within clusters if specified
if (alignWithinClusters) {
alignWithinClusters();
}
}
/**
* Copies and converts the given {@link StructuralMotif}s to a container object that holds the consensus score.
*
* @param structuralMotif the {@link StructuralMotif}s to be converted
* @return the container object
*/
private static ConsensusContainer toContainer(StructuralMotif structuralMotif) {
// use copy of given structural motif
return new ConsensusContainer(structuralMotif.getCopy(), false);
}
public List<Double> getAlignmentTrace() {
return alignmentTrace;
}
public List<BinaryTree<ConsensusContainer>> getClusters() {
return clusters;
}
/**
* Writes the created clusters to the specified {@link Path}.
*
* @param outputPath the desired output {@link Path}
* @throws IOException If the path cannot be written to.
*/
public void writeClusters(Path outputPath) throws IOException {
logger.info("writing {} clusters to {}", clusters.size(), outputPath);
Files.createDirectories(outputPath);
for (int i = 0; i < clusters.size(); i++) {
String clusterBaseLocation = "cluster_" + (i + 1) + "/";
BinaryTree<ConsensusContainer> currentCluster = clusters.get(i);
// write consensus
if (currentCluster.getLeafNodes().size() > 1) {
StructureWriter.writeLeafSubstructures(currentCluster.getRoot().getData().getStructuralMotif().getAllLeafSubstructures(),
outputPath.resolve(clusterBaseLocation + "consensus_" + (i + 1) + ".pdb"));
}
// write leaves
for (BinaryTreeNode<ConsensusContainer> leafNode : currentCluster.getLeafNodes()) {
if (leafNode.getData().getSuperimposition() != null) {
StructureWriter.writeLeafSubstructures(leafNode.getData().getSuperimposition().getMappedFullCandidate(),
outputPath.resolve(clusterBaseLocation + leafNode.getData().toString() + ".pdb"));
} else {
StructureWriter.writeLeafSubstructures(leafNode.getData().getStructuralMotif().getAllLeafSubstructures(),
outputPath.resolve(clusterBaseLocation + leafNode.getData().toString() + ".pdb"));
}
}
}
}
/**
* Aligns all leaf nodes to the root of the tree (observations against consensus).
*/
private void alignWithinClusters() {
// skip one-trees
clusters.stream().filter(cluster -> cluster.size() > 1).forEach(cluster -> {
// reference is always the root consensus
ConsensusContainer reference = cluster.getRoot().getData();
cluster.getLeafNodes().stream().map(BinaryTreeNode::getData).forEach(consensusContainer -> {
SubstructureSuperimposition superimposition = superimpose(reference, consensusContainer);
consensusContainer.setSuperimposition(superimposition);
});
});
}
/**
* Splits the top-level tree according to the cutoff value.
*/
private void splitTopLevelTree() {
// create list where all trees are stored
clusters = new ArrayList<>();
clusters.add(getTopConsensusTree());
// start iterating over the list
ListIterator<BinaryTree<ConsensusContainer>> clustersIterator = clusters.listIterator();
while (clustersIterator.hasNext()) {
// get current node and child nodes
BinaryTreeNode<ConsensusContainer> currentNode = clustersIterator.next().getRoot();
BinaryTreeNode<ConsensusContainer> leftNode = currentNode.getLeft();
BinaryTreeNode<ConsensusContainer> rightNode = currentNode.getRight();
// try to determine distances
double leftDistance;
if (leftNode != null) {
leftDistance = leftNode.getData().getConsensusDistance();
} else {
leftDistance = 0.0;
}
double rightDistance;
if (rightNode != null) {
rightDistance = rightNode.getData().getConsensusDistance();
} else {
rightDistance = 0.0;
}
// split tree if distance exceeds cutoff value
if (leftDistance > clusterCutoff || rightDistance > clusterCutoff) {
// remove parent tree
clustersIterator.remove();
// after removing parent tree add new trees and shift pointer
clustersIterator.add(new BinaryTree<>(currentNode.getLeft()));
clustersIterator.previous();
clustersIterator.add(new BinaryTree<>(currentNode.getRight()));
clustersIterator.previous();
}
}
}
/**
* Returns the top-level tree of this consensus alignment.
*
* @return the top-level tree
*/
public BinaryTree<ConsensusContainer> getTopConsensusTree() {
return consensusTrees.get(consensusTrees.size() - 1);
}
/**
* Returns all trees that were constructed during this alignment.
*
* @return all trees that were constructed
*/
public List<BinaryTree<ConsensusContainer>> getConsensusTrees() {
return consensusTrees;
}
/**
* Starts the calculation of the consensus alignments.
*/
private void calculateConsensusAlignment() {
// iteratively reduce candidates
while (!alignments.isEmpty()) {
findAndMergeClosestPair();
}
}
/**
* Returns the consensus score of this {@link ConsensusAlignment}, i.e. the sum of all closest pairs RMSD values.
*
* @return The consensus score
*/
public double getConsensusScore() {
return consensusScore;
}
/**
* Returns the consensus score normalized by number of iterations and the size of the input structures:
*
* @return The normalized consensus score.
*/
public double getNormalizedConsensusScore() {
return consensusScore / (iterationCounter * input.get(0).getStructuralMotif().size());
}
/**
* Finds and merges the closest pair of all input structures and recomputes the alignment.
*/
private void findAndMergeClosestPair() {
iterationCounter++;
Pair<ConsensusContainer> closestPair = alignments.firstEntry().getValue();
SubstructureSuperimposition closestPairSuperimposition = alignments.firstKey();
double closestPairRmsd = closestPairSuperimposition.getRmsd();
alignmentTrace.add(closestPairRmsd);
alignmentCounts.add(input.size());
logger.debug("closest pair for iteration {} is {} with RMSD {}", iterationCounter, closestPair, closestPairRmsd);
// sum up closest pair RMSD
consensusScore += closestPairRmsd;
createConsensus(alignments.firstEntry());
updateAlignments(alignments.firstEntry());
}
/**
* Removes the given pair from the alignments and recomputes them.
*
* @param substructurePair the pair to be removed
*/
private void updateAlignments(Map.Entry<SubstructureSuperimposition,
Pair<ConsensusContainer>> substructurePair) {
Iterator<Map.Entry<SubstructureSuperimposition, Pair<ConsensusContainer>>> alignmentsIterator =
alignments.entrySet().iterator();
while (alignmentsIterator.hasNext()) {
Map.Entry<SubstructureSuperimposition, Pair<ConsensusContainer>> currentAlignment =
alignmentsIterator.next();
boolean referenceObservationMatches = currentAlignment.getValue().getFirst()
.equals(substructurePair.getValue().getFirst()) ||
currentAlignment.getValue().getFirst().equals(substructurePair.getValue().getSecond());
boolean candidateObservationMatches = currentAlignment.getValue().getSecond()
.equals(substructurePair.getValue().getSecond()) ||
currentAlignment.getValue().getSecond().equals(substructurePair.getValue().getFirst());
// remove alignment
if (referenceObservationMatches || candidateObservationMatches) {
alignmentsIterator.remove();
}
}
// remove from input list
input.removeIf(inputStructure -> inputStructure.equals(substructurePair.getValue().getFirst()));
input.removeIf(inputStructure -> inputStructure.equals(substructurePair.getValue().getSecond()));
// add new alignments
for (ConsensusContainer inputStructure : input) {
// calculate superimposition
SubstructureSuperimposition superimposition = superimpose(currentConsensus, inputStructure);
// store alignment
Pair<ConsensusContainer> alignmentPair = new Pair<>(currentConsensus, inputStructure);
alignments.put(superimposition, alignmentPair);
}
// add consensusObservation to itemsetObservations
input.add(currentConsensus);
}
/**
* Creates a consensus representation of a {@link Pair} of lists of {@link LeafSubstructure}s by averaging
* coordinates of each position of the list.
*
* @param substructurePair the pair to be merged
*/
private void createConsensus(Map.Entry<SubstructureSuperimposition, Pair<ConsensusContainer>> substructurePair) {
List<LeafSubstructure<?>> consensusLeaveSubstructures = determineConsensus(substructurePair);
currentConsensus = new ConsensusContainer(StructuralMotif.fromLeafSubstructures(consensusLeaveSubstructures), true);
// create tree node
BinaryTreeNode<ConsensusContainer> leftNode;
BinaryTreeNode<ConsensusContainer> rightNode;
BinaryTreeNode<ConsensusContainer> consensusNode;
// both nodes have to be leaves
if (iterationCounter == 1) {
leftNode = findLeave(substructurePair.getValue().getFirst());
rightNode = findLeave(substructurePair.getValue().getSecond());
consensusNode = new BinaryTreeNode<>(currentConsensus, leftNode, rightNode);
} else {
// try to find matching node in existing tree
leftNode = findNode(substructurePair.getValue().getFirst());
// if node not found in existing tree it has to be a leave
if (leftNode == null) {
leftNode = findLeave(substructurePair.getValue().getFirst());
}
// try to find matching node in existing trees
rightNode = findNode(substructurePair.getValue().getSecond());
// if node not found in existing tree it has to be a leave
if (rightNode == null) {
rightNode = findLeave(substructurePair.getValue().getSecond());
}
consensusNode = new BinaryTreeNode<>(currentConsensus, leftNode, rightNode);
}
// create and set consensus tree
BinaryTree<ConsensusContainer> consensusTree = new BinaryTree<>(consensusNode);
currentConsensus.setConsensusTree(consensusTree);
consensusTrees.add(consensusTree);
// calculate consensus distances (half the RMSD of the consensus alignment)
// FIXME something really strange happens here when modifying the values of the map they are not reflected to the tree
consensusTree.getRoot().getLeft().getData().addToConsensusDistance(substructurePair.getKey().getRmsd() / 2);
consensusTree.getRoot().getRight().getData().addToConsensusDistance(substructurePair.getKey().getRmsd() / 2);
// substructurePair.getValue().getFirst().addToConsensusDistance(substructurePair.getKey().getRmsd() / 2);
// substructurePair.getValue().getSecond().addToConsensusDistance(substructurePair.getKey().getRmsd() / 2);
}
/**
* Returns the leave in the alignment tree that is equal to a given {@link ConsensusContainer}.
*
* @param consensusContainer the {@link ConsensusContainer} for which a leave in the alignment tree should be found
* @return the corresponding leave
*/
private BinaryTreeNode<ConsensusContainer> findLeave(ConsensusContainer consensusContainer) {
return leaves.stream()
.filter(leave -> leave.getData().equals(consensusContainer))
.findFirst().orElseThrow(() -> new ConsensusException("failed during tree construction"));
}
/**
* Searches in all existing alignment trees to find the node containing the given list of {@link
* LeafSubstructure}s.
*
* @param consensusContainer the list of {@link LeafSubstructure}s for which a node should be found
* @return the node containing the given list of {@link LeafSubstructure}s or null if it was not found
*/
private BinaryTreeNode<ConsensusContainer> findNode(ConsensusContainer consensusContainer) {
BinaryTreeNode<ConsensusContainer> nodeForObservation = null;
for (BinaryTree<ConsensusContainer> tree : consensusTrees) {
nodeForObservation = tree.findNode(consensusContainer);
if (nodeForObservation != null) {
break;
}
}
// TODO use Optional here
return nodeForObservation;
}
/**
* Initially calculates the leaves of the alignment tree.
*/
private void createTreeLeaves() {
leaves = input.stream()
.map(BinaryTreeNode::new)
.collect(Collectors.toList());
}
/**
* Initially calculates all pairwise alignments.
*/
private void calculateInitialAlignments() {
alignments = new TreeMap<>(Comparator.comparing(SubstructureSuperimposition::getRmsd));
double[][] temporaryDistanceMatrix = new double[input.size()][input.size()];
List<ConsensusContainer> distanceMatrixLabels = new ArrayList<>();
// initially append first label
distanceMatrixLabels.add(input.get(0));
int alignmentCounter = 0;
for (int i = 0; i < input.size() - 1; i++) {
for (int j = i + 1; j < input.size(); j++) {
StructuralMotif reference = input.get(i).getStructuralMotif();
StructuralMotif candidate = input.get(j).getStructuralMotif();
// calculate superimposition
SubstructureSuperimposition superimposition = superimpose(reference, candidate);
// store alignment
Pair<ConsensusContainer> alignmentPair = new Pair<>(new ConsensusContainer(reference, false),
new ConsensusContainer(candidate, false));
alignments.put(superimposition, alignmentPair);
// store distance matrix
temporaryDistanceMatrix[i][j] = superimposition.getRmsd();
temporaryDistanceMatrix[j][i] = superimposition.getRmsd();
alignmentCounter++;
if (alignmentCounter % 1000 == 0) {
logger.info("computed {} of {} initial alignments ", alignmentCounter, input.size() *
((input.size() - 1) / 2));
}
}
// store label
distanceMatrixLabels.add(input.get(i + 1));
}
distanceMatrix = new LabeledSymmetricMatrix<>(temporaryDistanceMatrix);
distanceMatrix.setColumnLabels(distanceMatrixLabels);
}
}
| true
|
f46fdada5f27dd3b22fe3d23fec2dbf8f87326c0
|
Java
|
Shradha1824/LineComparisonPrbm
|
/LineComparisonPrbm.java
|
UTF-8
| 2,076
| 3.765625
| 4
|
[] |
no_license
|
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Double;
public class LineComparisonPrbm {
public static void main(String[] args) {
System.out.println("Welcome to Line Comparison Computation Program");
//Length calculation
Scanner scan = new Scanner(System.in);
DecimalFormat decform = new DecimalFormat("0.##");
//Variable
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
int a1,b1,a2,b2;
double length1,length2;
double Length = 0;
//input
System.out.println("Enter X1 Coordinate");
x1 = scan.nextInt();
System.out.println("Enter Y1 Coordinate");
y1 = scan.nextInt();
System.out.println("Enter X2 Coordinate");
x2 = scan.nextInt();
System.out.println("Enter Y1 Coordinate");
y2 = scan.nextInt();
System.out.println("Enter A1 Coordinate");
a1 = scan.nextInt();
System.out.println("Enter B1 Coordinate");
b1 = scan.nextInt();
System.out.println("Enter A2 Coordinate");
a2 = scan.nextInt();
System.out.println("Enter B2 Coordinate");
b2 = scan.nextInt();
length1 = Math.sqrt(Math.pow(x2-x1, 2) + (Math.pow(y2-y1, 2)));
length2 = Math.sqrt(Math.pow(a2-a1, 2) + (Math.pow(b2-b1, 2)));
//Check When Two lines are equal
if (length1 == length2)
System.out.println("Line is Equal");
else
System.out.println("Line is Not Equal");
scan.close();
Length = Math.sqrt(Math.pow(x2-x1, 2) + (Math.pow(y2-y1, 2)));
System.out.println("The Length is " + decform.format(Length));
//Compare Two Line Using Operators
System.out.println(length1 + " == " + length2 + ": " + (length1 == length2));
System.out.println(length1 + " < " + length2 + ": " + (length1 < length2));
System.out.println(length1 + " > " + length2 + ": " + (length1 > length2));
//Compare Two Lines Using equals and compareTo methods
Double obj1 = length1;
Double obj2 = length2;
System.out.println("obj1 and obj2 equal? " + obj1.equals(obj2));
System.out.println(obj1.compareTo(obj2));//0-equal,1-length1>length2,-1-length2>length1;
}
}
| true
|
a90430495b50ab620825996bd1d948dd7ad99cc2
|
Java
|
c-ing/springboot_items
|
/springboot_demo/src/main/java/com/spring/demo/easyExcel/ZipUtil.java
|
UTF-8
| 10,804
| 2.421875
| 2
|
[] |
no_license
|
package com.spring.demo.easyExcel;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.spring.demo.pojo.CustomerRowWriteHandler;
import com.spring.demo.pojo.MonthSheetWriteHandler;
import com.spring.demo.pojo.PilebodycheckMonthDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Auther: cdc
* @Date: 2020/9/25 15:59
* @Description:
*/
@Slf4j
public class ZipUtil {
// 获取当前系统的临时目录
private static final String FilePath = System.getProperty("java.io.tmpdir") + File.separator;
public void execute(HttpServletResponse response) {
System.out.println("===================");
System.out.println(FilePath);
// 用于存放文件路径
List<String> filePaths = new ArrayList<>();
//生成的ZIP文件名为Demo.zip
String tmpFileName = "Demo.zip";
// zip文件路径
String strZipPath = FilePath + tmpFileName;
filePaths.add(strZipPath);
try {
//创建zip输出流
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
//声明文件集合用于存放excel文件
List<File> fileList = new ArrayList<File>();
//生成excel文件集合
for (int i = 0; i < 10; i++) {
// 生成随机文件名
String filename = FilePath + generateRandomFilename() + ".xlsx";
// 将文件路径保存
fileList.add(creatFile(filename));
filePaths.add(filename);
List<PilebodycheckMonthDto> list = new ArrayList<>();
for (int j = 0; j < 3; j++) {
// 造一些表格数据,一般是从数据库查出来的list集合数据
PilebodycheckMonthDto dataOne = new PilebodycheckMonthDto();
if (j == 0) {
dataOne.setOrderNum("至上月末");
} else if (j == 1) {
dataOne.setOrderNum("本月合计");
} else {
dataOne.setOrderNum("本年累计");
}
//。。。
list.add(dataOne);
}
// 使用easyexcel生成excel文件
writeExcel(fileList.get(i), PilebodycheckMonthDto.class, list,ExcelTypeEnum.XLS);
}
byte[] buffer = new byte[1024];
//将excel文件放入zip压缩包
for (int i = 0; i < fileList.size(); i++) {
File file = fileList.get(i);
FileInputStream fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.getName()));
//设置压缩文件内的字符编码,不然会变成乱码
//out.setEncoding("GBK");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
//下载zip文件
this.downFile(response, tmpFileName,filePaths);
} catch (Exception e) {
// 下载失败删除生成的文件
deleteFile(filePaths);
log.error("文件下载出错", e);
}
}
/**
* 文件下载
* @param response
* @param str
* @param filePaths
*/
private void downFile(HttpServletResponse response, String str, List<String> filePaths) {
try {
String path = FilePath + str;
File file = new File(path);
if (file.exists()) {
InputStream ins = new FileInputStream(path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
OutputStream outs = response.getOutputStream();// 获取文件输出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 设置response内容的类型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(str, "UTF-8"));// 设置头部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 这里一定要调用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
deleteFile(filePaths);
}
} catch (IOException e) {
deleteFile(filePaths);
log.error("文件下载出错", e);
}
}
//创建文件File对象
private File creatFile(String filePath) {
File file = new File(filePath);
return file;
}
//生成随机文件名
public String generateRandomFilename() {
String RandomFilename = "";
Random rand = new Random();//生成随机数
int random = rand.nextInt();
Calendar calCurrent = Calendar.getInstance();
int intDay = calCurrent.get(Calendar.DATE);
int intMonth = calCurrent.get(Calendar.MONTH) + 1;
int intYear = calCurrent.get(Calendar.YEAR);
String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
String.valueOf(intDay) + "_";
RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);
return RandomFilename;
}
//删除文件
public static boolean deleteFile(List<String> filePath){
boolean result = false;
for (String pathname:filePath){
File file = new File(pathname);
if (file.exists()) {
file.delete();
result = true;
}
}
return result;
}
/**
* @Title: writeExcel
* @Description: 写入excel文件到输出流web端
*
*/
private void writeExcel(OutputStream outputStream, Class<?> clazz, List<?> datalist, ExcelTypeEnum excelType, String sheetName) throws IOException {
EasyExcel.write(outputStream, clazz).excelType(excelType).sheet(sheetName==null ? "sheet1":sheetName).doWrite(datalist);
outputStream.flush();
}
/**
* @Title: writeExcel
* @Description: 写入excel到本地路径
*/
private void writeExcel(File newFile, Class<?> clazz, List<?> datalist, ExcelTypeEnum excelType) {
//内容样式策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置 自动换行
contentWriteCellStyle.setWrapped(true);
// 字体策略
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 11);
contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)11);
headWriteCellStyle.setWriteFont(headWriteFont);
ExcelWriter excelWriter = null;
try{
MonthSheetWriteHandler monthSheetWriteHandler = new MonthSheetWriteHandler();
monthSheetWriteHandler.setSupplierName("xx供应商");
monthSheetWriteHandler.setCityCompanyName("xx分公司");
excelWriter = EasyExcel.write(newFile, clazz)
//设置输出excel版本,不设置默认为xlsx
.excelType(ExcelTypeEnum.XLS).head(PilebodycheckMonthDto.class)
//设置拦截器或自定义样式
.registerWriteHandler(monthSheetWriteHandler)
.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle))
.registerWriteHandler(new CustomerRowWriteHandler())
// .sheet("存量建筑垃圾堆体治理进度月报表")
//设置默认样式及写入头信息开始的行数
.useDefaultStyle(true).relativeHeadRowIndex(10)
//这里的addsumColomn方法是个添加合计的方法,可删除
.build();
WriteSheet writeSheet = EasyExcel.writerSheet("存量建筑垃圾堆体治理进度月报表").build();
excelWriter.write(datalist, writeSheet);
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
// EasyExcel.write(newFile, clazz).excelType(excelType).sheet("sheet1").doWrite(datalist);
}
/**
* @Title: readExcel
* @Description: 读取excel内容(从输入流)
*/
private List<?> readExcel(InputStream inputStream, Class<?> clazz, ReadListener<?> listener) {
List<?> list = null;
list = EasyExcel.read(inputStream, clazz, listener).sheet().doReadSync();
return list;
};
}
| true
|
e81857a8b0c3e9a144884f3da8f0fd5f8f0163a7
|
Java
|
LingForCC/CodingDojo-FeatureToggle
|
/src/main/java/Calculator.java
|
UTF-8
| 405
| 3.59375
| 4
|
[] |
no_license
|
public class Calculator {
public int calculate(String operation, int i, int j) {
if(operation.equals("add")) {
return i + j;
}
if(operation.equals("substract")) {
return i - j;
}
if(operation.equals("multiply")) {
return i * j;
}
throw new RuntimeException("Unsupported Operation" + operation);
}
}
| true
|
c65fbbd313471704bde0260ee0373a2baeb14e5e
|
Java
|
15915763299/AndroidFoundation
|
/3-Thread/app/src/main/java/com/demo/thread/thread/ActEmpty.java
|
UTF-8
| 1,605
| 2.5625
| 3
|
[] |
no_license
|
package com.demo.thread.thread;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.demo.thread.R;
/**
* @author 尉迟涛
* create time : 2020/3/12 11:36
* description : Android Profiler 工具使用测试,检测内存泄漏,制造一个空Activity
*/
public class ActEmpty extends AppCompatActivity {
/**
* 对比有无static的情况
*
* 首先,反复打开关闭页面5次,然后收到GC(点击Profile MEMORY左上角的垃圾桶图标,
* 快速点三下,只点一下你会发现还有很多系统参数引用这Activity,甚至有WeakReference,说明还没被回收),
* 如果此时total内存还没有恢复到之前的数值,则可能发生了内存泄露。
* 此时,再点击Profile MEMORY左上角的垃圾桶图标旁的heap dump按钮查看当前的内存堆栈情况,
* 选择按包名查找,如果退出了当前Activity,但是Activity还存在,则表明发生了内存泄露。
*/
private /*static*/ class LeakHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
private LeakHandler leakHandler;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_empty);
leakHandler = new LeakHandler();
leakHandler.postDelayed(() -> {
}, 30_000);
}
}
| true
|
b7e5880ea0d99de56b52a35582bb167646b356f4
|
Java
|
tihonov-e/JAVA_Stepik
|
/JavaBaseTasks/Unsorted/Test2_Sokobano/Sokobano/src/gdi1sokoban/graphic/base/TextureDescriptor.java
|
UTF-8
| 926
| 2.703125
| 3
|
[] |
no_license
|
package gdi1sokoban.graphic.base;
import java.awt.image.BufferedImage;
import java.io.IOException;
import gdi1sokoban.base.ResourceDescriptor;
public class TextureDescriptor extends ResourceDescriptor<Texture> {
BufferedImage _image = null;
private String _name = null;
private int _minFilter;
private int _magFilter;
public TextureDescriptor(String filename, int minFilter, int magFilter) {
_name = filename;
_minFilter = minFilter;
_magFilter = magFilter;
}
public TextureDescriptor(String name, BufferedImage image, int minFilter, int magFilter) {
_name = name;
_image = image;
_minFilter = minFilter;
_magFilter = magFilter;
}
@Override
public Texture build() throws IOException {
if (_image == null) return TextureLoader.load(_name, _minFilter, _magFilter);
else return TextureLoader.load(_image, _minFilter, _magFilter);
}
@Override
public String getId() {
return _name;
}
}
| true
|
6907962c15c2304114c7a0b2927131f642cff721
|
Java
|
MuratKaragozgil/netmera4j
|
/src/main/java/com/github/muratkaragozgil/netmera4j/request/device/RemoveTagFromUsersRequest.java
|
UTF-8
| 418
| 1.671875
| 2
|
[
"MIT"
] |
permissive
|
package com.github.muratkaragozgil.netmera4j.request.device;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import com.github.muratkaragozgil.netmera4j.util.NotEmpty;
import java.util.List;
/**
* @author Murat Karagözgil
*/
@Getter
@ToString
@AllArgsConstructor
public class RemoveTagFromUsersRequest {
@NotEmpty
private String tag;
@NotEmpty
private List<String> extIds;
}
| true
|
f84a964f838441c11be44a680c9083c0412ae635
|
Java
|
butterfly0503/ChiBox
|
/app/src/main/java/com/chibox/wellness/SplashActivity.java
|
UTF-8
| 6,073
| 1.71875
| 2
|
[] |
no_license
|
package com.chibox.wellness;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.chibox.wellness.activity.MainActivity;
import com.chibox.wellness.receiver.ScreenOffAdminReceiver;
public class SplashActivity extends AppCompatActivity {
private boolean fromBoot;
private TextView tvWelcome;
int OVERLAY_REQUEST_CODE = 101, PERMISSION_REQUEST_CODE = 102, RESULT_ENABLE = 103;
String[] PERMISSIONS = {
Manifest.permission.RECEIVE_BOOT_COMPLETED,
Manifest.permission.WAKE_LOCK,
Manifest.permission.SYSTEM_ALERT_WINDOW,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECEIVE_BOOT_COMPLETED,
Manifest.permission.VIBRATE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.DISABLE_KEYGUARD,
};
DevicePolicyManager deviceManger;
ComponentName compName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
tvWelcome = findViewById(R.id.tvWelcome);
Intent intent = getIntent();
String from = intent.getStringExtra("From");
if (from != null && from.equals("BootReceiver")) fromBoot = true;
else fromBoot = false;
if (fromBoot) {
tvWelcome.setVisibility(View.GONE);
}
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_REQUEST_CODE);
} else {
canDrawOverlays();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST_CODE) {
canDrawOverlays();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == OVERLAY_REQUEST_CODE) {
checkDeviceAdmin();
} else if (requestCode == RESULT_ENABLE) {
goMain();
}
}
public void canDrawOverlays() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent2 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent2, OVERLAY_REQUEST_CODE);
} else {
checkDeviceAdmin();
}
} else {
checkDeviceAdmin();
}
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + this.getPackageName()));
startActivityForResult(intent2, OVERLAY_REQUEST_CODE);
} else {
}*/
}
public boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
public void checkDeviceAdmin() {
deviceManger = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
compName = new ComponentName(this, ScreenOffAdminReceiver.class);
boolean active = deviceManger.isAdminActive(compName);
if (active) {
goMain();
} else {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Please Click On Activate");
startActivityForResult(intent, RESULT_ENABLE);
}
}
public void goMain() {
/*Toast.makeText(this, "goMain", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();*/
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SplashActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
/*Toast.makeText(SplashActivity.this, "Opening Main screen", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();*/
}
}, 3000);
}
}
| true
|
a586775fcf09b729a0537ac74958a42c30a43b4f
|
Java
|
sng/geobeagle
|
/branches/andpet/GeoBeagle/src/com/google/code/geobeagle/database/CachesProviderCenterThread.java
|
UTF-8
| 6,100
| 2.765625
| 3
|
[] |
no_license
|
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheListPrecomputed;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.Refresher;
import android.os.Handler;
import android.util.Log;
import java.util.AbstractList;
/** Runs the decorated ICachesProviderCenter asynchronously.
* setCenter() therefore takes an extra parameter.
*
* getCaches() and getCount() only returns pre-calculated data,
* ensuring quick execution.
*
* hasChanged() will only return true when the thread has completed calculating
* new (and differing) data.
*
* If a new center is set before the geocache list for the previous one finished
* calculating, the calculation is finished and then the latest center is used
* for a new calculation.
*/
public class CachesProviderCenterThread implements ICachesProvider, IPausable {
private final ICachesProviderCenter mProvider;
/** Only replaced from the extra thread */
private AbstractList<Geocache> mGeocaches = GeocacheListPrecomputed.EMPTY;
private boolean mHasChanged = true;
/** The coordinates for which mGeocaches is currently valid */
private double mCalculatedLatitude;
private double mCalculatedLongitude;
/** When current calculation is done, continue with these center coordinates */
private double mNextLatitude;
private double mNextLongitude;
private boolean mIsCalculating = false;
private Thread mThread;
/** Used to execute listener notification on the main thread */
private final Handler mHandler;
private Refresher mObserver;
private class CalculationThread extends Thread {
private final double mLatitude;
private final double mLongitude;
public CalculationThread(double latitude, double longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
@Override
public void run() {
Log.d("GeoBeagle", "Thread starting to calculate");
/*
try {
sleep(2000);
} catch (InterruptedException e) {
}
Log.d("GeoBeagle", "Thread has slept for 2 sec");
*/
mProvider.setCenter(mLatitude, mLongitude);
AbstractList<Geocache> result = mProvider.getCaches();
if (result.equals(mGeocaches)) {
Log.d("GeoBeagle", "Thread finished calculating: the list didn't change");
registerResult(mLatitude, mLongitude, mGeocaches, false);
} else {
Log.d("GeoBeagle", "Thread finished calculating: the list did change");
registerResult(mLatitude, mLongitude, result, true);
}
startCalculation();
}
}
/** Called by the extra thread to atomically update the state */
private synchronized void registerResult(double latitude, double longitude,
AbstractList<Geocache> geocacheList, boolean changed) {
mCalculatedLatitude = latitude;
mCalculatedLongitude = longitude;
mGeocaches = geocacheList;
mIsCalculating = false; //Thread will die soon
mThread = null;
if (changed) {
mHasChanged = true;
mHandler.post(mObserverNotifier);
}
}
public CachesProviderCenterThread(ICachesProviderCenter provider) {
mProvider = provider;
//Create here to assure that main thread gets to execute notifications:
mHandler = new Handler();
}
/** Start an asynchronous calculation and notify a refresher when the
* list has changed (if it does change) */
public synchronized void setCenter(double latitude, double longitude,
Refresher notifyAfter) {
mNextLatitude = latitude;
mNextLongitude = longitude;
mObserver = notifyAfter;
startCalculation();
}
private synchronized void startCalculation() {
if (mIsCalculating)
return; //Will be started when current calculation finishes
if (mIsPaused)
return;
if (mCalculatedLatitude == mNextLatitude
&& mCalculatedLongitude == mNextLongitude) {
return; //No need to calculate again
}
Log.d("GeoBeagle", "startCalculation starts thread for coordinate diff latitude="+
(mNextLatitude-mCalculatedLatitude) + " longitude=" + (mNextLongitude-mCalculatedLongitude));
mIsCalculating = true;
mThread = new CalculationThread(mNextLatitude, mNextLongitude);
if (true) {
//mThread.setPriority();
mThread.start();
} else {
Log.d("GeoBeagle", "Running thread inline instead!");
mThread.run();
}
}
@Override
public AbstractList<Geocache> getCaches() {
//Don't calculate anything here -- just present previous results
return mGeocaches;
}
@Override
public int getCount() {
//Don't calculate anything here -- just present previous results
return mGeocaches.size();
}
@Override
public boolean hasChanged() {
return mHasChanged;
}
@Override
public synchronized void resetChanged() {
mHasChanged = false;
}
//Run this on the main thread
private final Runnable mObserverNotifier = new Runnable() {
@Override
public void run() {
if (mObserver != null)
mObserver.refresh();
}
};
private boolean mIsPaused = false;
public synchronized void onResume() {
mIsPaused = false;
startCalculation(); //There might be a pending update
}
public void onPause() {
synchronized (this) {
mIsPaused = true;
mObserver = null; //Don't report any pending result
}
try {
if (mThread != null)
mThread.join();
} catch (InterruptedException e) {
}
}
}
| true
|
dacf3de807d6c521d8e12e082259ec746bdc7d1b
|
Java
|
ZCW-Java6dot2/graded-students-EricRinger6
|
/src/main/java/io/zipcoder/Student.java
|
UTF-8
| 1,960
| 3.40625
| 3
|
[] |
no_license
|
package io.zipcoder;
import java.util.ArrayList;
import java.util.Arrays;
public class Student {
private String firstName = "";
private String lastName = "";
ArrayList<Double> examScores;
public Student(String firstName, String lastName, Double[] examScores){
this.firstName = firstName;
this.lastName = lastName;
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(examScores));
this.examScores = list;
}
public Student(){
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setExamScores(ArrayList<Double> examScores) {
this.examScores = examScores;
}
public ArrayList<Double> getExamScores(){
return examScores;
}
public String getExamScoresStr(ArrayList<Double> examScores) {
String[] output = {""};
int[] i = {1};
examScores.forEach((temp) -> {
output[0] = "Exam " + i[0] + " -> " + temp;
i[0]++;
});
return output[0];
}
public Integer getNumberOfExamsTaken(){
return examScores.size();
}
public void addExamScore(Double examScore){
this.examScores.add(examScore);
}
public void setExamScore(int examNumber, double newScore){
examScores.set(examNumber, newScore);
}
public Double getAverageExamScore(){
double sum = examScores.stream().mapToDouble(temp -> temp).sum();
return sum / examScores.size();
}
@Override
public String toString(){
return "Student Name: " + firstName + " " + lastName + "\nAverage Score: " +
getAverageExamScore() + "\n" + getExamScoresStr(examScores);
}
}
| true
|
c357129f8e248129c10ce1cf7273e25d21fb2a90
|
Java
|
Spirts/CodeGym_CorentinColinet
|
/task08/task0804/Solution.java
|
UTF-8
| 888
| 3.25
| 3
|
[] |
no_license
|
package fr.codegym.task.task08.task0804;
import java.util.HashMap;
import java.util.Map;
/*
Afficher une liste de clés
*/
public class Solution {
public static void main(String[] args) throws Exception {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Sim", "Sim");
map.put("Tom", "Tom");
map.put("Arbus", "Arbus");
map.put("Bébé", "Bébé");
map.put("Chat", "Chat");
map.put("Chien", "Chien");
map.put("Manger", "Manger");
map.put("Nourriture", "Nourriture");
map.put("Gevey", "Gevey");
map.put("Câlins", "Câlins");
imprimerCles(map);
}
public static void imprimerCles(Map<String, String> map) {
//écris ton code ici
for(Map.Entry<String,String> x : map.entrySet()){
System.out.println(x.getKey());
}
}
}
| true
|
df6e37767a4c42d8a95b33c94efd8346100bfed5
|
Java
|
ThomChar/IFT_287_TP4_BDJAVA
|
/TP4/src/modele/Equipes.java
|
ISO-8859-1
| 4,170
| 2.671875
| 3
|
[] |
no_license
|
package modele;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.inc;
import static com.mongodb.client.model.Updates.set;
import static com.mongodb.client.model.Sorts.ascending;
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import CentreSportif.Connexion;
public class Equipes {
private Connexion cx;
private MongoCollection<Document> equipesCollection;
/**
* Creation d'une instance.
*/
public Equipes(Connexion cx) {
this.cx = cx;
equipesCollection = cx.getDatabase().getCollection("Equipes");
}
/**
* Retourner la connexion associe.
*/
public Connexion getConnexion() {
return cx;
}
/**
* Ajout d'une nouvelle equipe non vide.
* @param nomEquipe
* @param matriculeCap
* @param nomLigue
*/
public void creer(String nomEquipe, String matriculeCap, String nomLigue) {
Equipe e = new Equipe(nomLigue, nomEquipe, matriculeCap);
// Ajout d'une ligue.
equipesCollection.insertOne(e.toDocument());
}
/**
* Vrifie si une Equipe existe.
* @param nomEquipe
* @return boolean
*/
public boolean existe(String nomEquipe){
return equipesCollection.find(eq("nomEquipe", nomEquipe)).first() != null;
}
/**
* Verifie si un participant est deja capitain d'une equipe.
* @param matricule
* @return un boolean
*/
public boolean testDejaCapitaine(String matricule) {
return equipesCollection.find(eq("matriculeCap", matricule)).first() != null;
}
/**
* Lecture d'une Equipe.
* @param nomEquipe
* @return un objet quipe
*/
public Equipe getEquipe(String nomEquipe) {
Document e = equipesCollection.find(eq("nomEquipe", nomEquipe)).first();
if (e != null) {
return new Equipe(e);
}
return null;
}
/**
* Suppression d'une equipe.
* @param nomEquipe
* @return un boolean
*/
public boolean supprimer(String nomEquipe) {
return equipesCollection.deleteOne(eq("nomEquipe", nomEquipe)).getDeletedCount() > 0;
}
/**
* Changer le capitaine de l'equipe d'une equipe
* @param nomEquipe
* @param matriculeCap
*/
public void changerCapitaine(String nomEquipe, String matriculeCap) {
equipesCollection.updateOne(eq("nomEquipe", nomEquipe), set("matriculeCap", matriculeCap));
}
/**
* ajouter un joueur dans une quipe
* @param nomEquipe
*/
public void ajouterJoueur(String nomEquipe) {
equipesCollection.updateOne(eq("nomEquipe", nomEquipe), inc("nbParticipants", 1));
}
/**
* supprimer un joueur d'une quipe
* @param nomEquipe
*/
public void supprimerJoueur(String nomEquipe) {
equipesCollection.updateOne(eq("nomEquipe", nomEquipe), inc("nbParticipants", -1));
}
/**
* ajouter un rsultat dans une quipe
* @param nomEquipe
*/
public void ajouterResultat(String nomEquipe) {
equipesCollection.updateOne(eq("nomEquipe", nomEquipe), inc("nbResultats", 1));
}
/**
* supprimer un rsultat dans une quipe
* @param nomEquipe
*/
public void supprimerResultat(String nomEquipe) {
equipesCollection.updateOne(eq("nomEquipe", nomEquipe), inc("nbResultats", -1));
}
/**
* Suppression des quipes d'une ligue.
* @param nomLigue
* @return boolean
*/
public boolean supprimerEquipesLigue(String nomLigue) {
return equipesCollection.deleteMany(eq("nomLigue", nomLigue)).getDeletedCount() > 0;
}
/**
* Lecture des equipes d'une ligue
* @throws SQLException
*/
public ArrayList<Equipe> lectureEquipesLigue(String nomLigue) {
ArrayList<Equipe> listEquipes = new ArrayList<Equipe>();
MongoCursor<Document> eqs = equipesCollection.find(eq("nomLigue", nomLigue)).iterator();
while (eqs.hasNext()) {
listEquipes.add(new Equipe(eqs.next()));
}
return listEquipes;
}
/**
* Lecture des equipes
* @throws SQLException
*/
public ArrayList<Equipe> lectureEquipes() {
ArrayList<Equipe> listEquipes = new ArrayList<Equipe>();
MongoCursor<Document> eqs = equipesCollection.find().sort(ascending("nomLigue")).iterator();
while (eqs.hasNext()) {
listEquipes.add(new Equipe(eqs.next()));
}
return listEquipes;
}
}
| true
|
9241c067ff14a05351bb4c731288a4a760cfe896
|
Java
|
threen/gitdemo
|
/src/git/demo/Demo.java
|
UTF-8
| 284
| 2.15625
| 2
|
[] |
no_license
|
package git.demo;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Firefox is OK!");
System.out.println("IE is OK!");
System.out.println("Chrome is OK!");
}
}
| true
|
e68369015dd28f912b8f9a00699bbb94e9a7d283
|
Java
|
MichaelHussey/spring-cloud-stream-binder-solace
|
/spring-cloud-stream-solace-sample/src/main/java/com/solace/spring_cloud_stream/sample/SolaceMessageReceiver.java
|
UTF-8
| 1,066
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.solace.spring_cloud_stream.sample;
/**
* Class to which the SolaceBinder will pass Messages received from VMR
*
* Annotate methods with either @StreamListener or @ServiceActivator in order to receive
* messages from the configured channels
*/
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import com.solace.spring_cloud_stream.binder.SolaceTopicSink;
@EnableBinding(ListenerDefinitionInterface.class)
public class SolaceMessageReceiver {
@StreamListener(SolaceTopicSink.INPUT)
//@ServiceActivator(inputChannel = SolaceTopicSink.INPUT)
public void testMessage(Message<?> message) {
System.out.println("Received testMessage: "+message);
}
//@StreamListener(SolaceTopicSink.INPUT)
@ServiceActivator(inputChannel = "input1")
public void testMessage1(Message<?> message) {
System.out.println("Received testMessage1: "+message);
}
}
| true
|
691e63d98fe5762a6efa82a8b8509999b6c1e096
|
Java
|
stevenbluesky/rent
|
/src/main/java/com/rent/services/RoleService.java
|
UTF-8
| 355
| 1.75
| 2
|
[] |
no_license
|
package com.rent.services;
import java.util.List;
import com.rent.entity.Role;
public interface RoleService {
void add(Role role);
void edit(Role role);
int delete(Integer id);
int delete(Integer [] id);
Role findById(Integer id);
List<Role> findAll();
List<Role> findByName(String name);
Integer getOnUseNum(Integer id);
}
| true
|
0b2e2ac9c4ef3d4dcba596e456c333be62d719bd
|
Java
|
genglefr/reactor-demo
|
/src/main/java/com/genglefr/webflux/demo/Application.java
|
UTF-8
| 915
| 2.0625
| 2
|
[] |
no_license
|
package com.genglefr.webflux.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| true
|
9e7a4646c7f8abb167c03f387452f305a9228414
|
Java
|
504865348/GreenHousePlus
|
/src/com/gh/greenhouse/controller/SystemMgrController.java
|
UTF-8
| 777
| 1.976563
| 2
|
[] |
no_license
|
package com.gh.greenhouse.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.gh.greenhouse.dao.BaseDao;
@RequestMapping("/sysmgr")
@Controller
public class SystemMgrController {
@Resource
private BaseDao baseDao;
@RequestMapping("/index")
public String index(Model model,
@RequestParam(value="ps",required=false,defaultValue="20") Integer pageSize,
@RequestParam(value="pn",required=false,defaultValue="1") Integer pageNumber){
model.addAttribute("pager", baseDao.listByPage(null, pageSize, pageNumber));
return "sysmgr/sysIndex";
}
}
| true
|
13280f4021046ab6cabb4aac02792438c850265e
|
Java
|
huqiangqaq/AgriculturalSupervision
|
/app/src/main/java/agricultural/nxt/agriculturalsupervision/Activity/ProductSoldActivity.java
|
UTF-8
| 2,407
| 1.929688
| 2
|
[] |
no_license
|
package agricultural.nxt.agriculturalsupervision.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import agricultural.nxt.agriculturalsupervision.R;
import agricultural.nxt.agriculturalsupervision.base.BaseActivity;
public class ProductSoldActivity extends BaseActivity {
// @BindView(R.id.lettoolbar)
// LetToolBar toolBar;
// @BindView(R.id.et_search)
// EditText et_search;
// @BindView(R.id.lv_result)
// RecyclerView lv_result;
// private List<SeachResult> results = new ArrayList<>();
// private ResultAdapter resultAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void initView() {
// toolBar.setTitle("产品信息查询");
// toolBar.setLeftButtonIcon(ContextCompat.getDrawable(this,R.mipmap.icon_arrow_02));
// toolBar.setLeftButtonOnClickLinster(v -> finish());
// initData();
// lv_result.setLayoutManager(new LinearLayoutManager(this));
// lv_result.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
// lv_result.setItemAnimator(new DefaultItemAnimator());
// resultAdapter = new ResultAdapter(results);
// resultAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
// lv_result.setAdapter(resultAdapter);
// lv_result.addOnItemTouchListener(new OnItemClickListener() {
// @Override
// public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
// ZToastUtils.showShort(ProductSoldActivity.this, "" + position);
// }
// });
}
private void initData() {
// results.add(new SeachResult(1, "种子", "西瓜", "江西省种子公司"));
// results.add(new SeachResult(2, "种子", "苹果", "南昌县"));
// results.add(new SeachResult(3, "种子", "菠萝", "江西省种子工程有限公司"));
// results.add(new SeachResult(3, "种子", "菠萝", "江西省种子工程有限公司"));
}
@Override
protected int getLayoutResId() {
return R.layout.activity_product_sold;
}
public static void actionStart(Context context) {
Intent intent = new Intent(context, ProductSoldActivity.class);
context.startActivity(intent);
}
}
| true
|
ecea2229a20c5deea6e29b1a179d1627ee2169ed
|
Java
|
jenkinsci/maven-hpi-plugin
|
/src/main/java/org/jenkinsci/maven/plugins/hpi/util/Utils.java
|
UTF-8
| 535
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.jenkinsci.maven.plugins.hpi.util;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Utils {
/**
* Return an unmodifiable set whose contents are the unions of all the specified sets.
*/
@SafeVarargs
public static <T> Set<T> unionOf(Set<T>... sets) {
Set<T> unionSet = new HashSet<>(sets[0]);
for (int i = 1; i < sets.length; i++) {
unionSet.addAll(sets[i]);
}
return Collections.unmodifiableSet(unionSet);
}
}
| true
|
45db1105d2f5717cd9165388545c06ec3e80645f
|
Java
|
Teg79/BBArena
|
/src/test/java/bbarena/ds/DataSourceFactoryTest.java
|
UTF-8
| 472
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package bbarena.ds;
import junit.framework.TestCase;
public class DataSourceFactoryTest extends TestCase {
DataSourceFactory dsFactory = null;
public void setUp(){
dsFactory = new DataSourceFactory();
}
public void testLocalRosterDS(){
RosterDS localRDS = dsFactory.getRosterDS("LRB5.0", true);
assertTrue(localRDS != null);
// assertTrue(localRDS.getRosterNames().size() == 2);
// assertTrue(localRDS.getRosterNames().get(0).equals("humans"));
}
}
| true
|
c9e0e8ebda493f4667d17663b648dc2201fac1c5
|
Java
|
24986810/SFTR_HRTA
|
/SFTR_HRTA/src/public/nc/itf/hr/ta/IBclbDefining.java
|
GB18030
| 4,611
| 1.945313
| 2
|
[] |
no_license
|
package nc.itf.hr.ta;
import java.util.ArrayList;
import java.util.Map;
import nc.vo.hr.comp.formulaset.FuncParser;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.tam.tongren.power.UserClassDeptVO;
import nc.vo.tam.tongren.power.UserClassTypeVO;
import nc.vo.tam.tongren.power.UserDeptVO;
import nc.vo.tbm.tbm_029.BclbHeaderVO;
import nc.vo.tbm.tbm_029.BclbItemVO;
import nc.vo.tbm.tbm_029.BclbVO;
import nc.vo.trade.pub.HYBillVO;
public interface IBclbDefining {
/**
* ݿɾһVO
*
* ڣ(2001-6-6)
* @param key String
* @return int 0ɾ1¼ãɾ
* @exception BusinessException 쳣˵
*/
public abstract void deleteBclb(BclbHeaderVO vo) throws BusinessException;
/**
* ݿвһVO
*
* ڣ(2001-6-6)
* @param bclb nc.vo.pd.pd1020.BclbVO
* @return java.lang.String VOַ
* @exception BusinessException 쳣˵
*/
public abstract String insertBclb029(BclbVO bclb) throws BusinessException;
/**
* ݿɾһVO
*
* ڣ(2001-6-6)
* @param key String
* @return int 0ûã1¼
* @exception BusinessException 쳣˵
*/
public abstract int isInUseBclb029(BclbHeaderVO vo) throws BusinessException;
public abstract BclbHeaderVO[] queryBclb029AllBclbHeader(String unitCode,
String gcbm) throws BusinessException;
//ͬϷֻsql
public abstract BclbHeaderVO[] queryBclb029AllBclbHeader(String unitCode,
String gcbm,String sql) throws BusinessException;
public abstract BclbItemVO[] queryAllBclbItemBclb029(BclbHeaderVO bhvo)
throws BusinessException;
/**
* ѯ˾еĬϰ
* @param pkCorp
* @return BclbHeaderVO
* @throws SQLException
*/
public BclbHeaderVO queryDefaultBclbHeader(String pkCorp)throws BusinessException ;
/**
* VOֵݿ⡣
*
* ڣ(2001-6-6)
* @param bclb nc.vo.pd.pd1020.BclbVO
* @exception BusinessException 쳣˵
*/
public abstract void updateBclb029(BclbVO bclb,boolean isPsncalendarClear,FuncParser fpFuncParser,int l_intRuleScale) throws BusinessException;
public abstract void updateBclb029(BclbVO bclb) throws BusinessException;
/**
* ͨVO
* @param key
* @return
* @throws BusinessException
*/
public abstract BclbHeaderVO findBclbHeaderByPrimaryKey(String key)throws BusinessException;
public abstract BclbHeaderVO findBclbHeaderByClassName(String className,String pkCorp)throws BusinessException;
/**
* ͨVO
*
* ڣ(2002-1-22)
* @return nc.vo.tbm.tbm_002.BclbVO
* @param key String
* @exception BusinessException 쳣˵
*/
public abstract BclbVO findBclbByPrimaryKey(String key)
throws BusinessException;
public Map queryBclbByCorpMap(String pkCorp) throws BusinessException;
public BclbVO[] queryBclbByCorp(String pkCorp) throws BusinessException;
public abstract void insertBclbs(BclbHeaderVO[] bclbHeaderVOs) throws BusinessException;
public boolean setRoleOrUserAtdTypeAuth(String tempid,ArrayList<UserDeptVO> list,int vflag,String pk_module,String pk_corp,int type) throws BusinessException;
public boolean setClassRoleOrUserAtdTypeAuth(String tempid,ArrayList<UserClassDeptVO> list,int vflag,String pk_module,String pk_corp,int type) throws BusinessException;
public boolean setClassRoleOrUserAtdClassTypeAuth(String tempid,ArrayList<UserClassTypeVO> list,int vflag,String pk_module,String pk_corp,int type) throws BusinessException;
public void onAuditApply(HYBillVO billvo) throws BusinessException;
public void onCancleAuditApply(HYBillVO billvo) throws BusinessException;
public void onSaveApply(HYBillVO billvo) throws BusinessException;
public void onDelApply(HYBillVO billvo) throws BusinessException;
public void getOAHoilday(UFDate date) throws BusinessException;
public void onBoAudit(ArrayList<String> listupdate) throws BusinessException;
public void onBoUnAudit(ArrayList<String> listupdate) throws BusinessException;
public void onBoOaUpload(ArrayList<String> listupdate) throws BusinessException;
public void onBoZbCommit(ArrayList<String> listupdate) throws BusinessException;
}
| true
|
c13f4c9ad071b6b919caf7f43ebc72cd26124ca7
|
Java
|
shulieTech/Takin-web
|
/takin-web-data/src/main/java/io/shulie/takin/web/data/dao/agent/AgentPluginLibSupportDAOImpl.java
|
UTF-8
| 2,630
| 2
| 2
|
[] |
no_license
|
package io.shulie.takin.web.data.dao.agent;
import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import io.shulie.takin.web.data.mapper.mysql.AgentPluginLibSupportMapper;
import io.shulie.takin.web.data.model.mysql.AgentPluginLibSupportEntity;
import io.shulie.takin.web.data.result.agent.AgentPluginLibSupportResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
* @author fanxx
* @date 2020/10/13 11:00 上午
*/
@Component
public class AgentPluginLibSupportDAOImpl implements io.shulie.takin.web.data.dao.agent.AgentPluginLibSupportDAO {
@Autowired
private AgentPluginLibSupportMapper agentPluginLibSupportMapper;
@Override
public List<AgentPluginLibSupportResult> getAgentPluginLibSupportList() {
List<AgentPluginLibSupportResult> agentPluginLibSupportResultList = Lists.newArrayList();
LambdaQueryWrapper<AgentPluginLibSupportEntity> wrapper = new LambdaQueryWrapper<>();
wrapper.select(
AgentPluginLibSupportEntity::getId,
AgentPluginLibSupportEntity::getPluginId,
AgentPluginLibSupportEntity::getLibName,
AgentPluginLibSupportEntity::getLibVersionRegexp,
AgentPluginLibSupportEntity::getIsIgnore
);
List<AgentPluginLibSupportEntity> agentPluginLibSupportEntityList = agentPluginLibSupportMapper
.selectList(wrapper);
if (CollectionUtils.isEmpty(agentPluginLibSupportEntityList)) {
return agentPluginLibSupportResultList;
}
agentPluginLibSupportResultList = agentPluginLibSupportEntityList.stream().map(
agentPluginLibSupportEntity -> {
AgentPluginLibSupportResult agentPluginLibSupportResult = new AgentPluginLibSupportResult();
agentPluginLibSupportResult.setId(agentPluginLibSupportEntity.getId());
agentPluginLibSupportResult.setPluginId(agentPluginLibSupportEntity.getPluginId());
agentPluginLibSupportResult.setLibName(agentPluginLibSupportEntity.getLibName());
agentPluginLibSupportResult.setLibVersionRegexp(agentPluginLibSupportEntity.getLibVersionRegexp());
agentPluginLibSupportResult.setIsIgnore(agentPluginLibSupportEntity.getIsIgnore());
return agentPluginLibSupportResult;
}).collect(Collectors.toList());
return agentPluginLibSupportResultList;
}
}
| true
|
305e901b73af2c35ea299262177130559a43424e
|
Java
|
harshpatil/MiscProgramsInJava
|
/src/main/array/SparseArrays.java
|
UTF-8
| 2,671
| 3.8125
| 4
|
[] |
no_license
|
package main.array;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
* There are N strings. Each string's length is no more than 20 characters. There are also Q queries.
* For each query, you are given a string, and you need to find out how many times this string occurred previously.
*
* The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.
*
* Sample Input
4
aba
baba
aba
xzxb
3
aba
xzxb
ab
Sample Output
2
1
0
*
*
* Created by HarshPatil on 1/21/17.
*/
public class SparseArrays {
public static void main(String[] args) throws Exception{
System.out.println("Enter number of Strings ::: ");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String input = bufferedReader.readLine();
int totalNumberOfStrings = Integer.parseInt(input);
List<String> inputStringList = new ArrayList<String>();
System.out.println("Enter "+ totalNumberOfStrings + " Strings");
for(int i=0; i<totalNumberOfStrings; i++){
inputStringList.add(bufferedReader.readLine());
}
System.out.println("Enter number of Strings to be seached ::: ");
String inputNumber = bufferedReader.readLine();
int totalSearchStrings = Integer.parseInt(inputNumber);
List<String> searchStringList = new ArrayList<String>();
System.out.println("Enter "+ totalSearchStrings + " search Strings");
for(int i=0; i<totalSearchStrings; i++){
searchStringList.add(bufferedReader.readLine());
}
Map<String, Integer> inputStringToCountMap = new HashMap<String, Integer>();
for(int i=0; i<totalNumberOfStrings; i++){
if(inputStringToCountMap.containsKey(inputStringList.get(i))){
int count = inputStringToCountMap.get(inputStringList.get(i));
count = count + 1;
inputStringToCountMap.put(inputStringList.get(i), count);
} else {
inputStringToCountMap.put(inputStringList.get(i), 1);
}
}
System.out.println("Result Count");
for(int i=0; i<totalSearchStrings; i++){
if(inputStringToCountMap.containsKey(searchStringList.get(i))){
System.out.println(inputStringToCountMap.get(searchStringList.get(i)));
}else{
System.out.println(0);
}
}
}
}
| true
|
1880d9624a19c4b4bb3ba128ede1515c60adffec
|
Java
|
tsundberg/publisher
|
/model/src/main/java/se/somath/publisher/parser/IncludeFileTreeParser.java
|
UTF-8
| 2,637
| 2.453125
| 2
|
[
"MIT"
] |
permissive
|
package se.somath.publisher.parser;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import se.somath.publisher.excpetion.PublishException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
public class IncludeFileTreeParser {
private String root;
private boolean onlyDirs;
public void parse(String include) {
Document document;
try {
document = parseIncludeString(include);
} catch (ParserConfigurationException e) {
throw new PublishException(e);
} catch (SAXException e) {
throw new PublishException(e);
} catch (IOException e) {
throw new PublishException(e);
}
NamedNodeMap attributes = findIncludeTag(document);
root = findRootName(attributes);
onlyDirs = findDirsOnly(attributes);
}
public String getRoot() {
return root;
}
public boolean isOnlyDirs() {
return onlyDirs;
}
private Document parseIncludeString(String include) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader reader = new StringReader(include);
InputSource source = new InputSource(reader);
return builder.parse(source);
}
private NamedNodeMap findIncludeTag(Document document) {
String tagName = "include-file-tree";
NodeList elements = document.getElementsByTagName(tagName);
int theOnlyExpectedElement = 0;
Node item = elements.item(theOnlyExpectedElement);
return item.getAttributes();
}
private String findRootName(NamedNodeMap attributes) {
String attributeName = "root";
return getNodeValue(attributes, attributeName);
}
private boolean findDirsOnly(NamedNodeMap attributes) {
String attributeName = "only-dirs";
String nodeValue = getNodeValue(attributes, attributeName);
return nodeValue.equalsIgnoreCase("true");
}
private String getNodeValue(NamedNodeMap attributes, String attributeName) {
Node item = attributes.getNamedItem(attributeName);
if (item != null) {
return item.getNodeValue();
} else {
return "";
}
}
}
| true
|
417b2a6f6d66712e03c16093ac8a57308ceba61b
|
Java
|
balao7/FireBaseTest
|
/app/src/main/java/com/ironflowers/firebasetest/ui/signin/SignInContract.java
|
UTF-8
| 693
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package com.ironflowers.firebasetest.ui.signin;
import com.ironflowers.firebasetest.BasePresenter;
import com.ironflowers.firebasetest.BaseView;
import com.ironflowers.firebasetest.ui.signin.vm.SignInViewModel;
/**
* Specifies the contract between the view and the presenter.
*/
public interface SignInContract {
interface View extends BaseView<Presenter> {
void continueIntoApp();
/**
* Binds the ViewModel on the view.
*
* @param viewModel
*/
void bind(SignInViewModel viewModel);
boolean isActive();
}
interface Presenter extends BasePresenter<View> {
void onContinueButtonClicked();
}
}
| true
|
df3cbb9f2f8f09e04e63dc9c69a801fe85b76398
|
Java
|
DanielFeb/Chat
|
/chat_server/src/main/java/team/ziz/chat/config/WebSocketConfig.java
|
UTF-8
| 1,115
| 2.109375
| 2
|
[] |
no_license
|
package team.ziz.chat.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import team.ziz.chat.controller.ChatHandler;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/minchat")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOrigins("*");
registry.addHandler(myHandler(), "/minchat/sockjs")
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOrigins("*")
.withSockJS();
}
public WebSocketHandler myHandler() {
return new ChatHandler();
}
}
| true
|
c2d114a7209c12b54a73d81185f9490e5367a72f
|
Java
|
AimarT1/Java_Master_Class
|
/InnerClassChallange/src/com/javamasteclass/Album.java
|
UTF-8
| 2,334
| 3.828125
| 4
|
[] |
no_license
|
package com.javamasteclass;
import java.util.ArrayList;
import java.util.LinkedList;
public class Album {
private String name;
private String artist;
private SongList songArrayList;
public Album(String name, String artist) {
this.name = name;
this.artist = artist;
this.songArrayList = new SongList();
}
public boolean addSong(String title, double duration){
return this.songArrayList.add(new Song(title,duration));
}
//we pass the track number we want to add to playlist and we allso pass our playlist.
public boolean addToPlayList(int trackNumber, LinkedList<Song> playList){
Song checkedSong = this.songArrayList.findSong(trackNumber);
if (checkedSong != null){
playList.add(checkedSong);
return true;
}
System.out.println("This album does not have a track " +trackNumber);
return false;
}
public boolean addToPlayList(String title,LinkedList<Song> playList){
Song checkSong = this.songArrayList.findSong(title);
if (checkSong != null){
playList.add(checkSong);
return true;
}
System.out.println("Song "+ title + " is not in the album.");
return false;
}
private class SongList{
private ArrayList<Song> songArrayList;
public SongList() {
this.songArrayList = new ArrayList<Song>();
}
public boolean add(Song song){
if (songArrayList.contains(song)){
return false;
}
this.songArrayList.add(song);
return true;
}
private Song findSong(String title){
//knowns as for each command in java.
// It goes throgh and creates a variable called checkedSong for every entry that in our array list.
for (Song checkedSong : this.songArrayList){
if (checkedSong.getTitle().equals(title)){
return checkedSong;
}
}
return null;
}
public Song findSong(int trackNumber){
int index = trackNumber -1 ;
if (index > 0 && index < songArrayList.size()){
return songArrayList.get(index);
}
return null;
}
}
}
| true
|
06fde7111b3cba21ae3cddca0d250f058ebe40e8
|
Java
|
gdmec07150709/shop-parent
|
/shop-goods-server/src/main/java/cn/wolfcode/shop/service/impl/SkuPropertyServiceImpl.java
|
UTF-8
| 1,162
| 2.03125
| 2
|
[] |
no_license
|
package cn.wolfcode.shop.service.impl;
import cn.wolfcode.shop.domain.SkuProperty;
import cn.wolfcode.shop.mapper.SkuPropertyMapper;
import cn.wolfcode.shop.service.ISkuPropertyService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class SkuPropertyServiceImpl implements ISkuPropertyService {
@Autowired
private SkuPropertyMapper propertyMapper;
@Override
public List<SkuProperty> getCatalogProperty(Long catalogId) {
return propertyMapper.getCatalogProperty(catalogId);
}
@Override
public void save(SkuProperty property) {
if (property.getId() == null) {
propertyMapper.insert(property);
} else {
propertyMapper.updateByPrimaryKey(property);
}
}
@Override
public void delete(Long id) {
propertyMapper.deleteByPrimaryKey(id);
}
@Override
public SkuProperty getById(Long skuPropertyId) {
return propertyMapper.getById(skuPropertyId);
}
}
| true
|
08c9247f6c35a2fc1ff9526cdad7d8198780e4f2
|
Java
|
quydo144/ZaloImposter
|
/app/src/main/java/com/example/appchat/TaoNhomActivity.java
|
UTF-8
| 10,805
| 1.882813
| 2
|
[] |
no_license
|
package com.example.appchat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.appchat.Adapter.Adapter_Create_Nhom;
import com.example.appchat.Adapter.OnMultiClickCheckBoxListener;
import com.example.appchat.Models.BanBe;
import com.example.appchat.Models.Message;
import com.example.appchat.Models.MessageNhom;
import com.example.appchat.Models.NguoiDung;
import com.example.appchat.Models.Room;
import com.example.appchat.Models.ThanhVien;
import com.example.appchat.Retrofit2.APIUtils;
import com.example.appchat.Retrofit2.DataClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TaoNhomActivity extends AppCompatActivity {
ImageButton btnBackNhom, btnDongYTaoNhom;
TextView tenNhom;
String idGroup = "";
SharedPreferences preferences, preferencesDanhBa;
EditText txtSDT;
String SDT;
Adapter_Create_Nhom adapter_Create_nhom;
LinearLayoutManager layoutManager;
ArrayList<NguoiDung> lstUser = new ArrayList<>();
ArrayList<NguoiDung> lstCheck = new ArrayList<>();
BanBe ban_be_info;
RecyclerView recycleDSNhom_Tao;
TextView tvCap_Nhat_Chon_Ban_Be_Vao_Nhom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tao_nhom);
ban_be_info = new BanBe();
lstUser.clear();
lstCheck.clear();
init_Data();
GetDanhSachBan();
backFragmentNhom_Click();
CheckMultiItem();
CreateGroup();
}
protected void init_Data() {
preferences = getSharedPreferences("data_dang_nhap", MODE_PRIVATE);
preferencesDanhBa = getSharedPreferences("data_danh_ba", MODE_PRIVATE);
btnBackNhom = (ImageButton) findViewById(R.id.btnBack_FragmentNhom);
btnDongYTaoNhom = (ImageButton) findViewById(R.id.btnXac_Nhan_Tao_Nhom);
tenNhom = (TextView) findViewById(R.id.txtDatTenNhom);
SDT = preferences.getString("SoDienThoai", "");
recycleDSNhom_Tao = (RecyclerView) findViewById(R.id.recycleDSNhom_Tao);
layoutManager = new LinearLayoutManager(this);
recycleDSNhom_Tao.setLayoutManager(layoutManager);
tvCap_Nhat_Chon_Ban_Be_Vao_Nhom = (TextView) findViewById(R.id.tvCap_Nhat_Chon_Ban_Be_Vao_Nhom);
}
protected void backFragmentNhom_Click() {
btnBackNhom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
protected void CheckMultiItem() {
adapter_Create_nhom.setOnMultiClickCheckBoxListener(new OnMultiClickCheckBoxListener() {
@Override
public void onItemClicked(boolean isChecked, int position) {
if (isChecked) {
lstCheck.add(lstUser.get(position));
} else {
lstCheck.remove(lstUser.get(position));
}
tvCap_Nhat_Chon_Ban_Be_Vao_Nhom.setText("Đã chọn : " + lstCheck.size());
}
@Override
public void onItemCheckBoxChecked(boolean isChecked, int position) {
if (isChecked) {
lstCheck.add(lstUser.get(position));
} else {
lstCheck.remove(lstUser.get(position));
}
tvCap_Nhat_Chon_Ban_Be_Vao_Nhom.setText("Đã chọn : " + lstCheck.size());
}
});
}
protected void ShowDanhSach() {
adapter_Create_nhom = new Adapter_Create_Nhom(TaoNhomActivity.this, lstUser, false);
recycleDSNhom_Tao.setAdapter(adapter_Create_nhom);
adapter_Create_nhom.notifyDataSetChanged();
}
protected void GetDanhSachBan() {
String json = preferencesDanhBa.getString("ListUser", "");
if (json.equals("")) {
int MaNguoiDung = preferences.getInt("MaNguoiDung", 0);
DataClient client = APIUtils.getData();
BanBe banBe = new BanBe();
banBe.setMaNguoiDung_Mot(MaNguoiDung);
Call<Message> call = client.GetListFriend(banBe);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
if (response.body().getSuccess() == 1) {
for (NguoiDung user : response.body().getDanhsach()) {
if (user.isStatus()) {
lstUser.add(user);
}
}
ShowDanhSach();
}
}
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
}
});
} else {
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<NguoiDung>>() {
}.getType();
lstUser = gson.fromJson(String.valueOf(json), type);
ShowDanhSach();
}
}
private void CreateTableChat(String id) {
DataClient client = APIUtils.getData();
Room room = new Room();
room.setId_room(id);
Call<Message> call = client.CreateTable(room);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
}
});
}
private void CreateGroup() {
btnDongYTaoNhom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (lstCheck.size() == 0) {
Toast.makeText(TaoNhomActivity.this, "Hãy chọn thành viên", Toast.LENGTH_LONG).show();
return;
} else if (lstCheck.size() == 1) {
NguoiDung nd = lstCheck.get(0);
Intent intent = new Intent(TaoNhomActivity.this, NhanTinDonActivity.class);
String sdt = nd.getSoDienThoai();
String ten = nd.getHoTen();
int id_user = nd.getMaNguoiDung();
intent.putExtra("sdt", sdt);
intent.putExtra("ten", ten);
intent.putExtra("id_user", id_user);
startActivity(intent);
} else {
DataClient client = APIUtils.getData();
ThanhVien tv = new ThanhVien();
if (tenNhom.getText().toString().equals("")) {
Toast.makeText(TaoNhomActivity.this, "Hãy nhập tên nhóm để tạo nhóm", Toast.LENGTH_LONG).show();
tenNhom.setText("");
tenNhom.requestFocus();
return;
}
tv.setTenNhom(tenNhom.getText().toString().trim());
int maNguoiDung = preferences.getInt("MaNguoiDung", 0);
tv.setTruongNhom(maNguoiDung);
Call<MessageNhom> call = client.CreateGroup(tv);
call.enqueue(new Callback<MessageNhom>() {
@Override
public void onResponse(Call<MessageNhom> call, Response<MessageNhom> response) {
if (response.isSuccessful())
if (response.body().getSuccess() == 1) {
idGroup = response.body().getMaNhom();
if (idGroup.equals("")) {
Toast.makeText(TaoNhomActivity.this, "Nhóm chưa được tạo", Toast.LENGTH_LONG).show();
return;
}
CreateTableChat(response.body().getMaNhom());
AddThanhVienToGroup(lstCheck);
Intent intent = new Intent(TaoNhomActivity.this, NhanTinNhomActivity.class);
String id_nhom = idGroup;
String ten_nhom = tenNhom.getText().toString().trim();
intent.putExtra("ten_nhom", ten_nhom);
intent.putExtra("id_nhom", id_nhom);
startActivity(intent);
}
}
@Override
public void onFailure(Call<MessageNhom> call, Throwable t) {
}
});
}
}
});
}
private void AddThanhVienToGroup(ArrayList<NguoiDung> lst) {
if (lst.size() == 0) {
Toast.makeText(TaoNhomActivity.this, "Hãy chọn thành viên", Toast.LENGTH_LONG).show();
return;
}
for (NguoiDung nd : lst) {
DataClient client = APIUtils.getData();
ThanhVien tv = new ThanhVien();
tv.setMaNhom(idGroup);
tv.setMaThanhVien(Integer.toString(nd.getMaNguoiDung()));
Call<MessageNhom> call = client.AddItemGroup(tv);
call.enqueue(new Callback<MessageNhom>() {
@Override
public void onResponse(Call<MessageNhom> call, Response<MessageNhom> response) {
if (response.isSuccessful()) {
if (response.body().getSuccess() == 0) {
Toast.makeText(TaoNhomActivity.this, "Đang có lỗi thêm thành viên", Toast.LENGTH_LONG).show();
return;
}
}
}
@Override
public void onFailure(Call<MessageNhom> call, Throwable t) {
}
});
}
}
}
| true
|
e5c94c31ff467d91d25b2c58696642977314e265
|
Java
|
carloscazelattojr/springboot-mvc-project-mudi
|
/src/main/java/br/com/carlosjunior/mudi/controller/OrderController.java
|
UTF-8
| 1,061
| 2.15625
| 2
|
[] |
no_license
|
package br.com.carlosjunior.mudi.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import br.com.carlosjunior.mudi.Dto.OrderDto;
import br.com.carlosjunior.mudi.model.Order;
import br.com.carlosjunior.mudi.repositories.OrderRepository;
@Controller
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
@GetMapping("/form")
public String formulary(OrderDto newOrder) {
return "order/form";
}
@PostMapping("/neworder")
public String newOrder(@Valid OrderDto newOrder, BindingResult result) {
if (result.hasErrors()) {
return "order/form";
}
Order order1 = newOrder.toOrder();
orderRepository.save(order1);
return"redirect:/home";
}
}
| true
|
11c7a2af824d896bc989a78812a95cd9f3e362a6
|
Java
|
HymanLiuTS/ConcurrentModelsWithJava
|
/18ThreadPoolTS2/src/MainApp.java
|
GB18030
| 1,066
| 3.453125
| 3
|
[] |
no_license
|
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainApp {
public static void main(String[] args) {
MyTask mt = new MyTask();
//ֻһScheduledExecutor̳߳
//ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
//й̶ScheduledExecutor̳߳
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
System.out.println(System.currentTimeMillis()/1000 + ":Thread ID:" + Thread.currentThread().getId());
for (int i = 0; i < 1; i++) {
//ӳִ
//service.schedule(mt, 2, TimeUnit.SECONDS);
//ʼӳ룬ȻԿʼʱΪÿ1ִһ̺߳
//service.scheduleAtFixedRate(mt, 2, 1, TimeUnit.SECONDS);
//ʼӳ룬ȻϴĽʱ䵽ĿʼʱΪ1ִ
service.scheduleWithFixedDelay(mt, 2, 1, TimeUnit.SECONDS);
}
}
}
| true
|
0d8683242f7e8a92ecb4fca68b5bbafea34bf1de
|
Java
|
mondris360/talentscity1.2
|
/src/main/java/com/talentscity/com/Config/SpringSecurityConfig.java
|
UTF-8
| 1,472
| 2.109375
| 2
|
[] |
no_license
|
package com.talentscity.com.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/dashboard/**").authenticated()
.antMatchers("/").permitAll()
.antMatchers("/h2-console/**").permitAll()
.and()
.oauth2Login()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.failureUrl("/invalidlogin")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.failureUrl("/login");
http.csrf().disable();
http.headers().frameOptions().disable();
}
// password enconder
@Bean
public PasswordEncoder getPasswordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
| true
|
8b73dc9212b0a23b76f26e0aef5abe6c4822a8fd
|
Java
|
goodGid/GreenLight
|
/greenlight/src/member/deleteInfo.java
|
UTF-8
| 1,060
| 2.21875
| 2
|
[] |
no_license
|
package member;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.sql.Connection;
import member.MemberDTO;
import member.DBConnection;
public class deleteInfo extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
request.setCharacterEncoding("UTF-8");
Connection conn = DBConnection.getConnection();
MemberDAO dao = new MemberDAO(conn);
HttpSession session = request.getSession();
MemberDTO dto = (MemberDTO)session.getAttribute("login_session");
System.out.println("ggod");
String ID = dto.getID();
dao.deleteData(ID);
System.out.println("ggod");
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('SUCCESS');");
out.println("location.href='login.html'");
out.println("</script>");
out.close();
}
}
| true
|
dd3ad2229ee04736576ed1db9f633d581a1ee7cb
|
Java
|
cabetoam/uoc-TFM
|
/services/ConfirmingRegInversor/src/main/java/com/confirming/reg/inversor/publisher/LoginPublisher.java
|
UTF-8
| 2,778
| 2.1875
| 2
|
[] |
no_license
|
package com.confirming.reg.inversor.publisher;
//import java.util.UUID;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
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.confirming.reg.inversor.config.MessagingConfig;
import com.confirming.reg.inversor.dto.LoginStatus;
import com.confirming.reg.inversor.model.InsertResult;
import com.confirming.reg.inversor.model.Login;
@RestController
@RequestMapping("/loginInsert")
public class LoginPublisher {
@Autowired
private RabbitTemplate template;
@PostMapping("/{email}")
public InsertResult loginToInsert(@RequestBody Login login, @PathVariable String email) {
//login.setOrderId(UUID.randomUUID().toString());
InsertResult insertResult = new InsertResult();
LoginStatus loginStatus = new LoginStatus();
loginStatus.setLogin(login);
loginStatus.setStatus("PROCESS");
loginStatus.setMessage("order placed succesfully in " + email);
System.out.println("email en MQ : " + email);
template.convertAndSend(MessagingConfig.EXCHANGE, MessagingConfig.ROUTINGKEY, loginStatus);
insertResult.setInsertR("Ok");
insertResult.setError("Sucess !!");
System.out.println("insertResult : " + insertResult.getInsertR());
return insertResult;
}
/* @PostMapping("/{email}")
public String loginToInsert(@RequestBody Login login, @PathVariable String email) {
//login.setOrderId(UUID.randomUUID().toString());
LoginStatus loginStatus = new LoginStatus();
loginStatus.setLogin(login);
loginStatus.setStatus("PROCESS");
loginStatus.setMessage("order placed succesfully in " + email);
template.convertAndSend(MessagingConfig.EXCHANGE, MessagingConfig.ROUTINGKEY, loginStatus);
return "Sucess !!";
}*/
/* public String loginToInsert(@RequestBody Login login, @PathVariable String email) {
//login.setOrderId(UUID.randomUUID().toString());
System.out.println("email to RabbitMq : " + email);
System.out.println("login to RabbitMq : " + login.getLogin());
LoginStatus loginStatus = new LoginStatus();
loginStatus.setLogin(login);
loginStatus.setStatus("PROCESS");
loginStatus.setMessage("order placed succesfully in " + email);
System.out.println("email to RabbitMq : " + loginStatus.getStatus());
System.out.println("login to RabbitMq : " + loginStatus.getLogin().getLogin());
template.convertAndSend(MessagingConfig.EXCHANGE, MessagingConfig.ROUTINGKEY, loginStatus);
return "Sucess !!";
} */
}
| true
|
83cf49642b89e182880e5b85872ce5c611f49e50
|
Java
|
Tech-Fearless/tech-fearless
|
/ssm-source/src/main/java/com/tech/proxy/cglib/HelloConcrete.java
|
UTF-8
| 163
| 1.71875
| 2
|
[] |
no_license
|
package com.tech.proxy.cglib;
public class HelloConcrete {
public void gotoHome() {
System.out.println("============gotoHome============");
}
}
| true
|
b57bfb27fb6f2c1c7975d0f68f15ed3e954cf615
|
Java
|
AllBinary/AllBinary-Platform
|
/allbinary_src/PreLoaderJavaLibraryM/src/main/java/org/allbinary/logic/java/number/LongUtil.java
|
UTF-8
| 867
| 2.359375
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
/*
* AllBinary Open License Version 1
* Copyright (c) 2011 AllBinary
*
* By agreeing to this license you and any business entity you represent are
* legally bound to the AllBinary Open License Version 1 legal agreement.
*
* You may obtain the AllBinary Open License Version 1 legal agreement from
* AllBinary or the root directory of AllBinary's AllBinary Platform repository.
*
* Created By: Travis Berthelot
*
*/
package org.allbinary.logic.java.number;
public class LongUtil
{
private LongUtil()
{
}
public static String fillIn(String end)
{
StringBuffer frameStringBuffer = new StringBuffer();
frameStringBuffer.append(end);
while(frameStringBuffer.length() < LongData.MAX_LONG_LENGTH)
{
frameStringBuffer.insert(0, '0');
}
return frameStringBuffer.toString();
}
}
| true
|
8e7ed934bf1ce276910557bc4b4449d1bc6640ac
|
Java
|
saifulhoque26/learningpipeline
|
/src/test/java/learningtests/itemsTest.java
|
UTF-8
| 252
| 2.125
| 2
|
[] |
no_license
|
package learningtests;
import items.*;
import org.junit.Assert;
import org.junit.Test;
public class itemsTest
{
@Test
public void test1()
{
items a = new items("jama", 5,5);
Assert.assertEquals(a.getItemCount(),5);
}
}
| true
|
593b67bd4f875a145e47452d48992f06a3535910
|
Java
|
DonkiChen/svg2vector
|
/src/main/java/com/github/DonkiChen/svg/shape/Line.java
|
UTF-8
| 997
| 2.390625
| 2
|
[] |
no_license
|
package com.github.DonkiChen.svg.shape;
import com.github.DonkiChen.svg.SvgHelper;
import com.github.DonkiChen.svg.attribute.style.Attributes;
import com.github.DonkiChen.svg.bean.Point;
import com.github.DonkiChen.svg.constant.ShapeAttribute;
import org.dom4j.Element;
public class Line extends BaseShape {
@Override
public String resolvePath(Element shape, Attributes attributes) {
double x1 = SvgHelper.getAttributeDouble(shape, ShapeAttribute.Line.X1);
double y1 = SvgHelper.getAttributeDouble(shape, ShapeAttribute.Line.Y1);
double x2 = SvgHelper.getAttributeDouble(shape, ShapeAttribute.Line.X2);
double y2 = SvgHelper.getAttributeDouble(shape, ShapeAttribute.Line.Y2);
Point startPoint = new Point(x1, y1);
Point endPoint = new Point(x2, y2);
attributes.matrixHelper.applyTransformToPoints(startPoint, endPoint);
return PathBuilder.newBuilder().moveTo(startPoint)
.lineTo(endPoint).build();
}
}
| true
|
c832884dc00dee7fb515dfae6f5d7150090b8aea
|
Java
|
CodeLaViva/MySVNRepository
|
/trunk/IdeaProjects/临时/PersonDaoImpl.java
|
UTF-8
| 450
| 2.25
| 2
|
[] |
no_license
|
package com.lhz.dao;
import com.lhz.model.Person;
import com.lhz.util.Hibernate_Util;
public class PersonDaoImpl implements PersonDao{
@Override
public void update() {
}
@Override
public void delete() {
}
@Override
public void change(Person person) {
Hibernate_Util.change(person);
}
@Override
public Person query(String username) {
return Hibernate_Util.query(username, 1);
}
}
| true
|
81fe83d2f7d092577c5ac66219451cef28640719
|
Java
|
thopvna/projects
|
/Ikariam/app/src/main/java/com/thopv/projects/ikariam/data/schema/armies/SFieldTroop.java
|
UTF-8
| 3,893
| 2.34375
| 2
|
[] |
no_license
|
package com.thopv.projects.ikariam.data.schema.armies;
import android.arch.persistence.room.Entity;
import android.support.annotation.NonNull;
/**
* Created by thopv on 11/13/2017.
*/
@Entity(primaryKeys = {"party", "unitName", "viewId"})
public class SFieldTroop {
private int party;
@NonNull private String unitName;
private int viewId;
private int amount;
private int maxAmount;
private int currentHitPoints;
private int currentMunitions;
public SFieldTroop(int party, @NonNull String unitName, int viewId, int amount, int maxAmount, int currentHitPoints, int currentMunitions) {
this.party = party;
this.unitName = unitName;
this.viewId = viewId;
this.amount = amount;
this.maxAmount = maxAmount;
this.currentHitPoints = currentHitPoints;
this.currentMunitions = currentMunitions;
}
@NonNull
public String getUnitName() {
return unitName;
}
public void setUnitName(@NonNull String unitName) {
this.unitName = unitName;
}
public int getViewId() {
return viewId;
}
public void setViewId(int viewId) {
this.viewId = viewId;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof SFieldTroop){
return getUnitName().equalsIgnoreCase(((SFieldTroop) obj).getUnitName())
&& getParty() == ((SFieldTroop) obj).getParty()
&& getViewId() == ((SFieldTroop) obj).getViewId()
;
}
return super.equals(obj);
}
public int getMaxAmount() {
return maxAmount;
}
public void setMaxAmount(int maxAmount) {
this.maxAmount = maxAmount;
}
public int getCurrentHitPoints() {
return currentHitPoints;
}
public void setCurrentHitPoints(int currentHitPoints) {
this.currentHitPoints = currentHitPoints;
}
public int getCurrentMunitions() {
return currentMunitions;
}
public void setCurrentMunitions(int currentMunitions) {
this.currentMunitions = currentMunitions;
}
public int getParty() {
return party;
}
public void setParty(int party) {
this.party = party;
}
public static class Builder {
private int party;
private String unitName;
private int viewId;
private int amount;
private int maxAmount;
private int currentHitPoints;
private int currentMunitions;
public Builder setParty(int party) {
this.party = party;
return this;
}
public Builder setUnitName(String unitName) {
this.unitName = unitName;
return this;
}
public Builder setViewId(int viewId) {
this.viewId = viewId;
return this;
}
public Builder setAmount(int amount) {
this.amount = amount;
return this;
}
public Builder setMaxAmount(int maxAmount) {
this.maxAmount = maxAmount;
return this;
}
public Builder setCurrentHitPoints(int currentHitPoints) {
this.currentHitPoints = currentHitPoints;
return this;
}
public Builder setCurrentMunitions(int currentMunitions) {
this.currentMunitions = currentMunitions;
return this;
}
public SFieldTroop build() {
return new SFieldTroop(party, unitName, viewId, amount, maxAmount, currentHitPoints, currentMunitions);
}
}
}
| true
|
1593f022530d96051dd8ef4a73ea0d11705e40db
|
Java
|
guitarcertifiedplayer/Gestionnaire-de-planning
|
/src/ja/model/entities/AbstractComposite.java
|
UTF-8
| 73
| 1.515625
| 2
|
[] |
no_license
|
package ja.model.entities;
public abstract class AbstractComposite {
}
| true
|
69db77b9c9a1ef523893dc003c984c8eb14c68d0
|
Java
|
rc-01-04/TDDpractice-group4
|
/src/main/java/domain/Member.java
|
UTF-8
| 544
| 2.703125
| 3
|
[] |
no_license
|
package domain;
import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@AllArgsConstructor
@Data
public class Member {
private String name;
private String gender;
private String cellphoneNumber;
private int age;
public Member(){
}
public void setAge(int age) {
if(age<0 || age>200)
throw new IllegalArgumentException();
else this.age = age;
}
public void addAge() {
this.age++;
}
}
| true
|
a7e64a49e16bb4403acd3d8e4a98aa1ed94ecf3d
|
Java
|
marcelogomez/TlalocSample
|
/app/src/main/java/tlaloc/mng687/tlalocsample/model/Tutorial.java
|
UTF-8
| 1,496
| 2.578125
| 3
|
[] |
no_license
|
package tlaloc.mng687.tlalocsample.model;
import java.io.Serializable;
/**
* Created by mng687 on 2/21/15.
*/
public class Tutorial implements Serializable {
private int id;
private String name;
private String description;
private int category_id;
private TutorialContent[] tutorial_contents;
private Category category;
public TutorialContent[] getTutorial_contents() {
return tutorial_contents;
}
public void setTutorial_contents(TutorialContent[] tutorial_contents) {
this.tutorial_contents = tutorial_contents;
}
public int getCategory_id() {
return category_id;
}
public void setCategory_id(int category_id) {
this.category_id = category_id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public String toString() {
return "Tutorial " + getId() + ": " + getName() + "\nCategory: " + getCategory().getName() + "\n" + getDescription();
}
}
| true
|
66f020638f76a8d6ce0186d217f045cc181dcfd2
|
Java
|
vaarvik/parkypark
|
/src/main/java/no/parkypark/repository/IParkinglotsRepository.java
|
UTF-8
| 374
| 2.21875
| 2
|
[] |
no_license
|
package no.parkypark.repository;
import no.parkypark.model.Parkinglot;
import java.util.List;
public interface IParkinglotsRepository {
List<Parkinglot> getAllParkinglots();
Parkinglot addParkinglot(Parkinglot parkinglot) throws Exception;
Parkinglot getParkinglotById(String id);
Parkinglot updateParkinglot(Parkinglot updatedLot) throws Exception;
}
| true
|
634ea8708d48f19645611d3bda529a1efdfe1608
|
Java
|
sandra99-rais/MunicipalApp
|
/src/sample/controlleur/ControllerRecette.java
|
UTF-8
| 13,492
| 2.0625
| 2
|
[] |
no_license
|
package sample.controlleur;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.time.LocalDate;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import sample.Models.Recette;
import sample.Models.login;
import sample.services.recetteServiceImpl;
import javax.swing.*;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerRecette implements Initializable {
@FXML
private Button Cancel;
@FXML
private Button supp;
@FXML
private Button ajouter;
@FXML
private TextField gainTextfield;
@FXML
private TextField depenseTextfield;
@FXML
private TextField soldeTextfield;
@FXML
private Button modifier;
@FXML
private ComboBox<String> type_operationComboBox;
@FXML
private ComboBox<String> rubriqueComboBox;
@FXML
private DatePicker dateDatePicker;
@FXML
private ComboBox<String> nomComboBox;
@FXML
private TextField idTextfield;
@FXML
private TextField search;
@FXML
private TableView<Recette> tableview;
@FXML
private TableColumn<Recette, Date> date;
@FXML
private TableColumn<Recette, String> Type_operation;
@FXML
private TableColumn<Recette, String> Rubrique;
@FXML
private TableColumn<Recette, String> Nom;
@FXML
private TableColumn<Recette, Integer> Id;
@FXML
private TableColumn<Recette, Float> Gain;
@FXML
private TableColumn<Recette,Float > Depense;
@FXML
private TableColumn<Recette, Float> Solde;
@FXML
private Label soldelabel;
@FXML
private Button viewIcon;
ObservableList<Recette> listM;
ObservableList<Recette> dataList;
int index = -1;
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst = null;PreparedStatement pst1 = null;PreparedStatement pst2 = null;
recetteServiceImpl recetteservice=new recetteServiceImpl();
login log=null;
public void login(login log){
this.log=log;
}
public void UpdateTable() {
date.setCellValueFactory(new PropertyValueFactory<Recette,Date>("Date"));
Type_operation.setCellValueFactory(new PropertyValueFactory<Recette, String>("Type_operation"));
Rubrique.setCellValueFactory(new PropertyValueFactory<Recette, String>("Rubrique"));
Nom.setCellValueFactory(new PropertyValueFactory<Recette, String>("Nom"));
Id.setCellValueFactory(new PropertyValueFactory<Recette, Integer>("Id"));
Gain.setCellValueFactory(new PropertyValueFactory<Recette, Float>("Gain"));
Depense.setCellValueFactory(new PropertyValueFactory<Recette, Float>("Depense"));
Solde.setCellValueFactory(new PropertyValueFactory<Recette,Float>("Solde"));
listM = recetteservice.getDataRecette();
tableview.setItems(listM);
}
@FXML
private void searchRecette() {
date.setCellValueFactory(new PropertyValueFactory<Recette,Date>("Date"));
Type_operation.setCellValueFactory(new PropertyValueFactory<Recette, String>("Type_operation"));
Rubrique.setCellValueFactory(new PropertyValueFactory<Recette, String>("Rubrique"));
Nom.setCellValueFactory(new PropertyValueFactory<Recette, String>("Nom"));
Id.setCellValueFactory(new PropertyValueFactory<Recette, Integer>("Id"));
Gain.setCellValueFactory(new PropertyValueFactory<Recette, Float>("Gain"));
Depense.setCellValueFactory(new PropertyValueFactory<Recette, Float>("Depense"));
Solde.setCellValueFactory(new PropertyValueFactory<Recette,Float>("Solde"));
dataList = recetteservice.getDataRecette();
tableview.setItems(listM);
FilteredList<Recette> filteredData = new FilteredList<>(dataList, b -> true);
search.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate(recette -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (new String(String.valueOf(recette.getDate())).toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true; //
}else if (recette.getType_operation().toLowerCase().contains(lowerCaseFilter)) {
return true;}
else if (recette.getRubrique().toLowerCase().contains(lowerCaseFilter)) {
return true;}
else if (recette.getNom().toLowerCase().contains(lowerCaseFilter) ) {
return true;}
else if (String.valueOf(recette.getGain()).indexOf(lowerCaseFilter) != -1 ) {
return true;}
else if (String.valueOf(recette.getDepense()).indexOf(lowerCaseFilter) != -1 ) {
return true;}
else if (String.valueOf(recette.getSolde()).indexOf(lowerCaseFilter) != -1 ) {
return true;}
else
return false; // Does not match.
});
});
SortedList<Recette> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tableview.comparatorProperty());
tableview.setItems(sortedData);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
type_operationComboBox.getItems().addAll("Décaissement", "Encaissement");
UpdateTable();
searchRecette();
combo();
soldeupdate();
}
public void CancelButtonOnAction () {
Stage stage = (Stage) Cancel.getScene().getWindow() ;
stage.close();
}
@FXML
public void addRecette() {
if (!(gainTextfield.getText().matches("[0-9.]+"))) JOptionPane.showMessageDialog(null, "Le gain est incorrect ");
else if (!(depenseTextfield.getText().matches("[0-9.]+"))) JOptionPane.showMessageDialog(null, " La dépense est incorrecte ");
else if (!(soldeTextfield.getText().matches("[0-9.]+")) ) JOptionPane.showMessageDialog(null, "Le solde est incorect ");
else if (!(idTextfield.getText().matches("[0-9]+"))) JOptionPane.showMessageDialog(null, "l'ID est incorrect");
else if (type_operationComboBox.getSelectionModel().isEmpty()) JOptionPane.showMessageDialog(null, " Veuillez selectionner un Models ");
else if (rubriqueComboBox.getSelectionModel().isEmpty()) JOptionPane.showMessageDialog(null, " Veuillez séléctionner une rubrique ");
else if (nomComboBox.getSelectionModel().isEmpty()) JOptionPane.showMessageDialog(null, " Veuillez séléctionner un nom ");
else if(dateDatePicker.getValue().isBefore(LocalDate.now()))JOptionPane.showMessageDialog(null, " La date devrait être avant la date d'aujourd'hui ");
else {
if (recetteservice.verif(Integer.parseInt(idTextfield.getText()))) {
JOptionPane.showMessageDialog(null, "La Recette existe déjà ");
} else {
Recette recette=new Recette(java.sql.Date.valueOf((dateDatePicker.getValue())), type_operationComboBox.getValue(),
rubriqueComboBox.getValue(),nomComboBox.getValue(),Integer.parseInt(idTextfield.getText()), Float.parseFloat(gainTextfield.getText()),
Float.parseFloat(depenseTextfield.getText()),Float.parseFloat(soldeTextfield.getText()) );
recetteservice.addrecette(recette);
searchRecette();
UpdateTable();
}
}
soldeupdate();
}
public void Delete() {
if(idTextfield.getText().trim().isEmpty())
JOptionPane.showMessageDialog(null, "ecrire l'id de la recette");
else if (!(recetteservice.verif(Integer.parseInt(idTextfield.getText())))) {
JOptionPane.showMessageDialog(null, "La Recette n'existe pas ");
} else{
int reply=JOptionPane.showConfirmDialog(null,"confirmer votre decision");
if(reply==JOptionPane.YES_OPTION){
recetteservice.Delete(idTextfield.getText());
UpdateTable();
searchRecette();
soldeupdate();}}
}
@FXML
public void getselected() throws SQLException {
index = tableview.getSelectionModel().getSelectedIndex();
if (index <= -1){
return;
}
ResultSet rs= recetteservice.getRecette(Id.getCellData(index));
while (rs.next()){
dateDatePicker.setValue(rs.getDate("Datee").toLocalDate());
type_operationComboBox.setValue(rs.getString("Type_operation"));
rubriqueComboBox.setValue(rs.getString("Rubrique"));
nomComboBox.setValue(rs.getString("Nom"));
idTextfield.setText(rs.getString("Id"));
gainTextfield.setText(String.valueOf(rs.getFloat("Gain")));
depenseTextfield.setText(String.valueOf(rs.getFloat("Depense")));
soldeTextfield.setText(String.valueOf((rs.getFloat("Solde"))));
}
}
public void modif(){
if (!(gainTextfield.getText().matches("[0-9.]+"))) JOptionPane.showMessageDialog(null, "Le gain est incorrect ");
else if (!(depenseTextfield.getText().matches("[0-9.]+"))) JOptionPane.showMessageDialog(null, "La dépense est incorrecte ");
else if (!(soldeTextfield.getText().matches("[0-9.]+")) ) JOptionPane.showMessageDialog(null, "Le solde est incorect ");
else if (!(idTextfield.getText().matches("[0-9]+"))) JOptionPane.showMessageDialog(null, "L'ID est incorrect");
else{
if (!(recetteservice.verif(Integer.parseInt(idTextfield.getText())))) {
JOptionPane.showMessageDialog(null, "La Recette n'existe pas ");
} else{
Recette recette=new Recette(java.sql.Date.valueOf((dateDatePicker.getValue())), type_operationComboBox.getValue(),
rubriqueComboBox.getValue(),nomComboBox.getValue(),Integer.parseInt(idTextfield.getText()), Float.parseFloat(gainTextfield.getText()),
Float.parseFloat(depenseTextfield.getText()),Float.parseFloat(soldeTextfield.getText()) );
recetteservice.modif(recette);
UpdateTable();
searchRecette();}
}
soldeupdate();
}
private void combo(){
type_operationComboBox.valueProperty().addListener((obs, oldValue, newValue) -> {
if (newValue == null) {
rubriqueComboBox.getItems().clear();
rubriqueComboBox.setDisable(true);
rubriqueComboBox.getEditor().setEditable(false);
nomComboBox.getItems().clear();
nomComboBox.setDisable(true);
} else
if(newValue == "Encaissement"){
rubriqueComboBox.getItems().clear();;
// sample code, adapt as needed:
rubriqueComboBox.getItems().addAll("Frais de services d'extrait","Frais d'organisation des événements","Location des matériels","Frais de mission des projets");
rubriqueComboBox.setDisable(false);
nomComboBox.getItems().clear();
nomComboBox.getItems().addAll("citoyen");
}
else{
rubriqueComboBox.getItems().clear();
rubriqueComboBox.getItems().addAll("Achat matériel","Achat vehicule");
rubriqueComboBox.setDisable(false);
nomComboBox.getItems().clear();
nomComboBox.getItems().addAll("fournisseur");
}
}); }
public void soldeupdate(){
ObservableList<Recette> list= recetteservice.getDataRecette();
int l= list.size();
Recette r=list.get(l-1);
soldelabel.setText("solde="+ r.getSolde());
}
@FXML
private void imprimer() throws IOException {
if(index!=-1){
Recette permission = tableview.getSelectionModel().getSelectedItem();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/sample/views/PermissionAffichers.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
AfficherPermission addPermissionController = fxmlLoader.getController();
addPermissionController.setTextField(permission.getId(),permission.getType_operation(),permission.getRubrique(), permission.getDate(),permission.getNom(),permission.getGain(),permission.getDepense(),permission.getSolde());
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(new Scene(root1));
stage.setMaximized(true);
stage.initStyle(StageStyle.UNDECORATED);
stage.showAndWait();}
else
JOptionPane.showMessageDialog(null, "choisir un recette");
}
}
| true
|
60c38d1a340ff187cc7e26b2e490331bdbe037bc
|
Java
|
shimengqiang/cv
|
/api/src/main/java/com/vector/dubbo/service/PoductDataService.java
|
UTF-8
| 814
| 2.046875
| 2
|
[] |
no_license
|
package com.vector.dubbo.service;
import com.vector.dubbo.dto.ProductDto;
import com.vector.dubbo.dto.ProductSeckillDetail;
import java.util.Date;
import java.util.List;
public interface PoductDataService {
/**
* 减库存
*
* @param seckillId
* @param killTime
* @return 插入行数
*/
int reduceNumber(long seckillId, Date killTime);
/**
* 查询秒杀对象
*
* @param seckillId
* @return Seckill
*/
ProductDto querySeckillById(long seckillId);
/**
*
* @param offset
* @param limit
* @return Seckills
*/
List<ProductDto> queryAllSeckill(int offset, int limit);
int insertSuccessKilled(Long seckillId, long userPhone);
ProductSeckillDetail querySuccessKillByIdWithSeckill(long seckillId);
}
| true
|
b4fe298cb83db83e9ffca7e943616208fb66d794
|
Java
|
ablaziz/java-programming
|
/src/day45_oops/TrafficLightObject.java
|
UTF-8
| 687
| 3.390625
| 3
|
[] |
no_license
|
package day45_oops;
public class TrafficLightObject {
public static void main(String[] args) {
// create traffic light object
TrafficLight trafficLight = new TrafficLight();
// trafficLight.color="red"; not best practice
//Preferred way = we will assign//update the value of color using a method of the class
trafficLight.changeColor("green");
//call method to access the variable
trafficLight.showColor();
trafficLight.changeColor("red");
trafficLight.showColor();
TrafficLight trafficLight2 = new TrafficLight();
trafficLight2.changeColor("red");
trafficLight2.showColor();
}
}
| true
|
057ee7b132638b2f8787576603421a71b74e1cc1
|
Java
|
Jiyoung326/SONSOO_market
|
/src/main/java/com/sonsoo/controller/MemberController.java
|
UTF-8
| 4,374
| 2.15625
| 2
|
[] |
no_license
|
package com.sonsoo.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.sonsoo.domain.MemberVO;
import com.sonsoo.domain.ProductVO;
import com.sonsoo.paging.ReviewCriteria;
import com.sonsoo.service.MemberService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
@Controller
@RequestMapping("/member/*")
@AllArgsConstructor
@Log4j
public class MemberController {
private MemberService service;
// 로그인페이지
@GetMapping("/login")
public String getLogin() {
return "/member/login";
}
// 로그인하기
// 회원정보, 상품정보, 세션, 리뷰등록정보를 매개변수로 함.
@PostMapping("/loginPost")
public String getMember(MemberVO mvo, ProductVO pvo, HttpSession session, ReviewCriteria cri) {
System.out.println("아이디 : " + mvo.getId());
System.out.println("비밀번호 : " + mvo.getPassword());
System.out.println("P_Id : " + pvo.getP_id());
System.out.println("페이지번호 : " + cri.getPageNum());
System.out.println("어마운트 : " + cri.getAmount());
MemberVO member = service.getMember(mvo);
if (member != null) {
service.insertVisitDate(mvo);
session.setAttribute("memberId", member.getId());
System.out.println("memberId : " + member.getId());
// return "redirect:/review/product?id=" + mvo.getId() + "&p_id=" +
// pvo.getP_id() + "&pageNum=" + cri.getPageNum();
return "/home";
} else {
return "/member/login";
}
}
// 로그아웃하기
@RequestMapping("/logout")
public ModelAndView logout(HttpSession session) {
session.invalidate();
ModelAndView mv = new ModelAndView("redirect:/home");
return mv;
}
// 회원가입페이지
@GetMapping("/join")
public void join() {
// return "/member/join";
}
// 아이디체크
@GetMapping("/idcheckAjax")
public @ResponseBody String idcheckAjax(MemberVO vo) {
log.info(vo);
if (service.getMemberChk(vo) != null) {
if (vo.getId().equals(service.getMemberChk(vo).getId())) {
log.info(service.getMemberChk(vo));
return "exists";
} else {
return "noExists";
}
} else {
return "noExists";
}
}
// 회원가입폼에서 값을 입력후 컨트롤러로 넘어온 파라미터를 받아서 db에 저장후 redirect로 home으로 이동.
@PostMapping("/join")
public String join(MemberVO vo) {
service.join(vo);
return "redirect:/home";
}
// 회원정보수정페이지
@GetMapping("/myinfo")
public String myinfo(MemberVO vo, Model model, ProductVO pvo, HttpSession session, ReviewCriteria cri) {
// service.myinfo(service.join(vo));
System.out.println("아이디는 : " + vo.getId());
log.info("회원정보" + service.myinfo(vo));
model.addAttribute("member", service.myinfo(vo));
System.out.println("model : " + model);
return "/member/myinfo";
}
// 회원정보수정하기
@PostMapping("/mupdate")
public String mupdate(MemberVO vo, Model model) {
log.info("mupdate의 MemberVO :"+vo);
log.info("?????"+vo.getPassword().isEmpty());
System.out.println("model>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + model);
// TODO 비밀번호 null처리 필요!!!
// if (vo.getPassword() == null || vo.getPassword().equals("")) {
// // TODO log.info("회원정보" + service.myinfo(vo));
// vo.setPassword(vo.getPassword());
// }
service.mupdate(vo);
return "redirect:/home";
}
/*
* //회원정보수정페이지
*
* @GetMapping("/mupdate") public String mupdate() {
*
* return "/mypage/mupdate";
*
* }
*/
/*
* //회원정보수정페이지
*
* @PostMapping("/myinfo") public String myinfo(HttpSession session) {
*
* service.myinfo(session); return "member/myinfo";
*
* }
*/
@GetMapping("/mdelete")
public String mdelete(MemberVO vo, HttpSession session) {
log.info(vo);
service.mdelete(vo);
session.invalidate();
log.info(vo);
return "redirect:/home";
}
}
| true
|
bd46f3366a003422657c6b273d822ea012c1e06e
|
Java
|
Hed94/Pexeso-Server
|
/src/testserver/Lobby.java
|
UTF-8
| 2,215
| 2.828125
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testserver;
import java.net.Socket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import hra.Server;
public class Lobby extends Thread
{
public List<String> nicky = Collections.synchronizedList( new ArrayList<String>());
public Prijmac prijmac1;
public Prijmac prijmac2;
public Vysilac vysilac;
public InstanceHry instance;
public boolean konec = false;
public Lobby(Socket socket1, Socket socket2) throws IOException
{
vysilac = new Vysilac(socket1,socket2,this);
prijmac1 = new Prijmac(socket1,this);
prijmac2 = new Prijmac(socket2,this);
Server.LOGGER.info("Server vytvořil lobby pro "+socket1+"a"+socket2);
}
public void run()
{
try
{
prijmac1.start();
prijmac2.start();
Server.LOGGER.info("Server vytvořil hráčům příjmače pro komunikaci.");
while(nicky.size() < 2)
{
Server.LOGGER.info("Server čeká na nicky hráčů");
Thread.sleep(2000);
}
if(prijmac1.getNick().equals(nicky.get(1)))
{
String pomocny = nicky.get(0);
String pomocny2 = nicky.get(1);
nicky.clear();
nicky.add(pomocny2);
nicky.add(pomocny);
}
Server.LOGGER.info("Server začíná vytvářet hru");
instance = new InstanceHry(nicky.get(0),nicky.get(1),this);
Thread.sleep(1000);
Server.LOGGER.info("Server začal hru a dává vědět kdo je aktuální hráč");
vysilac.PosliZpravu(instance.getAktualniHrac(),"zacatek","");
}
catch (IOException ex)
{
Server.LOGGER.error("Lobby: " + ex.toString());
} catch (InterruptedException ex) {
Server.LOGGER.error("Lobby: " + ex.toString());
}
}
}
| true
|
175233903f54a94c6394d82c3bbcb92c61c314f1
|
Java
|
rensGit-netizen/GBBC--Web
|
/src/main/java/com/gbbc/webapplication/viewmodel/Authorize.java
|
UTF-8
| 1,014
| 2.09375
| 2
|
[] |
no_license
|
package com.gbbc.webapplication.viewmodel;
/**
* @author Emily Koo
*/
public class Authorize {
private String first_name;
private String last_name;
private String user_name;
private String password;
private String iban;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
}
| true
|
dae60c439bf816071ff0ddff1202717dfe7a51bb
|
Java
|
cuiyaqiang/springboot_manage
|
/managent/src/main/java/com/guye/sun/managent/pojo/po/Role.java
|
UTF-8
| 2,543
| 2.359375
| 2
|
[] |
no_license
|
package com.guye.sun.managent.pojo.po;
import com.guye.sun.managent.pojo.RecordEntity;
import java.util.Date;
import javax.persistence.*;
@Table(name = "t_sys_role")
public class Role extends RecordEntity {
/**
* 主键
*/
@Id
private Integer id;
/**
* 角色名
*/
private String name;
/**
* 编号
*/
private String code;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
@Column(name = "gmt_create")
private Date gmtCreate;
/**
* 最后修改时间
*/
@Column(name = "gmt_modified")
private Date gmtModified;
/**
* 获取主键
*
* @return id - 主键
*/
public Integer getId() {
return id;
}
/**
* 设置主键
*
* @param id 主键
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取角色名
*
* @return name - 角色名
*/
public String getName() {
return name;
}
/**
* 设置角色名
*
* @param name 角色名
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* 获取编号
*
* @return code - 编号
*/
public String getCode() {
return code;
}
/**
* 设置编号
*
* @param code 编号
*/
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
/**
* 获取备注
*
* @return remark - 备注
*/
public String getRemark() {
return remark;
}
/**
* 设置备注
*
* @param remark 备注
*/
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
/**
* 获取创建时间
*
* @return gmt_create - 创建时间
*/
public Date getGmtCreate() {
return gmtCreate;
}
/**
* 设置创建时间
*
* @param gmtCreate 创建时间
*/
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
/**
* 获取最后修改时间
*
* @return gmt_modified - 最后修改时间
*/
public Date getGmtModified() {
return gmtModified;
}
/**
* 设置最后修改时间
*
* @param gmtModified 最后修改时间
*/
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
}
| true
|
7ae6ce8b4e391c460e1dcfcfcd0517c0c36a4408
|
Java
|
CarlosVV/demuna
|
/src/pe/gob/dmn/model/FileUploadBean.java
|
UTF-8
| 479
| 1.921875
| 2
|
[] |
no_license
|
package pe.gob.dmn.model;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class FileUploadBean {
private String txtId2;
private CommonsMultipartFile file;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
public String getTxtId2() {
return txtId2;
}
public void setTxtId2(String txtId2) {
this.txtId2 = txtId2;
}
}
| true
|
e2a2d30dcb6ab167bf76fa3199e532f78d7b7aa7
|
Java
|
cenbow/Daisy
|
/yourong-core/src/main/java/com/yourong/core/ic/dao/LeaseDetailMapper.java
|
UTF-8
| 1,712
| 1.914063
| 2
|
[] |
no_license
|
package com.yourong.core.ic.dao;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.yourong.common.pageable.Page;
import com.yourong.core.ic.model.LeaseDetail;
public interface LeaseDetailMapper {
int deleteByPrimaryKey(Long id);
int insert(LeaseDetail record);
int insertSelective(LeaseDetail record);
LeaseDetail selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(LeaseDetail record);
int updateByPrimaryKey(LeaseDetail record);
Page<LeaseDetail> findByPage(Page<LeaseDetail> pageRequest, @Param("map") Map<String, Object> map);
int batchDelete(@Param("ids") long[] ids);
List<LeaseDetail> selectForPagin(@Param("map") Map<String, Object> map);
int selectForPaginTotalCount(@Param("map") Map<String, Object> map);
/**
* 根据租赁分红id查询租赁记录的条数
*
* @param leaseBonusId
* @return
*/
int selectCountByLeaseBonusId(@Param("leaseBonusId") Long leaseBonusId);
/**
*根据租赁分红id查询已分红的租赁记录
*
* @param leaseBonusId
* @return
*/
List<LeaseDetail> selectListByLeaseBonusId(@Param("leaseBonusId") Long leaseBonusId);
/**
* 根据项目id获取租赁记录
*
* @param projectId
* @return
*/
List<LeaseDetail> findListByProjectId(@Param("projectId") Long projectId);
/**
* 获取一个分红项目中用户已分红的总额
* @param leaseBonusId
* @return
*/
BigDecimal getTotalUserBonusByLeaseBonusId(@Param("leaseBonusId")Long leaseBonusId);
/**
* 根据状态获取项目分红期数
* @param leaseBonusId
* @return
*/
int getLeaseDetailCountByStatus(@Param("map")Map<String, Object> map);
}
| true
|
acb818006770bed0e21eae2e8cdb43c715bf901a
|
Java
|
Shaq1256/RESTAPI
|
/src/main/java/kodilla/library/Book.java
|
UTF-8
| 1,587
| 3.0625
| 3
|
[] |
no_license
|
package kodilla.library;
import java.time.LocalDate;
public class Book {
String title;
String author;
LocalDate publishedDate;
public Book(String title, String author, int yearOfPublished, int monthOfPublished, int dayOfPublished) {
this.title = title;
this.author = author;
this.publishedDate = LocalDate.of(yearOfPublished, monthOfPublished, dayOfPublished);
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public LocalDate getPublishedDate() {
return publishedDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (title != null ? !title.equals(book.title) : book.title != null) return false;
if (author != null ? !author.equals(book.author) : book.author != null) return false;
return publishedDate != null ? publishedDate.equals(book.publishedDate) : book.publishedDate == null;
}
@Override
public int hashCode() {
int result = title != null ? title.hashCode() : 0;
result = 31 * result + (author != null ? author.hashCode() : 0);
result = 31 * result + (publishedDate != null ? publishedDate.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Title: '" + title + '\'' +
", author='" + author + '\'' +
", publishedDate: " + publishedDate;
}
}
| true
|
8e4c2cb9d60e1bb4e4272466863727a5adf9738f
|
Java
|
18646331841/WorkManage
|
/app/src/main/java/com/barisetech/www/workmanage/http/HttpService.java
|
UTF-8
| 4,492
| 2.5
| 2
|
[] |
no_license
|
package com.barisetech.www.workmanage.http;
import android.text.TextUtils;
import com.barisetech.www.workmanage.BuildConfig;
import com.barisetech.www.workmanage.base.BaseConstant;
import com.barisetech.www.workmanage.utils.LogUtil;
import com.barisetech.www.workmanage.utils.SharedPreferencesUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by LJH on 2018/8/3.
*/
public class HttpService {
public static final String TAG = "HttpService";
private static final int DEFAULT_TIME_OUT = 20;//超时时间 10s
private static final int DEFAULT_READ_TIME_OUT = 10;
private Retrofit mRetrofit;
private HttpService(){
}
private static class SingletonHolder{
private static final HttpService INSTANCE = new HttpService();
}
/**
* 获取HttpService
* @return
*/
public static HttpService getInstance(){
return SingletonHolder.INSTANCE;
}
/**
* json数据方式请求
*/
public HttpService buildJsonRetrofit() {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept-Encoding", "gzip");
headerMap.put("Accept", "application/json");
headerMap.put("Content-Type", "application/json; charset=utf-8");
return buildRetrofit(headerMap);
}
/**
* urlencoded方式请求
*/
public HttpService buildUrlencodedRetrofit() {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Content-Type", "application/x-www-form-urlencoded");
return buildRetrofit(headerMap);
}
/**
* 构建Retrofit,并设置请求头信息
* @param headerMap 请求头Map
* @return
*/
public HttpService buildRetrofit(Map<String, String> headerMap) {
// headerMap.put(BaseConstant.AUTH_HEADER, "Bearer " + SharedPreferencesUtil.getInstance().getString(BaseConstant
// .SP_ACCESS_TOKEN, ""));
// 创建 OKHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间
builder.writeTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//写操作 超时时间
builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//读操作超时时间
if (BuildConfig.DEBUG) {
// Log信息拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置 Debug Log 模式
builder.addInterceptor(loggingInterceptor);
}
//项目中设置头信息
Interceptor headerInterceptor = chain -> {
Request originalRequest = chain.request();
Request.Builder requestBuilder = originalRequest.newBuilder();
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
requestBuilder.method(originalRequest.method(), originalRequest.body());
Request request = requestBuilder.build();
return chain.proceed(request);
};
builder.addInterceptor(headerInterceptor);
String value = SharedPreferencesUtil.getInstance().getString(BaseConstant.SP_IP_PORT, "");
String path;
if (!TextUtils.isEmpty(value)) {
String[] split = value.split("_");
path = String.format("http://%s:%s/", split[0], split[1]);
} else {
path = Config.BASE_URL;
}
// 创建Retrofit
mRetrofit = new Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(path)
.build();
return SingletonHolder.INSTANCE;
}
/**
* 获取对应的Service
* @param service Service 的 class
* @param <T>
* @return
*/
public <T> T create(Class<T> service){
return mRetrofit.create(service);
}
}
| true
|
9c4b80b5e768c2703e889ba61908f264a9f22ed7
|
Java
|
TrinhTrinh99/LTDD-CuoikyAppDocTruyen
|
/app/src/main/java/com/example/appdoctruyen/MainTimKiem.java
|
UTF-8
| 3,667
| 2.265625
| 2
|
[] |
no_license
|
package com.example.appdoctruyen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.example.appdoctruyen.adapter.adapterTruyen;
import com.example.appdoctruyen.database.Databasedoctruyen;
import com.example.appdoctruyen.model.Truyen;
import java.util.ArrayList;
public class MainTimKiem extends AppCompatActivity {
private ListView lvtimkiem;
private EditText edttimkiem;
ArrayList<Truyen> TruyenArrayList;
private Databasedoctruyen databasedoctruyen;
private ArrayList<Truyen> arrayList;
adapterTruyen adapterTruyen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tim_kiem);
lvtimkiem =(ListView)findViewById(R.id.lvtimkiem);
edttimkiem=(EditText)findViewById(R.id.searchtr);
initList();
lvtimkiem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainTimKiem.this,MainNoiDung.class);
String tent = arrayList.get(position).getTenTruyen();
String noidungt = arrayList.get(position).getNoiDung();
i.putExtra("ten truyen", tent);
i.putExtra("noi dung", noidungt);
startActivity(i);
}
});
edttimkiem.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
filter((s.toString()));
}
});
}
// searrch
private void filter(String text){
// xoa du lieu mang
arrayList.clear();
ArrayList<Truyen> filteredList = new ArrayList<>();
for(Truyen item : TruyenArrayList){
if(item.getTenTruyen().toLowerCase().contains(text.toLowerCase())){
// them item vao filtereslisst
filteredList.add(item);
arrayList.add(item);
}
}
adapterTruyen.filterList(filteredList);
}
private void initList() {
TruyenArrayList = new ArrayList<>();
arrayList = new ArrayList<>();
databasedoctruyen = new Databasedoctruyen(this);
Cursor cursor = databasedoctruyen.getData2();
while (cursor.moveToNext()) {
// Lấy dữ liệu và gán vào biến, dữ liệu tài khoản ở số 1, mk 2,idtaikhoan 0, email 3,phân quyền 4
int id = cursor.getInt(0);
String tentruyen = cursor.getString(1);
String hinhanh = cursor.getString(2);
String noidung = cursor.getString(3);
int id_tk = cursor.getInt(4);
TruyenArrayList.add(new Truyen(id,tentruyen,hinhanh,noidung,id_tk));
arrayList.add(new Truyen(id,tentruyen,hinhanh,noidung,id_tk));
adapterTruyen = new adapterTruyen(getApplicationContext(),TruyenArrayList);
lvtimkiem.setAdapter(adapterTruyen);
}
cursor.moveToFirst();
cursor.close();
}
}
| true
|
bbde88175cf20785745a376b6745f22f7be6a313
|
Java
|
sabirova/chess
|
/src/com/chessgame/game/pieces/Knight.java
|
UTF-8
| 2,393
| 3.375
| 3
|
[] |
no_license
|
package com.chessgame.game.pieces;
import com.chessgame.game.Player;
import java.util.ArrayList;
import java.util.List;
public class Knight extends Piece {
public Knight(Color color, Position position) {
super("N", position, color);
}
@Override
public boolean canMove(Position positionTo) {
return false;
}
@Override
public List<Position> getPossibleMoves(Player player, Board board) {
List<Position> possibleMoves = new ArrayList<Position>();
int x = this.getPosition().getX();
int y = this.getPosition().getY();
//up-right
if (Position.isCorrectPosition(x + 2, y - 1)) {
if (!board.isOccupiedPosition(x+2, y-1, this.getColor())) {
possibleMoves.add(new Position(x+2, y-1));
}
}
if (Position.isCorrectPosition(x + 1, y - 2)) {
if (!board.isOccupiedPosition(x+1, y-2, this.getColor())) {
possibleMoves.add(new Position(x+1, y-2));
}
}
//up-left
if (Position.isCorrectPosition(x - 2, y - 1)) {
if (!board.isOccupiedPosition(x-2, y-1, this.getColor())) {
possibleMoves.add(new Position(x-2, y-1));
}
}
if (Position.isCorrectPosition(x - 1, y - 2)) {
if (!board.isOccupiedPosition(x-1, y-2, this.getColor())) {
possibleMoves.add(new Position(x-1, y-2));
}
}
//down-right
if (Position.isCorrectPosition(x + 2, y + 1)) {
if (!board.isOccupiedPosition(x+2, y+1, this.getColor())) {
possibleMoves.add(new Position(x+2, y+1));
}
}
if (Position.isCorrectPosition(x + 1, y + 2)) {
if (!board.isOccupiedPosition(x+1, y+2, this.getColor())) {
possibleMoves.add(new Position(x+1, y+2));
}
}
//down-left
if (Position.isCorrectPosition(x - 2, y + 1)) {
if (!board.isOccupiedPosition(x-2, y+1, this.getColor())) {
possibleMoves.add(new Position(x-2, y+1));
}
}
if (Position.isCorrectPosition(x - 1, y + 2)) {
if (!board.isOccupiedPosition(x-1, y+2, this.getColor())) {
possibleMoves.add(new Position(x-1, y+2));
}
}
return possibleMoves;
}
}
| true
|
99b83c1a764fedcaafdcbc52e6fac42e9a70e2ed
|
Java
|
Jason0803/Java
|
/isis/2.TagHighlighter/src/ReadAndHighlightTag.java
|
UTF-8
| 12,073
| 2.578125
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
import java.nio.charset.Charset;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
/* LAST VIEWED: 08/05/2015 9:01 AM */
/* Algorithm Updated */
/* Fastened Work */
/* All Found Errors Gone */
/* Errors gone, just need extenstion */
/*
*
* This application is made for following purposes:
* 1. Browse ".EXP" file(s) (now extension on progress)
* 2. Find all of 'Segments'
* 3. Find segments contain specific tag(s) e.g. <b> or <keyword> (on progress to find multiple tags)
* 4. Highlight the tags" <b> and </b> OR <keyword="blahh"></keyword>
*
*/
//--------------------------------------------------------------------------------------------------------------------//
@SuppressWarnings("serial")
public class ReadAndHighlightTag extends JPanel implements ActionListener
{
ArrayList<String> entire = new ArrayList<String>();
ArrayList<Segment> segments = new ArrayList<Segment>();
JButton openButton;
JButton btnSearch;
JFileChooser fc;
JEditorPane txtpnabc;
private JTextField textField;
private JLabel lblTag;
private JTextField txtTagtag;
private static File file;
private String tag;
private static final String seg = "<Segment>";
private static final String src = "<Source>";
private static final String trg = "<Target>";
Segment tmpSeg = new Segment();
int segmentCount = 0;
BufferedReader br;
private final JScrollPane scrollPane = new JScrollPane();
// -------------------------------------------------------------------------------------------------------------------//
public ReadAndHighlightTag() // Constructor
{
setAutoscrolls(true);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(1050, 430));
//Create a file chooser
fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".EXP Files", "EXP");
fc.addChoosableFileFilter(filter);
setLayout(null);
//For layout purposes, put the buttons in a separate panel
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.WHITE);
buttonPanel.setBounds(12, 14, 1029, 87);
buttonPanel.setLayout(null);
//Add the buttons and the log to this panel.
add(buttonPanel);
JLabel lblFile = new JLabel("File");
lblFile.setBounds(22, 12, 36, 20);
buttonPanel.add(lblFile);
textField = new JTextField();
textField.setEditable(false);
textField.setBounds(81, 11, 819, 23);
buttonPanel.add(textField);
textField.setColumns(10);
openButton = new JButton("Open a File...");
openButton.setBounds(908, 10, 109, 23);
buttonPanel.add(openButton);
lblTag = new JLabel("Tag");
lblTag.setBounds(22, 50, 36, 19);
buttonPanel.add(lblTag);
txtTagtag = new JTextField();
txtTagtag.setText("tag1,tag2, ...\r\n");
txtTagtag.setBounds(83, 49, 819, 20);
buttonPanel.add(txtTagtag);
txtTagtag.setColumns(10);
btnSearch = new JButton("Search");
btnSearch.setBounds(908, 48, 109, 23);
buttonPanel.add(btnSearch);
openButton.addActionListener(this);
btnSearch.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(12, 137, 1029, 278);
add(panel);
panel.setLayout(null);
scrollPane.setBackground(Color.WHITE);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(0, 0, 1029, 278);
panel.add(scrollPane);
txtpnabc = new JEditorPane();
txtpnabc.setBackground(SystemColor.control);
txtpnabc.setContentType("text/html");
scrollPane.setViewportView(txtpnabc);
JLabel lblResult = new JLabel("Result :");
lblResult.setBounds(22, 109, 57, 15);
add(lblResult);
}
// -------------------------------------------------------------------------------------------------------------------//
public void actionPerformed(ActionEvent e)
{
StyledDocument doc = (StyledDocument) txtpnabc.getDocument();
//Handle open button action.
if (e.getSource() == openButton)
{
int returnVal = fc.showOpenDialog(ReadAndHighlightTag.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
file = fc.getSelectedFile();
if( file.getName().indexOf(".EXP") == -1 )
{
JOptionPane.showMessageDialog(scrollPane, "You should choose .EXP File !", "Warning",
JOptionPane.WARNING_MESSAGE);
System.exit(0);
}
//This is where a real application would open the file.
textField.setText(file.getName());
try
{
br = new BufferedReader(new InputStreamReader
(new FileInputStream(file.getPath()), Charset.forName("UTF-16")));
String line = br.readLine();
while( line != null )
{
entire.add(line);
line = br.readLine();
}
findSegment(entire);
br.close();
}
catch(Exception error) { error.printStackTrace(); }
}
else{
textField.setText("File Choose Cancelled by user");
}
}
else if(e.getSource() == btnSearch)
{
try
{
int i = 0;
StringBuilder contents = new StringBuilder();
txtpnabc.setText("");
tag = txtTagtag.getText();
String _tag = "<" + tag;
while(i < segments.size() )
{
if( (segments.get(i).getSource().indexOf(_tag+">")!= -1 || segments.get(i).getSource().indexOf(_tag+" ")!=-1) ||
( segments.get(i).getTarget().indexOf(_tag+">")!= -1 || segments.get(i).getTarget().indexOf(_tag+" ")!= -1) )
{
// tag in both source and target
contents.append("Segment: " + segments.get(i).getSegment() + "\n");
contents.append(" Source: " + segments.get(i).getSource() + "\n");
contents.append(" Target: " + segments.get(i).getTarget()+ "\n\n");
}
i++;
} // End of While
doc.insertString(doc.getLength(), contents.toString(), null); // put entire 'contents' on txtpnabc
Document document = txtpnabc.getDocument();
tagHighlighter(document);
}
catch( Exception error ) {error.printStackTrace();}
}
}
// -------------------------------------------------------------------------------------------------------------------//
void tagHighlighter(Document document) {
try
{
String find_1 = "<" +tag;
String find_2 = ">";
String find_3 = "</" + tag;
LOOP:
for (int index = 0; index + find_1.length() < document.getLength(); index++)
{
DefaultHighlighter.DefaultHighlightPainter highlightPainter =
new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
String match = document.getText(index, find_1.length());
if(find_1.equals(match))
{
int idx = index; // From the beginning of tag to an end
while(true)
{
match = document.getText(idx, find_2.length());
if(find_2.equals(match))
{
txtpnabc.getHighlighter().addHighlight(index, idx+1, highlightPainter);
break;
}
idx++;
}
int idx_2 = idx;
while(true) // From the beginning of closing tag to an end
{
match = document.getText(idx_2, find_3.length());
if(find_3.equals(match))
{
int idx_3 = idx_2;
while(true)
{
match = document.getText(idx_3, find_2.length());
if(find_2.equals(match))
{
txtpnabc.getHighlighter().addHighlight(idx_2, idx_3+1, highlightPainter);
continue LOOP;
}
idx_3++;
}
}
idx_2++;
}
}
}
}
catch (BadLocationException ex) { ex.printStackTrace(); }
}
// -------------------------------------------------------------------------------------------------------------------//
private static void createAndShowGUI()
{
//Create and set up the window.'
JFrame frame = new JFrame("FileChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.getContentPane().add(new ReadAndHighlightTag());
//Display the window.
frame.pack();
frame.setVisible(true);
}
// -------------------------------------------------------------------------------------------------------------------//
void findSegment(ArrayList<String> entire) throws Exception
{
Segment tempSeg = new Segment();
StringBuilder sb = new StringBuilder();
String temp;
for (int i=0; i < entire.size(); i++)
{
if( entire.get(i).indexOf(seg) != -1 ) // a line with 'segment' found
{
tempSeg.setSegment( entire.get(i).substring(9));
//find source and target
}
if( entire.get(i).indexOf(src) != -1 )
{
if( entire.get(i).indexOf("</Source>") != -1)
{
tempSeg.setSource( entire.get(i).substring(
8, entire.get(i).indexOf("</Source>")));
}
else
{
int j = i;
while(true)
{
if (entire.get(j).indexOf("</Source>") == -1)
{
sb.append(entire.get(j));
}
else if( entire.get(j).indexOf("</Source>") != -1)
{
sb.append(entire.get(j));
break;
}
j++;
}
temp = sb.toString();
sb = new StringBuilder();
tempSeg.setSource( temp.substring(8, temp.indexOf("</Source>")));
}
}
if( entire.get(i).indexOf(trg) != -1 )
{
if( entire.get(i).indexOf("</Target>") != -1)
{
tempSeg.setTarget( entire.get(i).substring(
8, entire.get(i).indexOf("</Target>")));
}
else
{
int j = i;
while(true)
{
if (entire.get(j).indexOf("</Target>") == -1)
{
sb.append(entire.get(j));
}
else
{
sb.append(entire.get(j));
break;
}
j++;
}
temp = sb.toString();
tempSeg.setTarget( temp.substring(8, temp.indexOf("</Target>")));
}
segments.add(tempSeg);
tempSeg = new Segment();
sb = new StringBuilder();
segments.get(segmentCount).printSegment();
segmentCount++;
}
}
}
// -------------------------------------------------------------------------------------------------------------------//
public static void main(String[] args)
{
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
//Windows UI
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
createAndShowGUI();
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
// -------------------------------------------------------------------------------------------------------------------//
| true
|
a13442ddf58f9a6282971a09641b81463b775c37
|
Java
|
elderz6/testesJavaDio
|
/src/main/java/TesteDioTres.java
|
UTF-8
| 1,097
| 3.40625
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TesteDioTres {
public static void main(String[] args) throws IOException {
int positivos = 0;
int negativos = 0;
int pares = 0;
int impares = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while ( ((line = br.readLine()) != null) && (!line.isEmpty())) {
String[] tokens = line.split("\\s");
double valor = Double.parseDouble((line));
if (valor > 0)
positivos++;
else if(valor < 0)
negativos++;
if(valor % 2 == 0)
pares++;
else
impares++;
}
br.close();
System.out.println(pares + " valor(es) par(es)");
System.out.println(impares + " valor(es) impares");
System.out.println(positivos + " valor(es) positivos");
System.out.println(negativos + " valor(es) negativos");
//7 -5 6 -3.4 4.6 12
}
}
| true
|
f01f4c78601a736509d5d2f34bba7ff9952f0892
|
Java
|
Ecam223/SwerveDriveSimulator
|
/SwerveDriveSim2.0/SwerveDriveSimulator/src/main/java/RobotControllers/BetterArcadeDrive.java
|
UTF-8
| 3,850
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
package RobotControllers;
import interfaces.JoysticksInterface;
import interfaces.RobotController;
import interfaces.RobotInterface;
import interfaces.SwerveWheelInterface;
public class BetterArcadeDrive implements RobotController {
@Override
public void loop(JoysticksInterface joysticks, RobotInterface robot) {
//Variables
double leftPower = joysticks.getLeftStick().y * 5.0;
double rightPower = joysticks.getLeftStick().y * 5.0;
double right = joysticks.getRightStick().x * 5.0;
double c1 = 2 * 3.14 * 0.5;
double c2 = 2 * 3.14 * 0.75;
// assist to allow driving exactly straight
if (Math.abs(leftPower - rightPower) < 0.5) {
leftPower = rightPower;
}
for (SwerveWheelInterface wheel : robot.getDrivetrain()) {
// make sure the wheels are always facing forward (none of this funny swerve business)
wheel.setWheelAngle(0);
if(wheel.getPosition().x > 0){
//If wheel is on right side of robot
if(wheel.getPosition().x > 0.51){
//If wheel is on the outside of the right side
if((right/5) > 0.001){
//If right stick has moved
if((leftPower/5) < -0.001) {
wheel.setWheelVelocity(leftPower + ((c2 - c1) * (right)));
}else if((leftPower/5) > 0.001){
wheel.setWheelVelocity(leftPower - ((c2 - c1) * (right)));
}
}else if((right/5) >=0 && (right/5) < 0.001){
//If right stick is in neutral position
wheel.setWheelVelocity(leftPower);
}
}else if(wheel.getPosition().x > 0 && wheel.getPosition().x < 0.51) {
//If wheel is on the inside of the right side
wheel.setWheelVelocity(leftPower);
}
}else if(wheel.getPosition().x < 0){
//If wheel is on left side of roboto
if(wheel.getPosition().x < -.51){
//If wheel is on outside of the left side
if((right/5) < -0.001){
//If right stick has moved
if((leftPower/5) < -0.001) {
wheel.setWheelVelocity(leftPower - ((c2 - c1) * (right)));
}else if((leftPower/5) > 0.001){
wheel.setWheelVelocity(leftPower + ((c2 - c1) * (right)));
}
}else if((right / 5) <= 0 && (right / 5) >= -0.001){
wheel.setWheelVelocity(leftPower);
}
}else if(wheel.getPosition().x < 0 && wheel.getPosition().x > -.51){
//If wheel is on inside of left side
wheel.setWheelVelocity(leftPower);
}
}
if((leftPower / 5) < 0.001 && (leftPower / 5) > -.001){
if(wheel.getPosition().x > 0) {
if(right > 0) {
wheel.setWheelVelocity(-right);
System.out.println("It worked");
}else if(right < 0){
wheel.setWheelVelocity(-right);
System.out.println("It worked 2.0");
}
}else if(wheel.getPosition().x < 0){
if(right > 0){
wheel.setWheelVelocity(right);
}else if(right < 0){
wheel.setWheelVelocity(right);
}
}
}
}
}
}
| true
|
2a4de43811080be0857d8e7410004396f4015008
|
Java
|
decc/national-household-model-core-components
|
/core-projects/jasb/src/main/java/com/larkery/jasb/sexp/BetterPrinter.java
|
UTF-8
| 4,434
| 2.6875
| 3
|
[] |
no_license
|
package com.larkery.jasb.sexp;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Objects;
import com.google.common.base.CharMatcher;
public class BetterPrinter implements ISExpressionVisitor, AutoCloseable {
private final BufferedWriter output;
private int indentation = 0;
private Location whereAmI = null;
private Location toShift = null;
private boolean inSpace = true;
private int column = 1;
private int columnDelta = 0;
private int line = 1;
private boolean inComment = false;
private final int maxSpacing;
public BetterPrinter(final Writer output, final int maxSpacing) {
this.maxSpacing = maxSpacing;
this.output = new BufferedWriter(output);
}
public static void print(final ISExpression expression, final Writer output, final int maxLineSkip) {
try (BetterPrinter p = new BetterPrinter(output, maxLineSkip)) {
expression.accept(p);
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public void locate(final Location loc) {
toShift = loc;
}
private void doShift() {
shift(toShift);
inComment = false;
}
private void shift(final Location loc) {
if (whereAmI != null && loc != null) {
if (Objects.equals(whereAmI.name, loc.name)) {
if (line == loc.line) {
shiftColumn(loc.column - columnDelta);
} else if (line < loc.line) {
shiftLine(loc.line - line);
columnDelta = loc.column;
} else {
shiftLine(1);
columnDelta = loc.column;
}
} else {
shiftLine(1);
columnDelta = loc.column;
}
line = loc.line;
} else if (inComment) {
shiftLine(1);
} else if (loc != null) {
shiftLine(loc.line - line);
}
whereAmI = loc;
}
private void shiftColumn(final int column) {
try {
while (this.column < column) {
this.column++;
output.write(" ");
inSpace = true;
}
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private void shiftLine(int j) {
line += j;
j = Math.min(j, maxSpacing);
try {
while (j > 0) {
output.write("\n");
for (int i = 0; i<indentation; i++) {
output.write("\t");
}
j--;
inSpace = true;
column = 1;
}
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public void open(final Delim delimeter) {
doShift();
write(""+delimeter.open);
indentation++;
}
private static int lines(final String s) {
int c = 0;
boolean wasR = false;
for (int i =0; i<s.length(); i++) {
switch (s.charAt(i)) {
case '\n':
c++;
wasR = false;
break;
case '\r':
wasR = true;
break;
default:
if (wasR) {
c++;
}
wasR = false;
}
}
if (wasR) c++;
return c;
}
private static final CharMatcher END_TOKEN = CharMatcher.WHITESPACE.or(
CharMatcher.anyOf(":()[]"));
private static final CharMatcher NO_PRESPACE_TOKEN = CharMatcher.WHITESPACE.or(
CharMatcher.anyOf(")]"));
private void write(final String string) {
try {
if (!inSpace && !NO_PRESPACE_TOKEN.matches(string.charAt(0))) {
if (column > 100) {
shiftLine(1);
} else {
shiftColumn(this.column + 1);
}
}
if (string.contains("\n") || string.contains("\r")) {
output.write(string);
column = string.length() - (string.lastIndexOf("\n") + 1);
line += lines(string);
} else {
output.write(string);
column += string.length();
}
inSpace = END_TOKEN.matches(string.charAt(string.length()-1));
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public void atom(final String string) {
doShift();
write(Atom.escape(string));
}
@Override
public void comment(final String text) {
doShift();
if (whereAmI == null) {
shiftLine(1);
}
write(";" + text);
inComment = true;
}
@Override
public void close(final Delim delimeter) {
indentation--;
doShift();
write(""+delimeter.close);
}
@Override
public void close() throws IOException {
this.output.close();
}
public static String print(final ISExpression expand) {
return print(expand, Integer.MAX_VALUE);
}
public static String print(final ISExpression expand, final int maxLineSkip) {
final StringWriter sw = new StringWriter();
print(expand, sw, maxLineSkip);
return sw.toString();
}
}
| true
|
f7244774b65e7fc36424c86f62bb6652a3f4c8c6
|
Java
|
hoangminh281/New-Share-Food
|
/app/src/main/java/com/ptit/tranhoangminh/newsharefood/models/BillModel.java
|
UTF-8
| 504
| 2.15625
| 2
|
[] |
no_license
|
package com.ptit.tranhoangminh.newsharefood.models;
public class BillModel {
String user_id;
int total;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public BillModel(String user_id) {
this.user_id = user_id;
}
public BillModel() {
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
}
| true
|
c92dcbb2127cb3e71175b1f09de08eac896b98c5
|
Java
|
PandaWarrior2/DSBDA_HW2
|
/sbloghandler/src/main/java/ru/nikitin/sbloghandler/service/StatisticService.java
|
UTF-8
| 2,135
| 2.4375
| 2
|
[] |
no_license
|
package ru.nikitin.sbloghandler.service;
import com.datastax.spark.connector.japi.CassandraJavaUtil;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.springframework.stereotype.Service;
import ru.nikitin.sbloghandler.dto.LogDTO;
import ru.nikitin.sbloghandler.dto.ResultData;
import ru.nikitin.sbloghandler.properties.CassandraAppProperties;
import scala.Tuple2;
import java.util.Calendar;
import java.util.List;
import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions;
/**
* Сервис подсчёта статистики по логам
* */
@Service
public class StatisticService {
private final JavaSparkContext javaSparkContext;
private final CassandraAppProperties cassandraProperties;
public StatisticService(SparkConf sparkConf, CassandraAppProperties cassandraProperties) {
this.javaSparkContext = new JavaSparkContext(SparkContext.getOrCreate(sparkConf));
this.cassandraProperties = cassandraProperties;
}
/**
* Метод подсчёта статистика с помощью spark RDD*/
public List<ResultData> compute() {
Calendar calendar = Calendar.getInstance();
return javaFunctions(javaSparkContext)
.cassandraTable(
cassandraProperties.getKeySpace(),
cassandraProperties.getTable(),
CassandraJavaUtil.mapRowTo(LogDTO.class)
)
.mapToPair(logDTO -> {
calendar.setTimeInMillis(logDTO.getDatetime().getTime());
return new Tuple2<>(new Tuple2<Integer, Integer>(calendar.get(Calendar.HOUR_OF_DAY), logDTO.getPriority()), 1);
})
.reduceByKey(Integer::sum)
.map(tuple2IntegerTuple2 -> new ResultData(tuple2IntegerTuple2._1._1, tuple2IntegerTuple2._1._2, tuple2IntegerTuple2._2))
.sortBy(ResultData::getPriority, false, 10)
.sortBy(ResultData::getHour, true, 10)
.collect();
}
}
| true
|
20117e4901cf392188f45a0b61a27914ebbab89a
|
Java
|
kuldarim/gis_draw_dot_where_polyline_intersects
|
/src/main/java/src/IntersectApp.java
|
UTF-8
| 5,802
| 2.5
| 2
|
[] |
no_license
|
/* Copyright 2014 Esri
All rights reserved under the copyright laws of the United States
and applicable international laws, treaties, and conventions.
You may freely redistribute and use this sample code, with or
without modification, provided you include the original copyright
notice and use restrictions.
See the use restrictions.*/
package main.java.src;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Polyline;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.map.ArcGISTiledMapServiceLayer;
import com.esri.map.GraphicsLayer;
import com.esri.map.JMap;
import com.esri.map.LayerList;
import com.esri.map.MapEvent;
import com.esri.map.MapEventListenerAdapter;
/**
* This sample shows how to add different kinds of graphics to a graphics layer.
*/
public class IntersectApp {
private JMap map;
// Constructor
public IntersectApp() { }
// ------------------------------------------------------------------------
// Core functionality
// ------------------------------------------------------------------------
/**
* Creates the map, adds a tiled basemap and a graphics layer and adds
* graphics to this graphics layer when the 'map ready' event fires, that is,
* when the map's spatial reference has been set by the basemap.
* @return
*/
private JMap createMap() {
JMap jMap = new JMap();
// set to default extent
jMap.setExtent(new Envelope(-15.8, -37.8, 156.8, 77.3));
// add base layer
ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/NGS_Topo_US_2D/MapServer");
LayerList layers = jMap.getLayers();
layers.add(tiledLayer);
// create the graphics layer
final GraphicsLayer graphicsLayer = new GraphicsLayer();
jMap.addMapEventListener(new MapEventListenerAdapter() {
@Override
public void mapReady(final MapEvent arg0) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
addSimpleLineGraphics(graphicsLayer);
}
});
}
});
layers.add(graphicsLayer);
return jMap;
}
/**
* Adds graphics symbolized with SimpleLineSymbols.
* @param graphicsLayer
*/
private void addSimpleLineGraphics(GraphicsLayer graphicsLayer) {
Polyline polyline = new Polyline();
polyline.startPath(118.169, 34.016);
polyline.lineTo(104.941, 39.7072);
polyline.lineTo(96.724, 32.732);
SimpleLineSymbol symbol = new SimpleLineSymbol(Color.MAGENTA, 4);
symbol.setStyle(SimpleLineSymbol.Style.SOLID);
Graphic graphic = new Graphic(polyline, symbol);
graphicsLayer.addGraphic(graphic);
Polyline polyline2 = new Polyline();
polyline2.startPath(150.169, 34.016);
polyline2.lineTo(90.941, 39.7072);
SimpleLineSymbol symbol2 = new SimpleLineSymbol(Color.BLACK, 4);
symbol2.setStyle(SimpleLineSymbol.Style.SOLID);
Graphic graphic2 = new Graphic(polyline2, symbol2);
graphicsLayer.addGraphic(graphic2);
}
// ------------------------------------------------------------------------
// Static methods
// ------------------------------------------------------------------------
/**
* Starting point of this application.
*
* @param args
* arguments to this application.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
// instance of this application
IntersectApp addGraphicsApp = new IntersectApp();
// create the UI, including the map, for the application.
JFrame appWindow = addGraphicsApp.createWindow();
appWindow.add(addGraphicsApp.createUI());
appWindow.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
// ------------------------------------------------------------------------
// Public methods
// ------------------------------------------------------------------------
/**
* Creates and displays the UI, including the map, for this application.
*
* @return the UI component.
*/
public JComponent createUI() {
// application content
JComponent contentPane = createContentPane();
// map
map = createMap();
contentPane.add(map);
return contentPane;
}
// ------------------------------------------------------------------------
// Private methods
// ------------------------------------------------------------------------
/**
* Creates a content pane.
*
* @return a content pane.
*/
private static JLayeredPane createContentPane() {
JLayeredPane contentPane = new JLayeredPane();
contentPane.setBounds(100, 100, 1000, 700);
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.setVisible(true);
return contentPane;
}
/**
* Creates a window.
*
* @return a window.
*/
private JFrame createWindow() {
JFrame window = new JFrame("Add Graphics Application");
window.setBounds(100, 100, 1000, 700);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setLayout(new BorderLayout(0, 0));
window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
super.windowClosing(windowEvent);
map.dispose();
}
});
return window;
}
}
| true
|
4182dfc2ca58aaca072dbe674a142f24c84129b4
|
Java
|
Bupt-Gantch/ZigbeeResolution
|
/src/main/java/com/bupt/ZigbeeResolution/service/ILoggingEventServiceImpl.java
|
UTF-8
| 613
| 2.0625
| 2
|
[] |
no_license
|
package com.bupt.ZigbeeResolution.service;
import com.bupt.ZigbeeResolution.data.LoggingEvent;
import com.bupt.ZigbeeResolution.mapper.LogEventMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author yjt
* @date 2019/06/27
*/
@Service
public class ILoggingEventServiceImpl implements ILoggingEventService{
@Autowired
private LogEventMapper logEventMapper;
@Override
public boolean insertLog(LoggingEvent loggingEvent) {
Integer i = logEventMapper.addLogEvent(loggingEvent);
return i == 1;
}
}
| true
|
19c0a239ed8654ba4705dc2bfc60823974169041
|
Java
|
zagsuccess/rl-app-messageSent
|
/rl-app-sewage/src/main/java/com/uhope/sewage/web/SewageDisposeReportController.java
|
UTF-8
| 7,464
| 2
| 2
|
[] |
no_license
|
package com.uhope.sewage.web;
import com.github.pagehelper.PageInfo;
import com.uhope.base.constants.Constant;
import com.uhope.base.result.ResponseMsgUtil;
import com.uhope.base.result.Result;
import com.uhope.sewage.domain.SewageDisposeReport;
import com.uhope.sewage.service.SewageDisposeReportService;
import com.uhope.sewage.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
/**
* 描述:
* 条目控制类
*
* @author a4994
* @create 2018-09-28 9:12
*/
@RestController
@RequestMapping("/v1/SewageDisposeReport")
public class SewageDisposeReportController {
@Autowired
private SewageDisposeReportService sewageDisposeReportService;
@PostMapping("/add")
public Result<SewageDisposeReport> add(@RequestParam String name,
@RequestParam String region,
@RequestParam String assess,
@RequestParam Integer status,
@RequestParam String reason,
@RequestParam String parentid) {
SewageDisposeReport sewageDisposeReport = new SewageDisposeReport();
sewageDisposeReport.setId(UUID.randomUUID().toString().replace("-",""));
sewageDisposeReport.setCode(sewageDisposeReport.getId());
sewageDisposeReport.setName(name);
sewageDisposeReport.setRegion(region);
sewageDisposeReport.setAssess(assess);
sewageDisposeReport.setStatus(status);
sewageDisposeReport.setReason(reason);
sewageDisposeReport.setParentid(parentid);
sewageDisposeReportService.insert(sewageDisposeReport);
return ResponseMsgUtil.success(sewageDisposeReport);
}
@DeleteMapping("/delete")
public Result delete(@RequestParam String id) {
sewageDisposeReportService.remove(id);
return ResponseMsgUtil.success();
}
@DeleteMapping("/deletelist")
public Result deletelist(@RequestParam String parentid) {
sewageDisposeReportService.deletelist(parentid);
return ResponseMsgUtil.success();
}
@PutMapping("/update")
public Result<SewageDisposeReport> update(@RequestParam String id,
@RequestParam String name,
@RequestParam String region,
@RequestParam String assess,
@RequestParam Integer status,
@RequestParam String reason) {
SewageDisposeReport sewageDisposeReport = new SewageDisposeReport();
sewageDisposeReport.setId(id);
sewageDisposeReport.setName(name);
sewageDisposeReport.setRegion(region);
sewageDisposeReport.setAssess(assess);
sewageDisposeReport.setStatus(status);
sewageDisposeReport.setReason(reason);
sewageDisposeReportService.update(sewageDisposeReport);
return ResponseMsgUtil.success(sewageDisposeReport);
}
@GetMapping("/detail")
public Result<SewageDisposeReport> detail(@RequestParam String id) {
SewageDisposeReport surfaceWaterGrade = sewageDisposeReportService.get(id);
return ResponseMsgUtil.success(surfaceWaterGrade);
}
@GetMapping("/list")
public Result<PageInfo<SewageDisposeReport>> list(@RequestParam(defaultValue = Constant.DEFAULT_PAGE_NUMBER) Integer pageNumber,
@RequestParam(defaultValue = Constant.DEFAULT_PAGE_SIZE) Integer pageSize,
@RequestParam String parentid) {
return ResponseMsgUtil.success(sewageDisposeReportService.list(pageNumber,pageSize,parentid));
}
@PostMapping("/upload")
public Result<Integer> upload(@RequestParam MultipartFile file,
@RequestParam String parentid,
HttpServletRequest req) throws IOException {
int code=100;
SewageDisposeReport sewageDisposeReport = new SewageDisposeReport();
InputStream in = file.getInputStream();
Workbook wb = null;
if (ExcelUtil.isExcel2007(file.getOriginalFilename())) {
wb = new XSSFWorkbook(in);
} else {
wb = new HSSFWorkbook(in);
}
Sheet sheetAt = wb.getSheetAt(0);
//获取所有行
int hang = sheetAt.getPhysicalNumberOfRows();
for (int i = 2; i < hang; i++) {
Row row = sheetAt.getRow(i);
Cell cell = row.getCell(0);
if (cell != null) {
cell.setCellType(CellType.STRING);
}
String oldCode=cell== null ? null :cell.getStringCellValue();
String name = row.getCell(1)== null ? null :row.getCell(1).getStringCellValue();
String region=row.getCell(2)== null ? null :row.getCell(2).getStringCellValue();
String assess=row.getCell(3)== null ? null :row.getCell(3).getStringCellValue();
String sta=row.getCell(4)== null ? null :row.getCell(4).getStringCellValue();
if ("是".equals(sta)){
sewageDisposeReport.setStatus(0);
}else{
sewageDisposeReport.setStatus(1);
}
String reason=row.getCell(5)== null ? null :row.getCell(5).getStringCellValue();
sewageDisposeReport.setId(UUID.randomUUID().toString().replace("-",""));
sewageDisposeReport.setCode(sewageDisposeReport.getId());
sewageDisposeReport.setName(name);
sewageDisposeReport.setRegion(region);
sewageDisposeReport.setAssess(assess);
sewageDisposeReport.setReason(reason);
sewageDisposeReport.setParentid(parentid);
sewageDisposeReportService.insert(sewageDisposeReport);
code=200;
}
return ResponseMsgUtil.success(code);
}
// 查询所有的污水处理厂
@GetMapping("/selectWorks")
public Result<List<String>> selectWorks(){
return ResponseMsgUtil.success(sewageDisposeReportService.selectWorks());
}
// 查询所有的区
@GetMapping("/districtlist")
public Result<List<String>> districtlist(){
return ResponseMsgUtil.success(sewageDisposeReportService.districtlist());
}
// 查询能否添加指定处理厂
@GetMapping("/haveSewage")
public Result<Integer> haveDistrict(@RequestParam String name,
@RequestParam String parentid){
// 10表示列表中没有这个区 可以增加 11表示有这个区 不能增加
int sta=10;
List<SewageDisposeReport> list = sewageDisposeReportService.haveSewage(parentid);
for (SewageDisposeReport s:list ) {
if (name.equals(s.getName())){
sta=11;
}
}
return ResponseMsgUtil.success(sta);
}
}
| true
|
c56a273584ec84d2ff8964921ba6cf6d57e569a7
|
Java
|
nguyenvudl/SeleniumMaven
|
/src/test/java/demodataprovider/NewTourRegister.java
|
UTF-8
| 3,322
| 1.992188
| 2
|
[] |
no_license
|
package demodataprovider;
import automation.utils.data.CommonData;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.openqa.selenium.interactions.HasTouchScreen;
import org.openqa.selenium.interactions.TouchScreen;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.Assert;
import java.util.concurrent.TimeUnit;
import java.io.File;
import io.appium.java_client.*;
import automation.utils.web.*;
import automationCore.DriverFactory;
public class NewTourRegister extends DriverFactory {
@Test(dataProvider="userData")
public void NewTourRegister(String username, String password, String firstname, String lastname, String addr, String city, String country, String email) throws Exception {
WebDriver driver = getDriver();
StringBuffer verificationErrors = new StringBuffer();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);
driver.get("http://newtours.demoaut.com/");
//driver.manage().window().maximize();
//driver.findElement(By.linkText("REGISTER")).click();
WebUtil.findElementText(driver,"REGISTER").click();
driver.findElement(By.name("firstName")).sendKeys(firstname);
driver.findElement(By.name("lastName")).sendKeys(lastname);
driver.findElement(By.name("phone")).sendKeys("123456789");
driver.findElement(By.name("userName")).sendKeys(username);
driver.findElement(By.name("address1")).sendKeys(addr);
driver.findElement(By.name("city")).sendKeys(city);
Select select = new Select(driver.findElement(By.name("country")));
select.selectByVisibleText(country);
driver.findElement(By.name("email")).sendKeys(email);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.name("confirmPassword")).sendKeys(password);
WebUtil.click(driver, By.name("register"));
logger.info("Page title is: " + driver.getTitle() + " " + firstname);
// Body should contain "Thank you for registering"
final String expectstring = "Dear " + firstname + " " + lastname;
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(By.tagName("body")).getText().contains(expectstring);
}
});
int deadlink = UrlUtil.validateInvalidLinks(driver);
}
@DataProvider(name="userData", parallel = false)
public Object[][] loginData() {
String workingDir = System.getProperty("user.dir");
Object[][] arrayObject = CommonData.getExcelData(workingDir + File.separator + "data" + File.separator + "user.xls","Sheet1");
return arrayObject;
}
}
| true
|
0206ea426cee38a95020c227ce403da4b44b8887
|
Java
|
Supriya-konnur/hibernate-programs
|
/icecream_management/java/com/xworkz/icecream/repository/IceCreamRepository.java
|
UTF-8
| 714
| 1.976563
| 2
|
[] |
no_license
|
package com.xworkz.icecream.repository;
import java.util.List;
import com.xworkz.icecream.entity.IceCreamEntity;
public interface IceCreamRepository {
public IceCreamEntity persist(IceCreamEntity iceCreamEntity);
public List<IceCreamEntity> getAll();
public void updatePriceByName(String name, double price);
public IceCreamEntity findByNameAndPrice(String name, double price);
public IceCreamEntity getByMaxPrice();
public IceCreamEntity getByMinPrice();
public Double getBySumPrice();
public Double getPriceByName(String name);
public List<Object[]> getNameAndFlavourByPrice(double price);
public void persist(List<IceCreamEntity> entities);
public void deleteByName(String name);
}
| true
|
cba3874e066b53b8b24b83ae6b2db379eb380880
|
Java
|
Erranda/easypaas
|
/src/main/java/com/withinet/opaas/wicket/html/AccountUpdateWidget.java
|
UTF-8
| 3,195
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.withinet.opaas.wicket.html;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.markup.html.form.EmailTextField;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.StringValidator;
import com.withinet.opaas.controller.UserController;
import com.withinet.opaas.controller.common.UserControllerException;
import com.withinet.opaas.model.domain.User;
import com.withinet.opaas.wicket.services.UserSession;
/**
* Login page
*
* @author kloe and Folarin
*
*/
public class AccountUpdateWidget extends Panel {
/**
*
*/
private static final long serialVersionUID = -6370041751528976156L;
final User user = UserSession.get().getUser();
private String fullName = null;
private String password = null;
private String confirmPassword = null;
private String email = null;
@SpringBean
UserController userController;
public AccountUpdateWidget (String id) {
super (id);
Form<Void> updateForm = new Form<Void>("form") {
@Override
public void onSubmit () {
if (confirmPassword != null && password != null) {
if( confirmPassword.equals(password)) {
user.setPassword(password);
} else {
error ("Passwords have to match");
throw new RestartResponseAtInterceptPageException (getPage());
}
}
try {
//Save and refresh page
UserSession.get().setUser(userController.updateAccount(user, user.getID(), user.getID()));
AccountIndex newPage = new AccountIndex ();
newPage.info("Updated");
setResponsePage (newPage);
} catch (UserControllerException e) {
error (e.getMessage());
setResponsePage (getPage());
}
}
};
add(updateForm);
EmailTextField wicketEmail = new EmailTextField("email", new PropertyModel<String>(user, "email"));
updateForm.add(wicketEmail);
TextField<String> wicketName = new TextField<String>("name", new PropertyModel<String>(user, "fullName"));
wicketName.add(StringValidator.minimumLength(2));
updateForm.add(wicketName);
PasswordTextField wicketPassword = new PasswordTextField("password", new PropertyModel<String>(this, "password"));
wicketPassword.add (StringValidator.minimumLength(6));
wicketPassword.setRequired(false);
wicketPassword.setLabel(new ResourceModel ("label.password"));
updateForm.add(wicketPassword);
PasswordTextField wicketConfirmPassword = new PasswordTextField("confirm-password", new PropertyModel<String>(this, "confirmPassword"));
wicketConfirmPassword.add (StringValidator.minimumLength(6));
wicketConfirmPassword.setRequired(false);
wicketConfirmPassword.setLabel(new ResourceModel ("label.confirmPassword"));
updateForm.add(wicketConfirmPassword);
}
}
| true
|
2aaecf3babe1b75969b2e060d22bea2b5f1c09e1
|
Java
|
saifhaque/Food_Order_App
|
/app/src/main/java/com/example/foodorderapp/MainActivity.java
|
UTF-8
| 1,427
| 2.203125
| 2
|
[] |
no_license
|
package com.example.foodorderapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.os.Bundle;
import android.widget.Toast;
import com.example.foodorderapp.Adapters.MainAdapter;
import com.example.foodorderapp.Models.MainModel;
import com.example.foodorderapp.databinding.ActivityMainBinding;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
ArrayList<MainModel> list = new ArrayList<>();
list.add(new MainModel(R.drawable.burger, "Burger", "5", "Yummy burger"));
list.add(new MainModel(R.drawable.fries, "Fries", "3", "Yummy fries"));
list.add(new MainModel(R.drawable.maggi, "Maggi", "3", "Yummy maggi"));
list.add(new MainModel(R.drawable.pizza, "Pizza", "5", "Yummy pizza"));
list.add(new MainModel(R.drawable.burger, "Burger", "5", "Yummy burger"));
MainAdapter adapter = new MainAdapter(list, this);
binding.recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
binding.recyclerView.setLayoutManager(layoutManager);
}
}
| true
|
90a9d788771c84eec05a5898f883a47bf19e8a04
|
Java
|
gatechatl/DRPPM
|
/src/proteomics/phospho/tools/pssm/GenerateBackgroundFrequencyTable.java
|
UTF-8
| 5,353
| 2.546875
| 3
|
[] |
no_license
|
package proteomics.phospho.tools.pssm;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
public class GenerateBackgroundFrequencyTable {
public static String type() {
return "PSSM";
}
public static String description() {
return "Go through the entire UNIPROT database and grab all the S/T/Y site and generate the frequency background for S/T and Y motifs";
}
public static String parameter_info() {
return "[fastaFile] [outputFileST] [outputFileY]";
}
public static void execute(String[] args) {
try {
String fastaFile = args[0];
String outputFileST = args[1];
String outputFileY = args[2];
HashMap map = readFastaFile(fastaFile);
HashMap[] background_ST = new HashMap[15];
HashMap[] background_Y = new HashMap[15];
HashMap allbackground = new HashMap();
for (int i = 0; i < 15; i++) {
background_ST[i] = new HashMap();
background_Y[i] = new HashMap();
}
int totalST = 0;
int totalY = 0;
double totalAll = 0;
Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
String geneName = (String)itr.next();
String fasta = (String)map.get(geneName);
for (int i = 0; i < fasta.length() - 15; i++) {
String aminoacid = fasta.substring(i, i + 1);
totalAll++;
if (allbackground.containsKey(aminoacid)) {
double count = (Double)allbackground.get(aminoacid);
count++;
allbackground.put(aminoacid, count);
} else {
allbackground.put(aminoacid, 1.0);
}
String site = fasta.substring(i + 7, i + 7 + 1);
if (site.equals("S") || site.equals("T")) {
totalST++;
for (int j = 0; j < 15; j++) {
String aa = fasta.substring(i + j, i + j + 1);
if (background_ST[j].containsKey(aa)) {
int count = (Integer)background_ST[j].get(aa);
count++;
background_ST[j].put(aa, count);
} else {
int count = 0;
count++;
background_ST[j].put(aa, count);
}
}
}
if (site.equals("Y")) {
totalY++;
for (int j = 0; j < 15; j++) {
String aa = fasta.substring(i + j, i + j + 1);
if (background_Y[j].containsKey(aa)) {
int count = (Integer)background_Y[j].get(aa);
count++;
background_Y[j].put(aa, count);
} else {
int count = 0;
count++;
background_Y[j].put(aa, count);
}
}
}
}
}
FileWriter fwriter = new FileWriter(outputFileST);
BufferedWriter out = new BufferedWriter(fwriter);
FileWriter fwriter2 = new FileWriter(outputFileY);
BufferedWriter out2 = new BufferedWriter(fwriter2);
String[] amino_acids = {"A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y"};
out.write("Location");
out2.write("Location");
for (String aa: amino_acids) {
out.write("\t" + aa);
out2.write("\t" + aa);
}
out.write("\n");
out2.write("\n");
for (int i = 0; i < 15; i++) {
out.write((i - 7) + "");
out2.write((i - 7) + "");
for (String aa: amino_acids) {
if (background_ST[i].containsKey(aa)) {
double count = (Integer)background_ST[i].get(aa);
double frequency = count / totalST;
if (i == 7) {
if (aa.equals("T") || aa.equals("S")) {
count = (Double)allbackground.get(aa);
frequency = count / totalAll;
out.write("\t" + frequency);
}
} else {
out.write("\t" + frequency);
}
} else {
double count = 0;
double frequency = count / totalST;
out.write("\t" + frequency);
}
if (background_Y[i].containsKey(aa)) {
double count = (Integer)background_Y[i].get(aa);
double frequency = count / totalY;
if (i == 7) {
if (aa.equals("Y")) {
count = (Double)allbackground.get(aa);
frequency = count / totalAll;
out2.write("\t" + frequency);
}
} else {
out2.write("\t" + frequency);
}
//out2.write("\t" + frequency);
} else {
double count = 0;
double frequency = count / totalY;
out2.write("\t" + frequency);
}
}
out.write("\n");
out2.write("\n");
}
out.close();
out2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static HashMap readFastaFile(String inputFile) {
HashMap map = new HashMap();
try {
String uniprotName = "";
FileInputStream fstream = new FileInputStream(inputFile);
DataInputStream din = new DataInputStream(fstream);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
while (in.ready()) {
String str = in.readLine();
if (str.contains(">")) {
String[] split = str.split("\\|");
uniprotName = split[1];
} else {
if (map.containsKey(uniprotName)) {
String seq = (String)map.get(uniprotName);
seq += str.trim();
map.put(uniprotName, seq);
} else {
map.put(uniprotName, str.trim());
}
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
| true
|
60c0961b1bd564a424ab1dc7084f5d33a3eb46a3
|
Java
|
oogachuga/calculator
|
/src/com/calculator/EquationOperation.java
|
UTF-8
| 315
| 3.109375
| 3
|
[] |
no_license
|
package com.calculator;
public enum EquationOperation {
ADD ("+"),
SUBTRACT ("-"),
MULTIPLY ("*"),
DIVIDE ("/");
private final String part;
EquationOperation(String part) {
this.part = part;
}
public String getString() {
return this.part;
}
}
| true
|
feacd658846c30cfaebfde674fa6787de40721bd
|
Java
|
rgorodischer/sp-guava-demo
|
/guava-demo/src/test/java/com/scalepoint/ecc/education/guava/strings/JoinerTest.java
|
UTF-8
| 975
| 2.8125
| 3
|
[] |
no_license
|
package com.scalepoint.ecc.education.guava.strings;
import com.google.common.base.Joiner;
import com.google.inject.internal.ImmutableMap;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Map;
import static com.google.common.collect.Lists.newArrayList;
import static org.testng.Assert.assertEquals;
/**
* @author rgo
*/
@Test
public class JoinerTest {
public void testTokensJoining() {
List<String> tokens = newArrayList("first", "second", null, "last");
String result = Joiner.on(", ").useForNull("[null]").join(tokens);
assertEquals(result, "first, second, [null], last");
}
public void testKeyValuePairsJoining() {
Map<String, Integer> pairs = ImmutableMap.of("one", 1, "two", 2);
String result = Joiner.on(", and ").withKeyValueSeparator(" corresponds to digit ").join(pairs);
assertEquals(result, "one corresponds to digit 1, and two corresponds to digit 2");
}
}
| true
|
e4e336a5861cf136827c8c32d90da5c1bccf69a0
|
Java
|
shenzhen-arrom/DataStructureAndAlgorithm
|
/sort/ChooseSort.java
|
UTF-8
| 1,012
| 4.0625
| 4
|
[] |
no_license
|
package sort;
/**
* 选择排序:
* 原理:
* 1.从N个元素中找出关键字最小的与第一个元素交换
* 2.从2个元素开始找出里面的最小的元素,与第二元素互换,以此类推
* (核心是记录最小元素的角标)
*/
class ChooseSort{
/**
* 选择排序
* @param list
*/
public void chooseSort(int[] list){
//默认第一个是最小值
int index = 0;
for (int j = 0; j < list.length; j++) {
for (int i = j+1; i < list.length; i++) {
if(list[index]>list[i]){
//记录角标
index = i;
}
}
//交换元素(发现最小是第一个数据,则不需要交换)
if(j!=index){
//记录每轮的第一个元素
int temp = list[j];
list[j] = list[index];
list[index] = temp;
}
}
}
}
| true
|
d31625a2b9fce71c839cbeaf48ce3fc82794c9c9
|
Java
|
coder-zc/DataMiddlePlatform
|
/src/main/java/com/saas/datamiddleend/entity/vo/trans/FindTransListResVO.java
|
UTF-8
| 844
| 1.625
| 2
|
[] |
no_license
|
package com.saas.datamiddleend.entity.vo.trans;
import lombok.*;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName FindTransListResVO
* @Description TODO
* @Author leehao
* @Date 12/1/20 4:29 PM
* @Version V1.0
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class FindTransListResVO implements Serializable {
private static final long serialVersionUID = 6272050985531896884L;
/**
* 转换ID
*/
private Long idTransformation;
/**
* 转换名称
*/
private String name;
/**
* 描述
*/
private String description;
/**
* 创建用户
*/
private String createdUser;
/**
* 创建时间
*/
private Date createdDate;
/**
* 修改时间
*/
private Date modifiedDate;
}
| true
|
7f40deb566b2d8bb7bdb647dc6af06aa9e81bed8
|
Java
|
catalogueglobal/datatools-server
|
/src/main/java/com/conveyal/datatools/manager/models/ExternalFeedSourceProperty.java
|
UTF-8
| 994
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package com.conveyal.datatools.manager.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by demory on 3/30/16.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExternalFeedSourceProperty extends Model {
private static final long serialVersionUID = 1L;
// constructor for data dump load
public ExternalFeedSourceProperty() {}
public ExternalFeedSourceProperty(FeedSource feedSource, String resourceType, String name, String value) {
this.id = constructId(feedSource, resourceType, name);
this.feedSourceId = feedSource.id;
this.resourceType = resourceType;
this.name = name;
this.value = value;
}
public static String constructId(FeedSource feedSource, String resourceType, String name) {
return feedSource.id + "_" + resourceType + "_" + name;
}
public String resourceType;
public String feedSourceId;
public String name;
public String value;
}
| true
|
f6038c01946d23e8697081eeee98d0bee3e0f333
|
Java
|
pgangwani/zalenium
|
/src/test/java/de/zalando/ep/zalenium/dashboard/DashboardCleanupServletTest.java
|
UTF-8
| 4,799
| 2.25
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
package de.zalando.ep.zalenium.dashboard;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.zalando.ep.zalenium.util.CommonProxyUtilities;
import de.zalando.ep.zalenium.util.TestUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class DashboardCleanupServletTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private HttpServletRequest request;
private HttpServletResponse response;
private DashboardCleanupServlet dashboardCleanupServlet;
@Before
public void initMocksAndService() throws IOException {
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
private StringBuilder stringBuilder = new StringBuilder();
@Override
public boolean isReady() {
System.out.println("isReady");
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
System.out.println("setWriteListener");
}
@Override
public void write(int b) {
this.stringBuilder.append((char) b);
}
public String toString() {
return stringBuilder.toString();
}
});
dashboardCleanupServlet = new DashboardCleanupServlet();
// Temporal folder for dashboard files
TestUtils.ensureRequiredFilesExistForCleanup(temporaryFolder);
}
@Test
public void getDoCleanup() throws IOException {
try {
CommonProxyUtilities proxyUtilities = TestUtils.mockCommonProxyUtilitiesForDashboardTesting(temporaryFolder);
Dashboard.setCommonProxyUtilities(proxyUtilities);
when(request.getParameter("action")).thenReturn("doCleanup");
dashboardCleanupServlet.doGet(request, response);
Assert.assertEquals("SUCCESS", response.getOutputStream().toString());
} finally {
Dashboard.restoreCommonProxyUtilities();
}
}
@Test
public void postDoCleanup() throws IOException {
try {
CommonProxyUtilities proxyUtilities = TestUtils.mockCommonProxyUtilitiesForDashboardTesting(temporaryFolder);
Dashboard.setCommonProxyUtilities(proxyUtilities);
when(request.getParameter("action")).thenReturn("doCleanup");
dashboardCleanupServlet.doPost(request, response);
Assert.assertEquals("SUCCESS", response.getOutputStream().toString());
} finally {
Dashboard.restoreCommonProxyUtilities();
}
}
@Test
public void getDoReset() throws IOException {
try {
CommonProxyUtilities proxyUtilities = TestUtils.mockCommonProxyUtilitiesForDashboardTesting(temporaryFolder);
Dashboard.setCommonProxyUtilities(proxyUtilities);
when(request.getParameter("action")).thenReturn("doReset");
dashboardCleanupServlet.doGet(request, response);
Assert.assertEquals("SUCCESS", response.getOutputStream().toString());
} finally {
Dashboard.restoreCommonProxyUtilities();
}
}
@Test
public void postDoReset() throws IOException {
try {
CommonProxyUtilities proxyUtilities = TestUtils.mockCommonProxyUtilitiesForDashboardTesting(temporaryFolder);
Dashboard.setCommonProxyUtilities(proxyUtilities);
when(request.getParameter("action")).thenReturn("doReset");
dashboardCleanupServlet.doPost(request, response);
Assert.assertEquals("SUCCESS", response.getOutputStream().toString());
} finally {
Dashboard.restoreCommonProxyUtilities();
}
}
@Test
public void postMissingParameter() throws IOException {
dashboardCleanupServlet.doPost(request, response);
Assert.assertEquals("ERROR action not implemented. Given action=null", response.getOutputStream().toString());
}
@Test
public void postUnsupportedParameter() throws IOException {
when(request.getParameter("action")).thenReturn("anyValue");
dashboardCleanupServlet.doPost(request, response);
Assert.assertEquals("ERROR action not implemented. Given action=anyValue",
response.getOutputStream().toString());
}
}
| true
|
5b76f25fa076478e6ca94d758d029d9f1d32a376
|
Java
|
TeamParadise/M-O
|
/M-O/src/org/usfirst/frc/team1165/robot/subsystems/QuadEncoder.java
|
UTF-8
| 1,313
| 2.546875
| 3
|
[] |
no_license
|
package org.usfirst.frc.team1165.robot.subsystems;
import org.usfirst.frc.team1165.robot.RobotMap;
import org.usfirst.frc.team1165.robot.commands.ReportEncoder;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*/
public class QuadEncoder extends Subsystem
{
private Encoder encoder;
double distancePerTick = 6*Math.PI/360; //wheel diameter * pi / ticks per revolution
public QuadEncoder()
{
encoder = new Encoder(RobotMap.encoderChannelA, RobotMap.encoderChannelB, false, EncodingType.k4X );
reset();
}
public void initDefaultCommand()
{
setDefaultCommand(new ReportEncoder());
}
public void report()
{
SmartDashboard.putNumber("Encoder Distance", getInches());
SmartDashboard.putNumber("Encoder Ticks", encoder.get());
}
public double getInches()
{
return distancePerTick*getTicks();
}
public double getStrafeInches()
{
double strafePerTick = distancePerTick/3;
return strafePerTick*getTicks();
}
public double getTicks()
{
return encoder.get();
}
public void reset()
{
encoder.reset();
}
}
| true
|
f805a343500930c6daf0c006acedce86bb31f98b
|
Java
|
rajashree/Catalog
|
/Dell_Mercurial/mv_dell_acs/sn_lib/sn_core_services/event/src/main/java/com/sourcen/core/event/executor/AbstractEventExecutor.java
|
UTF-8
| 814
| 2.265625
| 2
|
[] |
no_license
|
/*
* Copyright(C) 2011, Sourcen Framework and the original authors.
* All Rights Reserved. Use is subject to license terms and conditions.
*/
package com.sourcen.core.event.executor;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Navin Raj Kumar G.S.
* @author $LastChangedBy: navinr $
* @version $Revision: 2705 $, $Date:: 2012-05-29 10:26:39#$
*/
abstract class AbstractEventExecutor implements EventExecutor {
protected Object result = null;
protected Integer priority = 0;
private final AtomicBoolean isExecuted = new AtomicBoolean(false);
@Override
public final Object call() {
synchronized (isExecuted) {
if (!isExecuted.get()) {
this.run();
isExecuted.set(true);
}
}
return result;
}
}
| true
|
b9425401002482ec38d9a92d9c7bb587ae226284
|
Java
|
zhushh/sysu-java
|
/stage3/part1/myImage/IImageIO.java
|
UTF-8
| 2,884
| 2.765625
| 3
|
[] |
no_license
|
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class IImageIO implements imagereader.IImageIO
{
// to-do
public Image myRead(String s) throws IOException
{
// to-do
Image image;
FileInputStream finput = new FileInputStream(s);
// start reading
int headSize = 14;
int imageInfo = 40;
byte[] header = new byte[headSize];
byte[] info = new byte[imageInfo];
finput.read(header, 0, headSize);
finput.read(info, 0, imageInfo);
int imgWidth = changeInt(info, 7);
int imgHeight = changeInt(info, 11);
int imgBitCount = (((int) info[15] & 0xff) << 8) | (int) info[14] & 0xff;
int imgDataSize = changeInt(info, 23);
if (imgDataSize == 0) { // calculate the image size
imgDataSize = ((((imgWidth * imgBitCount) + 31) & ~31) >> 3);
imgDataSize *= imgHeight;
}
int imgPad = (imgDataSize / imgHeight) - imgWidth * (imgBitCount / 8);
int[] imgData = new int[imgWidth * imgHeight];
byte[] imgBrgbs = new byte[(imgWidth + imgPad) * (imgBitCount / 8) * imgHeight];
finput.read(imgBrgbs, 0, (imgWidth + imgPad) * (imgBitCount/8) * imgHeight);
int nindex = 0;
for (int j = 0; j < imgHeight; j++) {
for (int i = 0; i < imgWidth; i++) {
imgData[imgWidth * (imgHeight - j - 1) + i] = ((255 & 0xff) << 24)
| (((int) imgBrgbs[nindex + 2] & 0xff) << 16)
| (((int) imgBrgbs[nindex + 1] & 0xff) << 8)
| ((int) imgBrgbs[nindex] & 0xff);
nindex += (imgBitCount / 8);
}
nindex += imgPad;
}
// finish reading
finput.close();
image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(imgWidth, imgHeight, imgData, 0, imgWidth));
return image;
}
public Image myWrite(Image image, String s) throws IOException
{
int imgWidth = image.getWidth(null);
int imgHeight = image.getHeight(null);
File foutput = new File(s);
BufferedImage bfImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_BGR);
bfImage.getGraphics().drawImage(image, 0, 0, imgWidth, imgHeight, null);
ImageIO.write(bfImage, "bmp", foutput);
return image;
}
public int changeInt(byte[] bi, int start){
return (((int)bi[start]&0xff)<<24)
| (((int)bi[start-1]&0xff)<<16)
| (((int)bi[start-2]&0xff)<<8)
| ((int)bi[start-3]&0xff);
}
}
| true
|
5240d3190dc7cb982177975e7060a2e975c386bd
|
Java
|
ericbinxi/projects
|
/mod_office/src/main/java/cn/com/mod/office/lightman/entity/LedInfo.java
|
UTF-8
| 758
| 2.078125
| 2
|
[] |
no_license
|
package cn.com.mod.office.lightman.entity;
/**
* Created by CAT on 2014/9/23.
*/
public class LedInfo {
// 在线
public static final int STATUS_ONLINE = 1;
// 不在线
public static final int STATUS_OFFLINE = 0;
// 故障
public static final int STATUS_WRONG = 0;
// 落地灯
public static final int TYPE_FLOOR_LAMP = 0;
// 洗墙灯
public static final int TYPE_WALL_WASHER = 1;
// 线条灯
public static final int TYPE_LINE_LAMP = 2;
// 双头格栅灯
public static final int TYPE_DOUBLE_GRILLE_LAMP = 3;
// 射灯
public static final int TYPE_SPOT_LAMP = 4;
public String ledId;
public int status;
public int type;
public int positionX;
public int positionY;
}
| true
|
26e2d2734b97f91047534d03edde841b14666c15
|
Java
|
GuilhRibas/DevJavaAndroidstudio
|
/aula4_cliente/MainCliente.java
|
UTF-8
| 515
| 2.78125
| 3
|
[] |
no_license
|
package aula4_cliente;
import java.util.Scanner;
public class MainCliente {
public static void main(String[]args){
Scanner ler = new Scanner(System.in);
Aula4_cliente a1 = new Aula4_cliente();
System.out.println("Digite seu nome: ");
a1.setNome(ler.nextLine());
System.out.println("Digite sua idade: ");
a1.setIdade(ler.nextInt());
System.out.println("Digite sua renda: ");
a1.setRenda(ler.nextDouble());
System.out.println(a1);
}
}
| true
|
65fe125265de384aea03193a3185d21900fff48c
|
Java
|
RDCooter/SEIS-610-Fall-2014
|
/src/edu/stthomas/seis610/tree/GeneticProgrammingTree.java
|
UTF-8
| 4,690
| 2.859375
| 3
|
[] |
no_license
|
package edu.stthomas.seis610.tree;
import java.util.Vector;
import edu.stthomas.seis610.gp.FitnessDatum;
import edu.stthomas.seis610.gp.GPSettings;
import edu.stthomas.seis610.gp.TrainingData;
import edu.stthomas.seis610.tree.BinaryTreeNode.NodeType;
import edu.stthomas.seis610.util.GPException;
public class GeneticProgrammingTree extends BinaryTree implements Comparable<GeneticProgrammingTree> {
protected FitnessDatum xFitness = new FitnessDatum();
protected Vector<TrainingData> xTrainingData;
public GeneticProgrammingTree() {
}
public GeneticProgrammingTree(BinaryTreeNode aNode) {
setRoot(aNode);
}
public GeneticProgrammingTree(Vector<TrainingData> aTrainingData) {
setTrainingData(aTrainingData);
}
/**
* @return the fitness measurement datum associated with this binary tree
*/
public FitnessDatum getFitness() {
return xFitness;
}
/**
* @param aValue the fitness measurement datum that represents the new fitness measurement
*/
public void setFitness(FitnessDatum aValue) {
this.xFitness = aValue;
}
/**
* @return the list of training data values to use for this GP tree
*/
public Vector<TrainingData> getTrainingData() {
return xTrainingData;
}
/**
* @param aTrainingData the training data values to assign for this GP tree
*/
public void setTrainingData(Vector<TrainingData> aTrainingData) {
this.xTrainingData = aTrainingData;
}
/**
* Resets all of the cached instance variables.
*/
public void reset() {
getRoot().resetTreeNodeInvalid();
xFitness.reset();
}
/**
* A recursive way to evaluate the function represented by this tree.
*
* @param aTrainingDatum the input training values (X and Y) of the target (perfect) function
* @return the fitness measurement result of the expression based upon the passed in input value
* @throws GPException
*/
public Double calculateFitness() {
xFitness.clear();
for (TrainingData trainingDatum : getTrainingData()) {
try {
xFitness.add(FitnessDatum.calculateStandardizedFitness(trainingDatum, evaluate(trainingDatum)));
} catch (GPException e) {
// When an error occurs during the evaluation, then simply add in the biggest standardized fitness value
// into the datum.
xFitness.add(new FitnessDatum(Double.MAX_VALUE));
System.out.println("ERROR: <BinaryTree::evaluate> x=" + trainingDatum.getInputData()
+ " BinaryTreeNode=" + this.toString());
e.printStackTrace();
}
}
return xFitness.getValue();
}
/**
* Selects a random tree node from the expression tree and mutates that node into a newly generated subtree that is
* in turn spliced back into existing tree.
*
* @throws GPException
*/
public void mutate() throws GPException {
// Randomly select an individual node from anywhere within the expression tree as the target for mutation.
BinaryTreeNode existingSubtreeNode = getRandomTreeNode();
// Randomly determine the height of the new mutation subtree that will be spliced into the existing expression
// node tree.
Integer newSubtreeHeight = GPSettings.getRandomInt(GPSettings.getMaxHtOfMutationSubtree()) + 1;
// Invoke the factory to generate a new subtree based upon our random height.
BinaryTreeNode newSubtreeRoot = GPTreeFactory.generateGrowSubtree(newSubtreeHeight);
// Determine if the randomly selected node to be mutated was the top or root node of the existing tree. If so,
// then simply replace the entire expression node with the newly generated one and be done with it.
if (existingSubtreeNode.getNodeType() == NodeType.ROOT || existingSubtreeNode.getParent() == null) {
this.setRoot(newSubtreeRoot);
} else {
// Otherwise, splice the newly generated subtree into the existing expression node tree and fix up the node
// types, parent and child references.
BinaryTreeNode subtreeParent = existingSubtreeNode.getParent();
newSubtreeRoot.setParent(subtreeParent);
if (existingSubtreeNode.getNodeType() == NodeType.LEFT) {
subtreeParent.setLeftChild(newSubtreeRoot);
newSubtreeRoot.setNodeType(NodeType.LEFT);
} else {
subtreeParent.setRightChild(newSubtreeRoot);
newSubtreeRoot.setNodeType(NodeType.RIGHT);
}
}
// Reset the cached information stored about this expression node tree since we have modified it and it may no
// longer be valid.
this.reset();
}
@Override
public Object clone() {
GeneticProgrammingTree newClone = (GeneticProgrammingTree) super.clone();
newClone.setFitness((FitnessDatum) getFitness().clone());
return newClone;
}
@Override
public int compareTo(GeneticProgrammingTree otherGPT) {
return this.getFitness().compareTo(otherGPT.getFitness());
}
}
| true
|
0f4fd64e88be66626206fe96b2874c386556227e
|
Java
|
Afsana-hussain1/Afsana_Hussain_Java_S1
|
/2019-10-08/src/test/java/com/company/PhysicsLibraryTest.java
|
UTF-8
| 3,987
| 2.90625
| 3
|
[] |
no_license
|
package com.company;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class PhysicsLibraryTest {
PhysicsLibrary physicsLibrary;
@Before
public void setUp() {
physicsLibrary = new PhysicsLibrary();
}
@Test
public void shouldFindForceOfTwoPositiveDoubles() {
assertEquals(200d, physicsLibrary.calculateForce(10.0d, 20.0d), .1d);
assertEquals(33d, physicsLibrary.calculateForce(5.5d, 6d), .1d);
assertEquals(85.25d, physicsLibrary.calculateForce(15.5d, 5.5d), .1d);
}
@Test
public void shouldFindForceOfOnePositiveOneNegativeDouble() {
assertEquals(-200, physicsLibrary.calculateForce(-10.0, 20.0), .1d);
assertEquals(-33, physicsLibrary.calculateForce(5.5, -6), .1d);
assertEquals(-85.25, physicsLibrary.calculateForce(-15.5, 5.5), .1d);
}
@Test
public void shouldFindForceOfTwoNegativeDoubles() {
assertEquals(200, physicsLibrary.calculateForce(-10.0, -20.0), .1d);
assertEquals(33, physicsLibrary.calculateForce(-5.5, -6), .1d);
assertEquals(85.25, physicsLibrary.calculateForce(-15.5, -5.5), .1d);
}
@Test
public void shouldFindVelocityWithPositiveDoubles() {
assertEquals(1.666666666666667, physicsLibrary.calculateVelocity(10.1, 20.1, 3.1, 9.1), .1);
assertEquals(5.0, physicsLibrary.calculateVelocity(20.1, 40.1, 6.1, 10.1), .1);
assertEquals(2.9999999999999996, physicsLibrary.calculateVelocity(30.1, 60.1, 10.1, 20.1), .1);
}
@Test
public void shouldFindVelocityWithNegativeDoubles() {
assertEquals(1.666666666666667, physicsLibrary.calculateVelocity(-10.1, -20.1, -3.1, -9.1), .1);
assertEquals(-3.71604938271605, physicsLibrary.calculateVelocity(20.1, -40.1, -6.1, 10.1), .1);
assertEquals(-2.9999999999999996, physicsLibrary.calculateVelocity(-30.1, -60.1, 10.1, 20.1), .1);
}
@Test
public void shouldFindMassTwoPositiveDoubles() {
assertEquals(4, physicsLibrary.calculateMass(20.1, 5.1), .1d);
assertEquals(6, physicsLibrary.calculateMass(30.1, 5.1), .1d);
assertEquals(7.862745098039216, physicsLibrary.calculateMass(40.1, 5.1), .1d);
}
@Test
public void shouldFindMassTwoNegativeDoubles() {
assertEquals(4, physicsLibrary.calculateMass(-20.1, -5.1), .1d);
assertEquals(6, physicsLibrary.calculateMass(-30.1, -5.1), .1d);
assertEquals(7.862745098039216, physicsLibrary.calculateMass(-40.1, -5.1), .1d);
}
@Test
public void shouldFindMassOneNegativeOnePositiveDoubles() {
assertEquals(4, physicsLibrary.calculateMass(-20.1, -5.1), .1d);
assertEquals(6, physicsLibrary.calculateMass(-30.1, -5.1), .1d);
assertEquals(7.862745098039216, physicsLibrary.calculateMass(-40.1, -5.1), .1d);
}
@Test
public void shouldFindAccelerationWithPositiveDoubles() {
assertEquals(2.0, physicsLibrary.calculateAcceleration(20.1, 40.1, 40.1, 30.1), .1);
assertEquals(2.0, physicsLibrary.calculateAcceleration(70.1, 30.1, 10.1, 30.1), .1);
assertEquals(2.4999999999999996, physicsLibrary.calculateAcceleration(80.1, 30.1, 10.1, 30.1), .1);
}
@Test
public void shouldFindAccelerationWithNegativeDoubles() {
assertEquals(2.0, physicsLibrary.calculateAcceleration(-20.1, -40.1, -40.1, -30.1), .1);
assertEquals(2.0, physicsLibrary.calculateAcceleration(-70.1, -30.1, -10.1, -30.1), .1);
assertEquals(-1.2437810945273629, physicsLibrary.calculateAcceleration(-80.1, -30.1, -10.1, 30.1), .1);
}
@Test
public void shouldFindDistanceTwoPositiveDoubles(){
assertEquals (20.5,physicsLibrary.calculateDistance(4.1,5),.1d);
assertEquals (25.5,physicsLibrary.calculateDistance(5.1,5),.1d);
assertEquals (30.5,physicsLibrary.calculateDistance(6.1,5),.1d);
}
@Test
public void shouldFindDistanceTwoNegativeDoubles(){
assertEquals (20.5,physicsLibrary.calculateDistance(-4.1,-5),.1d);
assertEquals (25.5,physicsLibrary.calculateDistance(-5.1,-5),.1d);
assertEquals (30.5,physicsLibrary.calculateDistance(-6.1,-5),.1d);
}
}
| true
|
d3a705228e14e2c33bc2529ec28955e24673e731
|
Java
|
lilingxiaofei/AndroidWolf
|
/app/src/main/java/com/chunlangjiu/app/amain/adapter/SecondClassAdapter.java
|
UTF-8
| 4,859
| 2.1875
| 2
|
[] |
no_license
|
package com.chunlangjiu.app.amain.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.chunlangjiu.app.R;
import com.chunlangjiu.app.amain.bean.SecondClassBean;
import com.chunlangjiu.app.amain.bean.ThirdClassBean;
import com.pkqup.commonlibrary.glide.GlideUtils;
import com.pkqup.commonlibrary.util.SizeUtils;
import com.pkqup.commonlibrary.view.MyGridView;
import java.util.List;
/**
* @CreatedbBy: liucun on 2018/8/6
* @Describe:
*/
public class SecondClassAdapter extends BaseExpandableListAdapter {
private Context context;
private List<SecondClassBean> lists;
private CallBack callBack;
public SecondClassAdapter(Context context, List<SecondClassBean> lists) {
this.context = context;
this.lists = lists;
}
public void setLists(List<SecondClassBean> lists) {
this.lists = lists;
notifyDataSetChanged();
}
public interface CallBack {
void onSubClick(int groupPosition, int subPosition);
}
public void setCallBackListener(CallBack callBack) {
this.callBack = callBack;
}
@Override
public int getGroupCount() {
return lists.size();
}
@Override
public Object getGroup(int groupPosition) {
return lists.get(groupPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.amain_item_second_class, null);
TextView tvName = convertView.findViewById(R.id.tvName);
tvName.setText(lists.get(groupPosition).getCat_name());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return 1;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return lists.get(groupPosition).getLv3();
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.amain_item_third_class, null);
MyGridView myGridView = convertView.findViewById(R.id.gridView);
SubGridAdapter subGridAdapter = new SubGridAdapter(lists.get(groupPosition).getLv3(), groupPosition);
myGridView.setAdapter(subGridAdapter);
myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != callBack) {
callBack.onSubClick(groupPosition, position);
}
}
});
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public class SubGridAdapter extends BaseAdapter {
private List<ThirdClassBean> lists;
private int groupPosition;
public SubGridAdapter(List<ThirdClassBean> lists, int groupPosition) {
this.lists = lists;
this.groupPosition = groupPosition;
}
@Override
public int getCount() {
return lists.size();
}
@Override
public Object getItem(int position) {
return lists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.amain_item_sub_third_class, null);
ImageView imgPic = convertView.findViewById(R.id.img_pic);
TextView tvName = convertView.findViewById(R.id.tv_name);
ViewGroup.LayoutParams layoutParams = imgPic.getLayoutParams();
int screenWidth = SizeUtils.getScreenWidth();
int picWidth = (screenWidth - SizeUtils.dp2px(130)) / 3;
layoutParams.height = picWidth;
layoutParams.width = picWidth;
imgPic.setLayoutParams(layoutParams);
tvName.setText(lists.get(position).getCat_name());
GlideUtils.loadImage(context, lists.get(position).getCat_logo(), imgPic);
return convertView;
}
}
}
| true
|
6d4d90131b7dcea0ef1782c38b1a8f14bdaf2aba
|
Java
|
F-WJ/java_practice
|
/项目/项目一/RBAC/src/test/java/DepartmentSerivceText.java
|
UTF-8
| 1,574
| 2.03125
| 2
|
[] |
no_license
|
import cn.wolfcode.ssm.domain.Department;
import cn.wolfcode.ssm.mapper.DepartmentMapper;
import cn.wolfcode.ssm.qo.PageResult;
import cn.wolfcode.ssm.qo.QueryObject;
import cn.wolfcode.ssm.serivce.IDepartmentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DepartmentSerivceText {
@Autowired
private IDepartmentService departmentService;
@Autowired
private DepartmentMapper departmentMapper;
@Test
public void testDepartmentSerice(){
System.out.println(departmentMapper);
Department department = departmentService.get(1L);
List<Department> all = departmentService.getAll();
System.out.println(all);
System.out.println(department);
}
@Test
public void testPage(){
System.out.println(departmentMapper);
Department department = departmentService.get(1L);
List<Department> all = departmentService.getAll();
System.out.println(all);
System.out.println(department);
}
//测试pageresult结果
@Test
public void test2(){
//
QueryObject qo = new QueryObject();
PageResult pageResult = departmentService.query(qo);
System.out.println(pageResult);
}
}
| true
|
893ac333c4f463d0ce9da1a7ecffc622a18a0ac4
|
Java
|
XudongYu1125/JIANCAN
|
/客户端/Message/java/message/ChatRecordActivity.java
|
UTF-8
| 9,102
| 2.046875
| 2
|
[] |
no_license
|
package com.example.user.jiancan.message.activityAndFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.user.jiancan.R;
import com.example.user.jiancan.User;
import com.example.user.jiancan.message.util.ChatRecordAdapter;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ChatRecordActivity extends AppCompatActivity {
private List<Map<String, Object>> dataSource = new ArrayList<>();
private ListView listView;
private ChatRecordAdapter chatRecordAdapter = null;
private TextView textView;
private EditText et;
private String input;
private User user;
private ImageView imageView;
/// private OkHttpClient okHttpClient;
private SharedPreferences sharedPreferences;
Map<String, Object> map1 = new HashMap<>();
int i = 0;
int[] img = {R.drawable.back, R.drawable.back, R.drawable.back};
String[] content = {"结界,我明天上班想吃大盘鸡,整个教程", "谢谢你啦", "11"};
// 0->i 1->u
int[] who = {1, 1, 1};
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("213", msg.what + "");
switch (msg.what) {
case 0:
chatRecordAdapter = new ChatRecordAdapter(com.example.user.jiancan.message.activityAndFragment.ChatRecordActivity.this, dataSource, R.layout.message_talk);
listView.setAdapter(chatRecordAdapter);
break;
case 1:
break;
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_talk);
//去除标题栏
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
/*
okHttpClient = new OkHttpClient();
sharedPreferences = getActivity().getSharedPreferences("loginInfo", MODE_PRIVATE);
Gson gson = new GsonBuilder().serializeNulls() .create();
user = gson.fromJson(sharedPreferences.getString("user", null), User.class);
*/
textView = findViewById(R.id.tv_about);
textView.setText("郜三");
initDatalv1();
listView = findViewById(R.id.con_lv);
}
private void initDatalv1() {
dataSource = new ArrayList<>();
for (i = 0; i < img.length; ++i) {
Map<String, Object> map = new HashMap<>();
map.put("img", img[i]);
map.put("who", who[i]);
map.put("content", content[i]);
dataSource.add(map);
}
Message message = new Message();
message.what = 0;
handler.sendMessage(message);
}
private void initDatalv() {
}
public void send1(View view) {
et = findViewById(R.id.con_et);
input = et.getText().toString();
if (input.equals("")) {
Toast.makeText(ChatRecordActivity.this, "发送内容不能为空", Toast.LENGTH_SHORT).show();
return;
}
map1.put("img", R.drawable.oop);
map1.put("who", 0);
map1.put("content", input);
chatRecordAdapter.addItem(map1);
}
//发送消息
/* public void send(View view) {
//发送消息
Log.e("send", "aa");
et = findViewById(R.id.con_et);
input = et.getText().toString();
if (input.equals("")) {
Toast.makeText(.this, "发送内容不能为空", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
ChatRecord chatrecord = new ChatRecord();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
Date dt = new Date();
String date = sdf.format(dt.getTime());
Log.e("时间哦", date);
chatrecord.setContent(input);
chatrecord.setDate(date);
chatrecord.setSenderid(user.getUserid());
chatrecord.setReceiverid(recevieid);
chatrecord.setUUID(uuid);
try {
URL url = new URL(Constant.URL_CHAT_LOCAL + "Add");
//获得连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
conn.getOutputStream().write(gson.toJson(chatrecord).getBytes("UTF-8"));
conn.getOutputStream().flush();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[2048];
int len;
StringBuffer stringBuffer = new StringBuffer();
while ((len = inputStream.read(buffer)) != -1) {
stringBuffer.append(new String(buffer, 0, len));
}
JSONObject response = new JSONObject(stringBuffer.toString());
boolean bl = (Boolean) response.get("isSuccess");
Log.e("成功", bl + "");
if (bl == true) {
Log.e("成功", bl + "");
if (uuid == 0) {
uuid = Integer.parseInt((String) response.get("UUID"));
Log.e("uud=的id", "" + uuid);
chatrecord.setUUID(uuid);
}
String strid = (String) response.get("chatRecordId");
int crid = Integer.parseInt(strid);
chatrecord.setChatrecordid(crid);
newid = crid;
Log.e("这是新的chatrecordid", String.valueOf(newid));
Bundle bundle = new Bundle();
Message msg = new Message();
msg.what = 2;
bundle.putSerializable("ChatRecord", (Serializable) chatrecord);
msg.setData(bundle);
handler.sendMessage(msg);
} else {
Log.e("12321321321", "2");
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}
inputStream.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}*/
public void sendemoji(View view) {
//表情
}
// 查看个人信息
public void toself(View view) {
Intent it1 = new Intent();
it1.setClass(com.example.user.jiancan.message.activityAndFragment.ChatRecordActivity.this, SelfActivity.class);
// 判断点击的是sender还是receiver 传递id
switch (view.getId()) {
case R.id.con_imgi:
it1.putExtra("userid", 1);
break;
case R.id.con_imgu:
it1.putExtra("userid", 2);
break;
}
startActivity(it1);
}
// 返回时向MessageActivity传递数据
@Override
public void onBackPressed() {
Intent i = new Intent();
Log.e("返回事件", "123");
String content = "1231";
String date = "1232";
int id = 123;
/*
for (int j = 0; j < dataSource.size(); j++) {
if (dataSource.get(j).getChatrecordid() == newid) {
content = dataSource.get(j).getContent();
date = dataSource.get(j).getDate();
id = dataSource.get(j).getUUID();
}
}
i.putExtra("content", content);
i.putExtra("date", date);
i.putExtra("UUID", id);
*/
ChatRecordActivity.this.setResult(1, i);
ChatRecordActivity.this.finish();
}
}
| true
|
752c1d46bc00c5217cf064091a70b84317ca5c3a
|
Java
|
masole523/Banking_application
|
/banking-application-project/src/main/java/com/revature/daos/EmployeeDAO.java
|
UTF-8
| 151
| 1.828125
| 2
|
[] |
no_license
|
package com.revature.daos;
import com.revature.models.*;
public interface EmployeeDAO {
public Employee getEmployee(String userName);
}
| true
|
3d70fc518f13c13806c956b125266ab0871225aa
|
Java
|
marschall/serialization-experiments
|
/src/main/java/com/github/marschall/serialization/context/OnlineProcessingDateTO.java
|
UTF-8
| 1,835
| 2.65625
| 3
|
[] |
no_license
|
package com.github.marschall.serialization.context;
import java.util.Date;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public final class OnlineProcessingDateTO extends AbstractTransferObject implements IOnlineProcessingDateProvider {
private final Date processingDate;
private final Date previousProcessingDate;
private final Date nextProcessingDate;
private final int hashCode;
public OnlineProcessingDateTO(Date processingDate, Date previousProcessingDate, Date nextProcessingDate) {
this.processingDate = processingDate;
this.previousProcessingDate = previousProcessingDate;
this.nextProcessingDate = nextProcessingDate;
// All fields are final, calculate hash code now
this.hashCode = new HashCodeBuilder(93, 49)
.append(processingDate)
.append(previousProcessingDate)
.append(nextProcessingDate)
.toHashCode();
}
public Date getProcessingDate() {
return this.processingDate;
}
public Date getPreviousProcessingDate() {
return this.previousProcessingDate;
}
public Date getNextProcessingDate() {
return this.nextProcessingDate;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof OnlineProcessingDateTO)) {
return false;
}
OnlineProcessingDateTO rhs = (OnlineProcessingDateTO) obj;
if (this.hashCode != rhs.hashCode) {
return false;
}
return new EqualsBuilder()
.append(this.processingDate, rhs.processingDate)
.append(this.previousProcessingDate, rhs.previousProcessingDate)
.append(this.nextProcessingDate, rhs.nextProcessingDate)
.isEquals();
}
@Override
public int hashCode() {
return this.hashCode;
}
}
| true
|