text
stringlengths 10
2.72M
|
|---|
package com.example.okta_cust_sign_in.util;
import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.example.okta_cust_sign_in.R;
import java.lang.ref.WeakReference;
public class OktaProgressDialog {
WeakReference<Context> mContext;
AlertDialog dialog;
public OktaProgressDialog(Context context) {
this.mContext = new WeakReference<>(context);
}
public void show() {
show(null);
}
public void show(String message) {
if(this.dialog == null) {
this.dialog = createAlertDialog(message);
}
if(this.dialog != null) {
dialog.show();
}
}
public void hide() {
if(this.dialog != null) {
dialog.cancel();
dialog = null;
}
}
private AlertDialog createAlertDialog(String message) {
if(mContext.get() != null) {
Context context = mContext.get();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false); // if you want user to wait for some process to finish,
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = mInflater.inflate(R.layout.layout_progress_dialog, null, false);
String textViewMessage = (message == null) ? "Please wait! This may take a moment." : message;
((TextView)view.findViewById(R.id.message_textview)).setText(textViewMessage);
builder.setView(R.layout.layout_progress_dialog);
return builder.create();
}
return null;
}
}
|
package com.beans;
import javax.ejb.Remote;
@Remote
public interface PaymentsServiceRemote {
boolean creditPayment(String token, int amount, String description);
}
|
package com.n2s.miniproject.pojo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.n2s.miniproject.core.databasecon;
/**
* Servlet implementation class AdminLogin
*/
@WebServlet("/AdminLogin")
public class AdminLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AdminLogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
Connection con;
con = databasecon.getconnection();
AdminRegisterPojo ad = new AdminRegisterPojo();
ad.setUname(request.getParameter("uname"));
ad.setPwd(request.getParameter("pwd"));
String uname = ad.getUname();
String password = ad.getPwd();
try {
PreparedStatement prep = con.prepareStatement("select name,password from register where name ='"+uname+"' and password = '"+password+"'");
ResultSet rs = prep.executeQuery();
if(rs.next()){
HttpSession sess = request.getSession(true);
sess.setAttribute("uname",uname);
response.sendRedirect("AdminConsole.jsp");
}else{
response.sendRedirect("Login.jsp?msg1=unsucc");
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class Power {
String name = "";
String cnt_in_effect;
String triggered;
String activated;
String expired;
String power_suspended;
String cnt_suspended;
String terminated;
String exerted;
String power_resumed;
String cnt_resumed;
String antecedent;
String pow;
Map<String, String> events = new HashMap<>();
Map<String, String> defines = new HashMap<>();
Power(String name){
this.name = name;
cnt_in_effect = "";
triggered = "";
activated = "";
expired = "";
power_suspended = "";
cnt_suspended = "";
terminated = "";
exerted = "";
power_resumed = "";
cnt_resumed = "";
antecedent = "";
}
public void generate() {
if(cnt_in_effect.trim().length()==0) {
cnt_in_effect = "TRUE";
}
if(triggered.trim().length()==0) {
events.put(this.name+"_triggered", "Event("+cnt_in_effect+");");
triggered = this.name+"_triggered._happened";
}
if(activated.trim().length()==0) {
events.put(this.name+"_activated", "Event("+this.name+".state=create);");
activated = this.name+"_activated._happened";
}
if(expired.trim().length()==0) {
events.put(this.name+"_expired", "Event("+this.name+".state=create);");
expired = this.name+"_expired._happened";
}
if(power_suspended.trim().length()==0) {
//events.put(this.name+"_power_suspended", "Event("+this.name+".state=inEffect);");
//power_suspended = this.name+"_power_suspended._happened";
power_suspended = "FALSE";
}
if(cnt_suspended.trim().length()==0) {
//events.put(this.name+"_cnt_suspended", "Event("+this.name+".state=inEffect);");
//cnt_suspended = this.name+"_cnt_suspended._happened";
cnt_suspended = "FALSE";
}
if(terminated.trim().length()==0) {
//events.put(this.name+"_terminated", "Event("+this.name+".state=inEffect);");
//terminated = this.name+"_terminated._happened";
terminated = "FALSE";
}
if(exerted.trim().length()==0) {
events.put(this.name+"_exerted", "Event("+this.name+".state=inEffect);");
exerted = this.name+"_exerted._happened";
}
if(power_resumed.trim().length()==0) {
//events.put(this.name+"_power_resumed", "Event("+this.name+".state=suspension);");
//power_resumed = this.name+"_power_resumed._happened";
power_resumed = "FALSE";
}
if (cnt_resumed.trim().length()==0) {
//events.put(this.name+"_cnt_resumed", "Event("+this.name+".state=suspension);");
//cnt_resumed = this.name+"_cnt_resumed._happened";
cnt_resumed = "FALSE";
}
if(antecedent.trim().length()==0) {
antecedent = "TRUE";
}
}
public void set_antecedent(String ant) {
antecedent = ant;
}
public void set_cnt_ineffect(String inef) {
cnt_in_effect = inef;
}
public void set_trigger(String trg) {
triggered = trg;
}
public String get() {
pow = "Power("+ cnt_in_effect + "," + triggered +","+ activated +",\r\n\t\t\t" +
expired +","+ power_suspended +","+ cnt_suspended +","+ terminated +",\r\n\t\t\t"+
exerted +","+ power_resumed + "," + cnt_resumed +","+ antecedent+");\n";
return "\t\t" + name + "\t:\t" + pow;
}
public String export_events() {
String list = "";
Iterator<Entry<String, String>> itr = events.entrySet().iterator();
while(itr.hasNext()) {
Map.Entry<String, String> event = itr.next();
list += "\t\t"+event.getKey() +"\t:\t"+event.getValue()+"\n";
};
return list;
}
}
|
package rafaxplayer.cheftools.stocks;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import rafaxplayer.cheftools.Globalclasses.BaseActivity;
import rafaxplayer.cheftools.Globalclasses.GlobalUttilities;
import rafaxplayer.cheftools.R;
import rafaxplayer.cheftools.products.fragments.ProductosMannager_Fragment;
import rafaxplayer.cheftools.stocks.fragment.StocksNewEdit_Fragment;
public class StocksNewEdit_Activity extends BaseActivity implements ProductosMannager_Fragment.OnSelectedCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, StocksNewEdit_Fragment.newInstance(getIntent().getIntExtra("id", 0)), "neweditstock")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
if (!GlobalUttilities.isScreenLarge(getApplicationContext())) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_template_for_all;
}
@Override
protected String getCustomTitle() {
return getString(R.string.activity_newedit_stocks);
}
@Override
public void onSelect(int pid) {
StocksNewEdit_Fragment fr = (StocksNewEdit_Fragment) getSupportFragmentManager().findFragmentByTag("neweditstock");
if (fr != null) {
fr.displayProductWithId(pid);
}
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.web.reactive.result.method.annotation;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Single;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.StringDecoder;
import org.springframework.http.HttpEntity;
import org.springframework.http.RequestEntity;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.testfixture.method.ResolvableMethod;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.http.MediaType.TEXT_PLAIN;
import static org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest.post;
/**
* Unit tests for {@link HttpEntityMethodArgumentResolver}.When adding a test also
* consider whether the logic under test is in a parent class, then see:
* {@link MessageReaderArgumentResolverTests}.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
*/
public class HttpEntityMethodArgumentResolverTests {
private final HttpEntityMethodArgumentResolver resolver = createResolver();
private final ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
private HttpEntityMethodArgumentResolver createResolver() {
List<HttpMessageReader<?>> readers = new ArrayList<>();
readers.add(new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
return new HttpEntityMethodArgumentResolver(readers, ReactiveAdapterRegistry.getSharedInstance());
}
@Test
public void supports() throws Exception {
testSupports(this.testMethod.arg(httpEntityType(String.class)));
testSupports(this.testMethod.arg(httpEntityType(Mono.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(Single.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(Maybe.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(CompletableFuture.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(Flux.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(Observable.class, String.class)));
testSupports(this.testMethod.arg(httpEntityType(Flowable.class, String.class)));
testSupports(this.testMethod.arg(forClassWithGenerics(RequestEntity.class, String.class)));
}
private void testSupports(MethodParameter parameter) {
assertThat(this.resolver.supportsParameter(parameter)).isTrue();
}
@Test
public void doesNotSupport() {
assertThat(this.resolver.supportsParameter(this.testMethod.arg(Mono.class, String.class))).isFalse();
assertThat(this.resolver.supportsParameter(this.testMethod.arg(String.class))).isFalse();
assertThatIllegalStateException().isThrownBy(() ->
this.resolver.supportsParameter(this.testMethod.arg(Mono.class, httpEntityType(String.class))))
.withMessageStartingWith("HttpEntityMethodArgumentResolver does not support reactive type wrapper");
}
@Test
public void emptyBodyWithString() {
ResolvableType type = httpEntityType(String.class);
HttpEntity<Object> entity = resolveValueWithEmptyBody(type);
assertThat(entity.getBody()).isNull();
}
@Test
public void emptyBodyWithMono() {
ResolvableType type = httpEntityType(Mono.class, String.class);
HttpEntity<Mono<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody()).expectNextCount(0).expectComplete().verify();
}
@Test
public void emptyBodyWithFlux() {
ResolvableType type = httpEntityType(Flux.class, String.class);
HttpEntity<Flux<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody()).expectNextCount(0).expectComplete().verify();
}
@Test
public void emptyBodyWithSingle() {
ResolvableType type = httpEntityType(Single.class, String.class);
HttpEntity<Single<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody().toFlowable())
.expectNextCount(0)
.expectError(ServerWebInputException.class)
.verify();
}
@Test
public void emptyBodyWithMaybe() {
ResolvableType type = httpEntityType(Maybe.class, String.class);
HttpEntity<Maybe<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody().toFlowable())
.expectNextCount(0)
.expectComplete()
.verify();
}
@Test
public void emptyBodyWithObservable() {
ResolvableType type = httpEntityType(Observable.class, String.class);
HttpEntity<Observable<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody().toFlowable(BackpressureStrategy.BUFFER))
.expectNextCount(0)
.expectComplete()
.verify();
}
@Test
public void emptyBodyWithFlowable() {
ResolvableType type = httpEntityType(Flowable.class, String.class);
HttpEntity<Flowable<String>> entity = resolveValueWithEmptyBody(type);
StepVerifier.create(entity.getBody())
.expectNextCount(0)
.expectComplete()
.verify();
}
@Test
public void emptyBodyWithCompletableFuture() {
ResolvableType type = httpEntityType(CompletableFuture.class, String.class);
HttpEntity<CompletableFuture<String>> entity = resolveValueWithEmptyBody(type);
entity.getBody().whenComplete((body, ex) -> {
assertThat(body).isNull();
assertThat(ex).isNull();
});
}
@Test
public void httpEntityWithStringBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(String.class);
HttpEntity<String> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(httpEntity.getBody()).isEqualTo("line1");
}
@Test
public void httpEntityWithMonoBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Mono.class, String.class);
HttpEntity<Mono<String>> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(httpEntity.getBody().block()).isEqualTo("line1");
}
@Test
public void httpEntityWithSingleBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Single.class, String.class);
HttpEntity<Single<String>> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(httpEntity.getBody().blockingGet()).isEqualTo("line1");
}
@Test
public void httpEntityWithMaybeBody() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Maybe.class, String.class);
HttpEntity<Maybe<String>> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(httpEntity.getBody().blockingGet()).isEqualTo("line1");
}
@Test
public void httpEntityWithCompletableFutureBody() throws Exception {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(CompletableFuture.class, String.class);
HttpEntity<CompletableFuture<String>> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(httpEntity.getBody().get()).isEqualTo("line1");
}
@Test
public void httpEntityWithFluxBody() {
ServerWebExchange exchange = postExchange("line1\nline2\nline3\n");
ResolvableType type = httpEntityType(Flux.class, String.class);
HttpEntity<Flux<String>> httpEntity = resolveValue(exchange, type);
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
StepVerifier.create(httpEntity.getBody())
.expectNext("line1")
.expectNext("line2")
.expectNext("line3")
.expectComplete()
.verify();
}
@Test
public void requestEntity() {
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = forClassWithGenerics(RequestEntity.class, String.class);
RequestEntity<String> requestEntity = resolveValue(exchange, type);
assertThat(requestEntity.getMethod()).isEqualTo(exchange.getRequest().getMethod());
assertThat(requestEntity.getUrl()).isEqualTo(exchange.getRequest().getURI());
assertThat(requestEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
assertThat(requestEntity.getBody()).isEqualTo("line1");
}
private MockServerWebExchange postExchange(String body) {
return MockServerWebExchange.from(post("/path").header("foo", "bar").contentType(TEXT_PLAIN).body(body));
}
private ResolvableType httpEntityType(Class<?> bodyType, Class<?>... generics) {
return ResolvableType.forClassWithGenerics(HttpEntity.class,
ObjectUtils.isEmpty(generics) ?
ResolvableType.forClass(bodyType) :
ResolvableType.forClassWithGenerics(bodyType, generics));
}
@SuppressWarnings("unchecked")
private <T> T resolveValue(ServerWebExchange exchange, ResolvableType type) {
MethodParameter param = this.testMethod.arg(type);
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
Object value = result.block(Duration.ofSeconds(5));
assertThat(value).isNotNull();
assertThat(param.getParameterType().isAssignableFrom(value.getClass())).as("Unexpected return value type: " + value.getClass()).isTrue();
return (T) value;
}
@SuppressWarnings("unchecked")
private <T> HttpEntity<T> resolveValueWithEmptyBody(ResolvableType type) {
ServerWebExchange exchange = MockServerWebExchange.from(post("/path"));
MethodParameter param = this.testMethod.arg(type);
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
HttpEntity<String> httpEntity = (HttpEntity<String>) result.block(Duration.ofSeconds(5));
assertThat(httpEntity.getHeaders()).isEqualTo(exchange.getRequest().getHeaders());
return (HttpEntity<T>) httpEntity;
}
@SuppressWarnings("unused")
void handle(
String string,
Mono<String> monoString,
HttpEntity<String> httpEntity,
HttpEntity<Mono<String>> monoBody,
HttpEntity<Flux<String>> fluxBody,
HttpEntity<Single<String>> singleBody,
HttpEntity<Maybe<String>> maybeBody,
HttpEntity<Observable<String>> observableBody,
HttpEntity<Flowable<String>> flowableBody,
HttpEntity<CompletableFuture<String>> completableFutureBody,
RequestEntity<String> requestEntity,
Mono<HttpEntity<String>> httpEntityMono) {}
}
|
package command.dining;
import org.springframework.web.multipart.MultipartFile;
public class MenuCommand {
Long menuNo;
Long rstNo;
String menuName;
Long menuPrice;
String menuCnt;
MultipartFile [] menuImg;
public Long getMenuNo() {
return menuNo;
}
public void setMenuNo(Long menuNo) {
this.menuNo = menuNo;
}
public Long getRstNo() {
return rstNo;
}
public void setRstNo(Long rstNo) {
this.rstNo = rstNo;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public Long getMenuPrice() {
return menuPrice;
}
public void setMenuPrice(Long menuPrice) {
this.menuPrice = menuPrice;
}
public String getMenuCnt() {
return menuCnt;
}
public void setMenuCnt(String menuCnt) {
this.menuCnt = menuCnt;
}
public MultipartFile[] getMenuImg() {
return menuImg;
}
public void setMenuImg(MultipartFile[] menuImg) {
this.menuImg = menuImg;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.beans.factory.support;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.core.io.AbstractResource;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Descriptive {@link org.springframework.core.io.Resource} wrapper for
* a {@link org.springframework.beans.factory.config.BeanDefinition}.
*
* @author Juergen Hoeller
* @since 2.5.2
* @see org.springframework.core.io.DescriptiveResource
*/
class BeanDefinitionResource extends AbstractResource {
private final BeanDefinition beanDefinition;
/**
* Create a new BeanDefinitionResource.
* @param beanDefinition the BeanDefinition object to wrap
*/
public BeanDefinitionResource(BeanDefinition beanDefinition) {
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
this.beanDefinition = beanDefinition;
}
/**
* Return the wrapped BeanDefinition object.
*/
public final BeanDefinition getBeanDefinition() {
return this.beanDefinition;
}
@Override
public boolean exists() {
return false;
}
@Override
public boolean isReadable() {
return false;
}
@Override
public InputStream getInputStream() throws IOException {
throw new FileNotFoundException(
"Resource cannot be opened because it points to " + getDescription());
}
@Override
public String getDescription() {
return "BeanDefinition defined in " + this.beanDefinition.getResourceDescription();
}
/**
* This implementation compares the underlying BeanDefinition.
*/
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof BeanDefinitionResource that &&
this.beanDefinition.equals(that.beanDefinition)));
}
/**
* This implementation returns the hash code of the underlying BeanDefinition.
*/
@Override
public int hashCode() {
return this.beanDefinition.hashCode();
}
}
|
package com._520it.wms.service;
import com._520it.wms.domain.OrderBill;
import com._520it.wms.domain.StockIncomeBill;
import com._520it.wms.page.PageResult;
import com._520it.wms.query.OrderBillQueryObject;
import com._520it.wms.query.StockIncomeBillQueryObject;
public interface IStockIncomeBillService {
void delete(Long id);
void save(StockIncomeBill entity);
StockIncomeBill get(Long id);
void update(StockIncomeBill entity);
PageResult pageQuery(StockIncomeBillQueryObject qo);
/**
* 到货审核入库
* @param billId
*/
void audit(Long billId);
}
|
package xyz.alviksar.orchidarium.ui;
import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.firebase.ui.auth.IdpResponse;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageException;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Stack;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xyz.alviksar.orchidarium.BuildConfig;
import xyz.alviksar.orchidarium.OrchidariumContract;
import xyz.alviksar.orchidarium.R;
import xyz.alviksar.orchidarium.data.OrchidariumPreferences;
import xyz.alviksar.orchidarium.model.OrchidEntity;
import xyz.alviksar.orchidarium.util.GlideApp;
import static com.google.firebase.storage.StorageException.ERROR_OBJECT_NOT_FOUND;
/**
* Shows photos of orchids and detail data.
* This is for a "admin" product flavor.
*/
public class DetailActivity extends AppCompatActivity
implements BannerAdapter.BannerAdapterOnClickHandler {
// An orchid that this activity shows
private OrchidEntity mOrchid;
// Flag if data was changed
private boolean mDataHasChanged = false;
@BindView(R.id.et_code)
EditText mCodeEditText;
@BindView(R.id.sw_put_up_for_sale)
SwitchCompat mPutOnForSaleSwitch;
@BindView(R.id.et_name)
EditText mNameEditText;
@BindView(R.id.sp_plant_age)
Spinner mPlantAgeSpinner;
@BindView(R.id.sp_pot_size)
Spinner mPotSizeSpinner;
@BindView(R.id.et_retail_price)
EditText mRetaPriceEditText;
@BindView(R.id.et_description)
EditText mDescriptionEditText;
@BindView(R.id.sp_currency)
Spinner mCurrencySymbol;
@BindView(R.id.pb_load_photo)
ProgressBar mProgressBar;
@BindView(R.id.iv_nice_photo)
ImageView mNiceImageView;
@BindView(R.id.rv_banner)
RecyclerView mBannerRecyclerView;
LinearLayoutManager mLayoutManager;
BannerAdapter mBannerAdapter;
MenuItem mSaveMenuItem;
private String mUserName;
private int mPlantAge;
private Uri mSelectedImageUri = null;
// Firebase vars
private FirebaseAuth mFirebaseAuth;
private FirebaseStorage mFirebaseStorage;
private StorageReference mStorageReference;
private DatabaseReference mDatabaseReference;
// Request codes values
private static final int RC_AUTH_SIGN_IN = 1;
private static final int RC_NICE_PHOTO_PICKER = 2;
private static final int RC_REAL_PHOTO_PICKER = 3;
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(OrchidEntity.EXTRA_ORCHID, mOrchid);
super.onSaveInstanceState(outState);
}
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
// Get authentication
mFirebaseAuth = FirebaseAuth.getInstance();
if (mFirebaseAuth.getCurrentUser() == null) {
// not signed in
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(!BuildConfig.DEBUG /* credentials */,
true /* hints */)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.EmailBuilder().build()))
// new AuthUI.IdpConfig.PhoneBuilder().build()))
.build(),
RC_AUTH_SIGN_IN);
} else {
mUserName = mFirebaseAuth.getCurrentUser().getUid();
}
// Init Firebase
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = firebaseDatabase
.getReference().child(OrchidariumContract.REFERENCE_ORCHIDS_DATA);
mFirebaseStorage = FirebaseStorage.getInstance();
mStorageReference = mFirebaseStorage
.getReference(OrchidariumContract.REFERENCE_ORCHIDS_PHOTOS);
// Set an activity title
String title;
if (savedInstanceState == null || !savedInstanceState.containsKey(OrchidEntity.EXTRA_ORCHID)) {
mOrchid = getIntent().getParcelableExtra(OrchidEntity.EXTRA_ORCHID);
} else {
mOrchid = savedInstanceState.getParcelable(OrchidEntity.EXTRA_ORCHID);
}
if (mOrchid == null) {
title = getString(R.string.title_new_orchid);
// Invalidate the options menu, so the "Delete" menu option can be hidden.
invalidateOptionsMenu();
mOrchid = new OrchidEntity();
} else {
title = mOrchid.getName();
}
setTitle(title);
CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
if (collapsingToolbarLayout != null)
collapsingToolbarLayout.setTitle(title);
// Set toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
/*
Check if a tablet portrait layout or not
https://stackoverflow.com/questions/9279111/determine-if-the-device-is-a-smartphone-or-tablet
*/
boolean tabletPort = getResources().getBoolean(R.bool.isTabletPort);
if (tabletPort) {
// If a tablet portrait screen, use 2 columns grid
mLayoutManager = new GridLayoutManager(this, 2);
} else {
// Use a linear layout manager
mLayoutManager = new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false);
}
mBannerRecyclerView.setLayoutManager(mLayoutManager);
ArrayList<String> bannerList = new ArrayList<>(mOrchid.getRealPhotos());
// Add an empty item for the add photo image
bannerList.add(getString(R.string.empty));
// Specify an adapter
mBannerAdapter = new BannerAdapter(bannerList, this);
mBannerRecyclerView.setAdapter(mBannerAdapter);
// Set orchid data
mCodeEditText.setText(mOrchid.getCode());
mNameEditText.setText(mOrchid.getName());
String s;
switch (mOrchid.getAge()) {
case OrchidEntity.AGE_BLOOMING:
s = getString(R.string.plant_age_blooming);
break;
case OrchidEntity.AGE_FLOWERING:
s = getString(R.string.plant_age_flowering);
break;
case OrchidEntity.AGE_ONE_YEARS_BEFORE:
s = getString(R.string.plant_age_one_years_before);
break;
case OrchidEntity.AGE_TWO_YEARS_BEFORE:
s = getString(R.string.plant_age_two_years_before);
break;
case OrchidEntity.AGE_UNKNOWN:
s = getString(R.string.empty);
break;
default:
s = getString(R.string.empty);
}
mPlantAgeSpinner.setSelection(((ArrayAdapter<String>) mPlantAgeSpinner.getAdapter())
.getPosition(s));
/*
http://qaru.site/questions/32545/how-to-set-selected-item-of-spinner-by-value-not-by-position
*/
if (mOrchid.getPotSize() != null) {
mPotSizeSpinner.setSelection(((ArrayAdapter<String>) mPotSizeSpinner.getAdapter())
.getPosition(mOrchid.getPotSize()));
}
if (mOrchid.getCurrencySymbol() == null
|| TextUtils.isEmpty(mOrchid.getCurrencySymbol())) {
// Take the last chosen currency symbol
String symbol = OrchidariumPreferences.getCurrencySymbol(this);
mCurrencySymbol.setSelection(((ArrayAdapter<String>) mCurrencySymbol.getAdapter())
.getPosition(symbol));
} else {
mCurrencySymbol.setSelection(((ArrayAdapter<String>) mCurrencySymbol.getAdapter())
.getPosition(mOrchid.getCurrencySymbol()));
}
// Format a price string
if (mOrchid.getRetailPrice() != 0)
mRetaPriceEditText.setText(String.format(Locale.getDefault(),
"%.2f", mOrchid.getRetailPrice()));
else
mRetaPriceEditText.setText("");
mDescriptionEditText.setText(mOrchid.getDescription());
// Set listeners if tap on any TextEdit or Spinner
mCodeEditText.setOnTouchListener(mTouchListener);
mPutOnForSaleSwitch.setOnTouchListener(mTouchListener);
mNameEditText.setOnTouchListener(mTouchListener);
mRetaPriceEditText.setOnTouchListener(mTouchListener);
mDescriptionEditText.setOnTouchListener(mTouchListener);
mPlantAgeSpinner.setOnTouchListener(mTouchListener);
mPotSizeSpinner.setOnTouchListener(mTouchListener);
mPutOnForSaleSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mPutOnForSaleSwitch.setText(mPutOnForSaleSwitch.getTextOn());
} else {
mPutOnForSaleSwitch.setText(mPutOnForSaleSwitch.getTextOff());
}
}
});
mPutOnForSaleSwitch.setChecked(mOrchid.getIsVisibleForSale());
if (mOrchid.getIsVisibleForSale()) {
mPutOnForSaleSwitch.setText(mPutOnForSaleSwitch.getTextOn());
} else {
mPutOnForSaleSwitch.setText(mPutOnForSaleSwitch.getTextOff());
}
// Set the integer to the constant values
mPlantAgeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.plant_age_two_years_before))) {
mPlantAge = OrchidEntity.AGE_TWO_YEARS_BEFORE;
} else if (selection.equals(getString(R.string.plant_age_one_years_before))) {
mPlantAge = OrchidEntity.AGE_ONE_YEARS_BEFORE;
} else if (selection.equals(getString(R.string.plant_age_flowering))) {
mPlantAge = OrchidEntity.AGE_FLOWERING;
} else if (selection.equals(getString(R.string.plant_age_blooming))) {
mPlantAge = OrchidEntity.AGE_BLOOMING;
} else {
mPlantAge = OrchidEntity.AGE_UNKNOWN;
}
} else {
mPlantAge = OrchidEntity.AGE_UNKNOWN;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mPlantAge = OrchidEntity.AGE_UNKNOWN;
}
});
GlideApp.with(mNiceImageView.getContext())
.load(mOrchid.getNicePhoto())
// .centerCrop()
.fitCenter()
.into(mNiceImageView);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
mSaveMenuItem = menu.findItem(R.id.action_save);
// If this is a new orchid, hide the "Delete" menu item.
if (mOrchid == null || getTitle().equals(getString(R.string.title_new_orchid))) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setEnabled(false);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
switch (item.getItemId()) {
// Respond to a click on the "Save" menu option
case R.id.action_save:
saveOrchid();
// finish();
return true;
// Respond to a click on the "Delete" menu option
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
// Respond to a click on the "Up" arrow button in the app bar
case android.R.id.home:
// Hook up the up button
// If the orchid hasn't changed, continue with navigating up to parent activity
if (!mDataHasChanged) {
NavUtils.navigateUpFromSameTask(DetailActivity.this);
return true;
}
/*
If there are unsaved changes, setup a dialog to warn the user.
Create a click listener to handle the user confirming that
changes should be discarded.
*/
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, navigate to parent activity.
NavUtils.navigateUpFromSameTask(DetailActivity.this);
}
};
// Show a dialog that notifies the user they have unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
return true;
}
} catch (IllegalArgumentException e) {
Snackbar.make(findViewById(R.id.coordinatorlayout),
e.getMessage(), Snackbar.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// RC_AUTH_SIGN_IN is the request code you passed into startActivityForResult(...)
// when starting the sign in flow.
if (requestCode == RC_AUTH_SIGN_IN) {
IdpResponse response = IdpResponse.fromResultIntent(data);
// Successfully signed in
if (resultCode == RESULT_OK && mFirebaseAuth.getCurrentUser() != null) {
mUserName = mFirebaseAuth.getCurrentUser().getUid();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Snackbar.make(findViewById(R.id.coordinatorlayout), R.string.msg_sign_in_canceled,
Snackbar.LENGTH_LONG).show();
finish();
} else {
// Sign in failed
if (response == null) {
Snackbar.make(findViewById(R.id.coordinatorlayout),
R.string.msg_sign_in_canceled,
Snackbar.LENGTH_LONG).show();
return;
}
if (response.getError().getErrorCode() == ErrorCodes.NO_NETWORK) {
Snackbar.make(findViewById(R.id.coordinatorlayout),
R.string.msg_no_connection_error,
Snackbar.LENGTH_LONG).show();
return;
}
Snackbar.make(findViewById(R.id.coordinatorlayout), response.getError().getMessage(),
Snackbar.LENGTH_LONG).show();
}
} else if (requestCode == RC_NICE_PHOTO_PICKER && resultCode == RESULT_OK) {
// Get a nice photo
mSelectedImageUri = data.getData();
GlideApp.with(mNiceImageView.getContext()).clear(mNiceImageView);
GlideApp.with(mNiceImageView.getContext())
.load(mSelectedImageUri)
.centerCrop()
.into(mNiceImageView);
} else if (requestCode == RC_REAL_PHOTO_PICKER && resultCode == RESULT_OK) {
// Get one of real photos
if (data.getData() != null)
mBannerAdapter.addImage(data.getData().toString());
}
}
/**
* Saves orchid data in database
*/
private void saveOrchid() {
if (mOrchid == null) {
mOrchid = new OrchidEntity();
}
mOrchid.setIsVisibleForSale(mPutOnForSaleSwitch.isChecked());
mOrchid.setCode(mCodeEditText.getText().toString().trim());
mOrchid.setName(mNameEditText.getText().toString().trim());
mOrchid.setAge(mPlantAge);
mOrchid.setPotSize(mPotSizeSpinner.getSelectedItem().toString().trim());
mOrchid.setRetailPrice(Double.valueOf(mRetaPriceEditText.getText().toString().trim()
.replace(',', '.')));
mOrchid.setDescription(mDescriptionEditText.getText().toString().trim());
mOrchid.setCurrencySymbol(mCurrencySymbol.getSelectedItem().toString());
mOrchid.setWriter(mUserName);
mOrchid.setSaveTime(System.currentTimeMillis());
// Save a chosen currency symbol
OrchidariumPreferences.setCurrencySymbol(this, mOrchid.getCurrencySymbol());
mProgressBar.setVisibility(View.VISIBLE);
// Update the list of real photos and save orchid data in database
changeListOfPhotosAndSaveDataToDb(
getToDelete(mOrchid.getRealPhotos(), mBannerAdapter.getData()));
}
/**
* Uploads the nice photo in Firebase Storage and save orchid data in the Database
*/
private void uploadNicePhotoAndSaveDataToDb() {
if (mSelectedImageUri != null) {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(0);
mSaveMenuItem.setEnabled(false);
// First, delete old image
if (!TextUtils.isEmpty(mOrchid.getNicePhoto())) {
// Delete old file
final StorageReference deleteRef = mFirebaseStorage
.getReferenceFromUrl(mOrchid.getNicePhoto());
deleteRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Upload a new nice image
uploadNicePhotoAndFinish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
String errMsg = exception.getMessage();
Snackbar.make(findViewById(R.id.coordinatorlayout), errMsg,
Snackbar.LENGTH_LONG).show();
int errorCode = ((StorageException) exception).getErrorCode();
if (errorCode == ERROR_OBJECT_NOT_FOUND) {
// Can continue
uploadNicePhotoAndFinish();
}
}
});
} else {
// Upload a new nice image
uploadNicePhotoAndFinish();
}
} else {
saveOrchidDataToDb();
finish();
}
}
/**
* Uploads the nice photo into Storage and saves the orchid data into the Database
*/
private void uploadNicePhotoAndFinish() {
final StorageReference photoRef = mStorageReference.child(mSelectedImageUri.getLastPathSegment());
photoRef.putFile(mSelectedImageUri)
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred())
/ taskSnapshot.getTotalByteCount();
mProgressBar.setProgress((int) progress);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
mProgressBar.setVisibility(View.INVISIBLE);
mSaveMenuItem.setEnabled(true);
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
// https://gist.github.com/jonathanbcsouza/13929ab81077645f1033bf9ce45beaab
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, get its download URL
photoRef.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// Take a new url
mOrchid.setNicePhoto(uri.toString());
mProgressBar.setVisibility(View.INVISIBLE);
// Save the object in the database
saveOrchidDataToDb();
// That is it. Uff...
finish();
}
});
}
});
}
private void saveOrchidDataToDb() {
// Save or add new orchid
if (TextUtils.isEmpty(mOrchid.getId())) {
// Add new data
mDatabaseReference.push().setValue(mOrchid);
} else {
// Replace existing data
mDatabaseReference.child(mOrchid.getId()).setValue(mOrchid);
}
}
/**
* Check if changes were made
*/
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mDataHasChanged = true;
return false;
}
};
private void showDeleteConfirmationDialog() {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the positive and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.msg_delete_dialog);
builder.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Delete" button, so delete the orchid.
// deleteOrchid();
deleteListOfPhotosAndObjectFromDb(
getToDelete(mOrchid.getRealPhotos(), new ArrayList<String>()));
NavUtils.navigateUpFromSameTask(DetailActivity.this);
}
});
builder.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Cancel" button, so dismiss the dialog
// and continue editing the orchid.
if (dialog != null) {
dialog.dismiss();
}
}
});
// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Deletes the orchid data from the Database.
*/
private void deleteOrchid() {
if (mOrchid != null && !TextUtils.isEmpty(mOrchid.getId())) {
if (!TextUtils.isEmpty(mOrchid.getNicePhoto())) {
// Delete image file
final StorageReference deleteRef
= mFirebaseStorage.getReferenceFromUrl(mOrchid.getNicePhoto());
deleteRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// If file was deleted successfully, delete object from database
mDatabaseReference.child(mOrchid.getId()).removeValue();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
String errMsg = exception.getMessage();
Snackbar.make(findViewById(R.id.coordinatorlayout), errMsg,
Snackbar.LENGTH_LONG).show();
int errorCode = ((StorageException) exception).getErrorCode();
if (errorCode == ERROR_OBJECT_NOT_FOUND) {
// Can delete
mDatabaseReference.child(mOrchid.getId()).removeValue();
}
}
});
} else {
mDatabaseReference.child(mOrchid.getId()).removeValue();
}
}
}
/**
* Creates a “Discard changes” dialog
*/
private void showUnsavedChangesDialog(
DialogInterface.OnClickListener discardButtonClickListener) {
// Create an AlertDialog.Builder and set the message, and click listeners
// for the positive and negative buttons on the dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.msg_unsaved_changes_dialog);
builder.setPositiveButton(R.string.btn_discard, discardButtonClickListener);
builder.setNegativeButton(R.string.btn_keep_editing, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked the "Keep editing" button, so dismiss the dialog
// and continue editing.
if (dialog != null) {
dialog.dismiss();
}
}
});
// Create and show the AlertDialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
@Override
public void onBackPressed() {
// If the orchid hasn't changed, continue with handling back button press
if (!mDataHasChanged) {
super.onBackPressed();
return;
}
// Otherwise if there are unsaved changes, setup a dialog to warn the user.
// Create a click listener to handle the user confirming that changes should be discarded.
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// User clicked "Discard" button, close the current activity.
finish();
}
};
// Show dialog that there are unsaved changes
showUnsavedChangesDialog(discardButtonClickListener);
}
@OnClick(R.id.btn_add_nice_photo)
public void onClickBtn(View view) {
choosePhoto(RC_NICE_PHOTO_PICKER);
}
@OnClick(R.id.iv_nice_photo)
public void onClickImage(View view) {
if (TextUtils.isEmpty(mOrchid.getNicePhoto())) return;
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(mOrchid.getNicePhoto()), "image/*");
startActivity(intent);
}
@Override
public void onClickBannerPhoto(View view, String url, int position) {
if (TextUtils.isEmpty(url)) {
// Starts an implicit intent to choose photo from the phone gallery
choosePhoto(RC_REAL_PHOTO_PICKER);
} else {
// Starts an implicit intent to show photo by viewer
Intent intent = new Intent(DetailActivity.this,
PhotoGalleryActivity.class);
intent.setData(Uri.parse(url));
intent.putExtra(OrchidEntity.EXTRA_ORCHID_NAME, mOrchid.getName());
intent.putStringArrayListExtra(OrchidEntity.EXTRA_ORCHID_PHOTO_LIST,
mBannerAdapter.getData());
intent.putExtra(OrchidEntity.EXTRA_ORCHID_PHOTO_LIST_POSITION, position);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
View sharedView = view.findViewById(R.id.iv_real_photo);
startActivity(intent,
ActivityOptions.makeSceneTransitionAnimation(
DetailActivity.this,
sharedView,
sharedView.getTransitionName())
.toBundle());
} else {
startActivity(intent);
}
}
}
/**
* Starts an implicit intent to choose photo from the phone gallery
*
* @param requestCode
*/
private void choosePhoto(int requestCode) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, getString(R.string.msg_choose_image)),
requestCode);
}
/**
* Defines the list of added photos which have to be uploaded
*
* @param afterList The changed list
* @return The list of added photos
*/
private Stack<String> getToUpload(List<String> afterList) {
Stack<String> toUpload = new Stack<>();
for (String s : afterList) {
Uri uri = Uri.parse(s);
String host = uri.getScheme();
if ("content".equals(host)) toUpload.push(s);
}
return toUpload;
}
/**
* Compares lists and takes the difference
*
* @param beforeList The old list
* @param afterList The new list
* @return The list of strings from the old list not included in the new list
*/
private Stack<String> getToDelete(List<String> beforeList, List<String> afterList) {
Stack<String> toDelete = new Stack<>();
for (String s : beforeList) {
if (!afterList.contains(s)) toDelete.push(s);
}
return toDelete;
}
/**
* Updates the list of real photos and saves orchid data in database
*
* @param toDelete List of real photos to be deleted.
*/
private void changeListOfPhotosAndSaveDataToDb(final Stack<String> toDelete) {
if (toDelete.empty()) {
// Next step
// Upload photos to Firebase Storage and save orchid data in database
uploadListOfPhotosAndSaveDataToDb(getToUpload(mBannerAdapter.getData()));
} else {
// Delete list of real photos
final String photoUrl = toDelete.pop();
if (!TextUtils.isEmpty(photoUrl)) {
// Delete image file
final StorageReference deleteRef
= mFirebaseStorage.getReferenceFromUrl(photoUrl);
deleteRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// If file was deleted successfully, delete next one
mOrchid.getRealPhotos().remove(photoUrl);
changeListOfPhotosAndSaveDataToDb(toDelete);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
String errMsg = exception.getMessage();
Snackbar.make(findViewById(R.id.coordinatorlayout), errMsg,
Snackbar.LENGTH_LONG).show();
int errorCode = ((StorageException) exception).getErrorCode();
if (errorCode == ERROR_OBJECT_NOT_FOUND) {
// Can continue
mOrchid.getRealPhotos().remove(photoUrl);
changeListOfPhotosAndSaveDataToDb(toDelete);
}
}
});
}
}
}
/**
* Deletes photos form Firebase Storage by list
*
* @param photosToDelete The list of photos to be deleted.
*/
private void deleteListOfPhotosAndObjectFromDb(final Stack<String> photosToDelete) {
if (photosToDelete.empty()) {
// Next step
deleteOrchid();
} else {
// Delete list of real photos
final String photoUrl = photosToDelete.pop();
if (!TextUtils.isEmpty(photoUrl)) {
// Delete image file
final StorageReference deleteRef
= mFirebaseStorage.getReferenceFromUrl(photoUrl);
deleteRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// If file was deleted successfully, delete next one
mOrchid.getRealPhotos().remove(photoUrl);
deleteListOfPhotosAndObjectFromDb(photosToDelete);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
String errMsg = exception.getMessage();
Snackbar.make(findViewById(R.id.coordinatorlayout), errMsg,
Snackbar.LENGTH_LONG).show();
int errorCode = ((StorageException) exception).getErrorCode();
if (errorCode == ERROR_OBJECT_NOT_FOUND) {
// Can continue
mOrchid.getRealPhotos().remove(photoUrl);
deleteListOfPhotosAndObjectFromDb(photosToDelete);
}
}
});
}
}
}
/**
* Uploads photos into Firebase Storage and saves orchid data in the Database
*
* @param toUpload The list of real photos to be upload into Firebase Storage
*/
private void uploadListOfPhotosAndSaveDataToDb(final Stack<String> toUpload) {
mProgressBar.setVisibility(View.VISIBLE);
if (toUpload.empty()) {
// All photos have been saved, so save the nice photo and the orchid data
uploadNicePhotoAndSaveDataToDb();
} else {
// Save the list of real photos recursively
String photoUrl = toUpload.pop();
if (!TextUtils.isEmpty(photoUrl)) {
Uri photoUri = Uri.parse(photoUrl);
final StorageReference photoRef = mStorageReference.child(photoUri.getLastPathSegment());
mProgressBar.setProgress(0);
// Listen for state changes, errors, and completion of the upload.
photoRef.putFile(photoUri).addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred())
/ taskSnapshot.getTotalByteCount();
mProgressBar.setProgress((int) progress);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
mProgressBar.setVisibility(View.INVISIBLE);
mSaveMenuItem.setEnabled(true);
String errMsg = exception.getMessage();
Snackbar.make(findViewById(R.id.coordinatorlayout), errMsg,
Snackbar.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
// https://gist.github.com/jonathanbcsouza/13929ab81077645f1033bf9ce45beaab
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//When the image has successfully uploaded, get its download URL
photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// Save new url
mOrchid.getRealPhotos().add(uri.toString());
mProgressBar.setVisibility(View.INVISIBLE);
// Upload next one
uploadListOfPhotosAndSaveDataToDb(toUpload);
}
});
}
});
}
}
}
}
|
package com.badawy.carservice.fragment;
import android.app.Activity;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.badawy.carservice.R;
import com.badawy.carservice.activity.HomepageActivity;
import com.badawy.carservice.adapters.ProductItemAdapter;
import com.badawy.carservice.adapters.SparePartsCategoryAdapter;
import com.badawy.carservice.models.CarModel;
import com.badawy.carservice.models.SparePartsCategoryModel;
import com.badawy.carservice.models.SparePartModel;
import com.badawy.carservice.utils.Constants;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class DeliveryCarSparePartsShopFragment extends Fragment implements SparePartsCategoryAdapter.OnCategoryClick {
private ImageView navMenuBtn, shoppingCart;
private RecyclerView partsCategoryNameRv, productsRv;
private CarModel selectedCarObject;
private DatabaseReference dbRef;
private ArrayList<SparePartsCategoryModel> sparePartsCategoryList;
private ArrayList<SparePartModel> productsList;
private Activity activity;
private ConstraintLayout emptyLayout,mainLayout;
public DeliveryCarSparePartsShopFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_spare_parts_shop, container, false);
activity = getActivity();
initializeUi(view);
showProgress();
mainLayout.setVisibility(View.GONE);
// Get Selected Car Data
getSelectedCar();
// Retrieve Available Categories For This Car
getCategoriesData();
navMenuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HomepageActivity.openDrawer();
}
});
shoppingCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = getActivity();
if (activity instanceof HomepageActivity) {
((HomepageActivity) activity).openShoppingCart();
}
}
});
return view;
}
private void getSelectedCar() {
assert getArguments() != null;
String serializedSelectedCarObject = getArguments().getString(Constants.SELECTED_CAR);
Gson gson = new Gson();
Type type = new TypeToken<CarModel>() {
}.getType();
selectedCarObject = gson.fromJson(serializedSelectedCarObject, type);
}
private void getCategoriesData() {
dbRef = FirebaseDatabase.getInstance().getReference().child(Constants.CARS_SPARE_PARTS).child(selectedCarObject.getCarID());
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
sparePartsCategoryList = new ArrayList<>();
for (DataSnapshot ds: dataSnapshot.getChildren()
) {
if (ds.hasChildren()){
// retrieve categories
List<String> sparePartsIdList = new ArrayList<>();
for (DataSnapshot child:ds.getChildren()){
sparePartsIdList.add(child.getKey());
}
sparePartsCategoryList.add(new SparePartsCategoryModel(ds.getKey(),sparePartsIdList));
}
}
if (sparePartsCategoryList.size()!=0){
bindCategoryDataToAdapter();
}
else{
hideProgress();
mainLayout.setVisibility(View.GONE);
emptyLayout.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void bindCategoryDataToAdapter() {
SparePartsCategoryAdapter sparePartsCategoryAdapter = new SparePartsCategoryAdapter(getActivity(), sparePartsCategoryList, this);
partsCategoryNameRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
partsCategoryNameRv.setAdapter(sparePartsCategoryAdapter);
hideProgress();
partsCategoryNameRv.setVisibility(View.VISIBLE);
}
private void initializeUi(View view) {
navMenuBtn = view.findViewById(R.id.sparePartsShop_navMenuBtn);
shoppingCart = view.findViewById(R.id.sparePartsShop_shoppingCart);
partsCategoryNameRv = view.findViewById(R.id.sparePartsShop_categoryNameRV);
productsRv = view.findViewById(R.id.sparePartsShop_productsRV);
emptyLayout =view.findViewById(R.id.sparePartsShop_emptyLayout);
mainLayout = view.findViewById(R.id.sparePartsShop_mainLayout);
}
@Override
public void onCategoryClick(final int position) {
partsCategoryNameRv.scrollToPosition(position);
fetchProductsOfThisCategory(position);
}
private void fetchProductsOfThisCategory(int position) {
showProgress();
final List<String> idList = sparePartsCategoryList.get(position).getPartIdList();
dbRef = FirebaseDatabase.getInstance().getReference().child(Constants.APP_DATA).child(Constants.SPARE_PARTS);
dbRef.child(sparePartsCategoryList.get(position).getPartsCategoryName())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
productsList = new ArrayList<>();
for (String id: idList) {
if (dataSnapshot.hasChild(id)){
productsList.add(dataSnapshot.child(id).getValue(SparePartModel.class));
}
}
bindProductData();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void bindProductData() {
ProductItemAdapter productItemAdapter = new ProductItemAdapter(getActivity(),productsList);
productsRv.setLayoutManager(new GridLayoutManager(getActivity(),2));
productsRv.setAdapter(productItemAdapter);
hideProgress();
productsRv.setVisibility(View.VISIBLE);
mainLayout.setVisibility(View.VISIBLE);
}
private void showProgress() {
if (activity instanceof HomepageActivity) {
((HomepageActivity) activity).showProgressBar(true);
}
}
private void hideProgress() {
if (activity instanceof HomepageActivity) {
((HomepageActivity) activity).showProgressBar(false);
}
}
private void fakeDataTest() {
// String[] nameArray = {"Tires", "Mirrors", "Engine", "Others"};
// int[] manufacturerImage={R.drawable.ic_hankook,R.drawable.tirelogo2,R.drawable.tirelogo3,R.drawable.hankook,R.drawable.hankook,R.drawable.hankook};
// String[] productName={"Hankook Ventus Prime 3 K125","Hankook KINERGY ECO 2 K435","Hankook VENTUS PRIME3 K125","Hankook Kinergy ECO K425","Hankook VENTUS PRIME3 K125","Hankook Kinergy ECO K425"};
// String[] productPartNumber={"8808563446509","8808563301211","8808563401720","8808563401768","8808563411880","8808563401775"};
// String[] productDescription={"205/55 R16 94W XL SBL ","205/55 R16 91W * SBL ","205/55 R16 91W * SBL BMW 1 3TR16 91W * SBL BMW 1 3TRR16 91W * SBL BMW 1 3TR16 91W * SBL BMW 1 3TR16 91W * SBL BMW 1 3T16 91W * SBL BMW 1 3TR16 91W * SBL BMW 1 3TR16 91W * SBL BMW 1 3T , BMW 1 5T","205/55 R16 91V SBL VOLKSWAGEN Golf VI","P205/55 R16 94H XL 4PR SBL","205/55 R16 91V SBL"};
// String[] productPrice={"1350.00 EGP","2139.00 EGP","780.30 EGP","2566.50 EGP","1600.00 EGP","1300.00 EGP"};
// int[] productImage={R.drawable.tire,R.drawable.tire,R.drawable.tire,R.drawable.tire,R.drawable.tire,R.drawable.tire};
// for (String s : nameArray) {
// nameList.add(new PartsCategoryNameModel(s));
// }
//
// PartsCategoryNameAdapter nameAdapter = new PartsCategoryNameAdapter(getActivity(), nameList);
// partsCategoryNameRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
// partsCategoryNameRv.setAdapter(nameAdapter);
//
// for (int i = 0;i<productName.length;i++){
//
// productsList.add(new ProductItemModel(manufacturerImage[i],productImage[i],productName[i],productPartNumber[i],productDescription[i],productPrice[i]));
//
// }
// ProductItemAdapter productItemAdapter = new ProductItemAdapter(getActivity(),productsList);
// productsRv.setLayoutManager(new GridLayoutManager(getActivity(),2));
// productsRv.setAdapter(productItemAdapter);
}
}
|
package com.lojaDeComputadorV3.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import com.lojaDeComputadorV3.dao.ProdutoDAO;
import com.lojaDeComputadorV3.domain.Produto;
@FacesConverter("produtoConverter")
public class ProdutoConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String valor) {
try {
Long codigo = Long.parseLong(valor);
ProdutoDAO produtoDAO = new ProdutoDAO();
Produto produto = (Produto) produtoDAO.buscarPorCodigo(codigo);
return produto;
} catch (Exception e) {
return null;
}
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object objeto) {
try {
Produto produto = (Produto) objeto;
Long codigo = produto.getCodigo();
return codigo.toString();
} catch (Exception e) {
return null;
}
}
}
|
import java.io.*;
import java.lang.*;
import java.util.*;
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include<stdbool.h>
/*
# Author : @RAJ009F
# Topic or Type : GFG/ARRAY
# Problem Statement : ConsecutiveEle.java
# Description :
# Complexity :
=======================
#sample output
----------------------
=======================
*/
class ConsecutiveEle
{
static boolean consecutive(int arr[], int n)
{
int max=arr[0];
int min=arr[0];
for(int i=0; i<n; i++)
{
if(arr[i]>max)
max = arr[i];
if(arr[i]<min)
min = arr[i];
}
int sum = n*(n+1)/2;
if(max-min+1==n)
{
for(int i=0; i<n; i++)
{
sum -=(arr[i]-min+1);
}
if(sum==0)
return true;
else
return false;
}
return false;
}
public static void main(String args[])
{
int arr[] = {1, 4, 5, 3, 2, 6};
if(consecutive(arr, arr.length))
System.out.println("Consecutive");
else
System.out.println("Not Consecutive");
}
}
|
package com.lenovohit.hcp.base.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.lenovohit.bdrp.authority.model.AuthRole;
import com.lenovohit.core.model.BaseIdModel;
import com.lenovohit.core.utils.BeanUtils;
@Entity
@Table(name = "HCP_ROLE") // 人员基本信息';
public class HcpRole extends BaseIdModel implements AuthRole {
/**
*
*/
private static final long serialVersionUID = -6902228056157687846L;
private String hosId;
private String code;
private String name;
private String parent;
private String description;
private String creator;
private Date createTime;
private String updater;
private Date updateTime;
private String isGroup; //是否集团
public String getHosId() {
return hosId;
}
public void setHosId(String hosId) {
this.hosId = hosId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdater() {
return updater;
}
public void setUpdater(String updater) {
this.updater = updater;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getIsGroup() {
return isGroup;
}
public void setIsGroup(String isGroup) {
this.isGroup = isGroup;
}
@Override
public AuthRole clone() {
try {
Object clone = super.clone();
return (HcpRole) clone;
} catch (CloneNotSupportedException e) {
HcpRole target = new HcpRole();
BeanUtils.copyProperties(this, target);
return target;
}
}
}
|
package com.company;
import java.util.Random;
/**
* Created by 17032361 on 2017/8/8.
* 生成随机数
*/
//public class chapter3_12 {
// public static void main(String[] args){
// Random xx = new Random();
// int number = xx.nextInt(10);
// System.out.println(number);
// }
//}
public class chapter3_12{
public static void main(String[] args){
System.out.println((int)(Math.random()*10));
}
}
|
package xhu.wncg.firesystem.modules.mapper;
import org.apache.ibatis.annotations.Param;
import xhu.wncg.firesystem.modules.controller.vo.DailyTableVO;
import xhu.wncg.firesystem.modules.controller.qo.DailyTableQO;
import xhu.wncg.common.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import xhu.wncg.firesystem.modules.pojo.DailyTable;
import java.lang.reflect.Array;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 日常检查表
*
* @author zhaobo
* @email 15528330581@163.com
* @version 2017-11-02 15:58:16
*/
@Mapper
public interface DailyTableMapper extends BaseMapper<DailyTableQO, DailyTableVO> {
/**
* 通过场所id查询该场所的检查记录
* @param countId
* @return list
*/
List<DailyTable> countDaily(Integer countId);
/**
* 通过日常检查表id查具体信息
* @param dailyTableId
* @return DailyTableVO
*/
DailyTableVO queryByDailyTableId(Integer dailyTableId);
/**
* 通过policeid查询警员检查次数
* @param params
* @return
*/
List<DailyTableVO> count(@Param("params")Object params);
}
|
package com.example.activitytest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class FirstActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.first_layout);
Button button1=(Button)findViewById(R.id.button_1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
String data="Hello,SecondActivity!";
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(intent,1);
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case 1:
if(resultCode == RESULT_OK){
String returnedData=data.getStringExtra("returned_data");
Toast.makeText(this,returnedData,Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.add_item:
Toast.makeText(this,"you clicked add",Toast.LENGTH_SHORT).show();
break;
case R.id.remove_item:
Toast.makeText(this,"you clicked remove",Toast.LENGTH_SHORT).show();
break;
default:
}
return true;
}
}
|
package com.resjob.modules.app.dao;
import java.util.List;
import com.resjob.common.persistence.CrudDao;
import com.resjob.common.persistence.annotation.MyBatisDao;
import com.resjob.modules.app.entity.PaperKeyword;
/**
* 论文关键字DAO接口
* @author wupeng
* @version 2016-05-20
*/
@MyBatisDao
public interface PaperKeywordDao extends CrudDao<PaperKeyword> {
/**
* 删除关键字
* @param paperId 论文编号
* @return
*/
public int deleteByPaperId(String paperId);
/**
* 查询关键字
* @param paperId
* @return
*/
public List<PaperKeyword> findListByPaperId(String paperId);
}
|
/**
* Copyright 2015 Thomas Cashman
*/
package org.protogen.compiler.core.condition;
/**
*
* @author Thomas Cashman
*/
public interface Condition {
}
|
package DemoRest.WebApp.repository;
import DemoRest.WebApp.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<Users, Integer> {
Users findByEmailAddress(String email_address);
Users findById(String id);
}
|
/**
* @author TATTYPLAY
* @date May 26, 2018
* @created 1:22:05 AM
* @filename CreationItemsReport.java
* @project Reporter
* @package com.tattyhost.reporter.inventory
* @copyright 2018
*/
package com.tattyhost.reporter.inventory.items;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.tattyhost.reporter.ItemStackE;
import com.tattyhost.reporter.Reporter;
import com.tattyhost.reporter.Manager.ManagerMySQL;
import com.tattyhost.reporter.Manager.ManagerReport;
public class CreationItemsReport {
// public static String[] playernames;
// public static String[] uuids;
// public static int[] reportsall;
// public static int[] hacking;
// public static int[] griefing;
// public static int[] spam;
// public static int[] insult;
private Reporter ma = Reporter.getInstance();
private ManagerMySQL mysql = ma.getMySQL();
private ManagerReport mr = new ManagerReport();
private static List<Object[]> itemSetOut = new ArrayList<Object[]>();
private static List<ItemStackE> items = new ArrayList<ItemStackE>();
private List<Map<String, Object>> resultSetToList() {
try {
PreparedStatement ps = mysql.getConnection(false).prepareStatement("SELECT * FROM `reports`;");
ResultSet rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
while (rs.next()) {
Map<String, Object> row = new HashMap<String, Object>(columns);
for (int i = 1; i <= columns; ++i) {
row.put(md.getColumnName(i), rs.getObject(i));
}
rows.add(row);
}
return rows;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public ItemStack createReportBook(boolean bool, UUID uuid) {
try {
PreparedStatement ps = mysql.getConnection(false).prepareStatement("SELECT * FROM `reports` WHERE `uuid` = ?");
ps.setString(1, uuid.toString());
ResultSet rs = ps.executeQuery();
rs.next();
if (rs != null) {
int insultNumber = (int) rs.getInt("insult");
int hackingNumber = (int) rs.getInt("hacking");
int griefingumber = (int) rs.getInt("griefing");
int spamNumber = (int) rs.getInt("spam");
int reportNumber = (int) rs.getInt("reportsall");
String playerName = (String) rs.getString("playername");
String UUIDPlayer = (String) rs.getString("uuid");
String insultString = mr.getInsultString();
String hackingString = mr.getHackingString();
String griefingString = mr.getGriefingString();
String spamString = mr.getSpamString();
String allreports = mr.getAllReportString();
String player = mr.getPlayerString();
String playerUUID = mr.getPlayerUUIDString();
String spacer = ma.getConfig().getString("Report.spacer");
String title = mr.getTitleString(playerName);
int material = 340;
ItemStackE reportBook = new ItemStackE(title, material, 0, 1, 0);
ItemMeta iMeta = reportBook.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(insultString + spacer + insultNumber);
lore.add(hackingString + spacer + hackingNumber);
lore.add(griefingString + spacer + griefingumber);
lore.add(spamString + spacer + spamNumber);
lore.add(allreports + spacer + reportNumber );
lore.add(player + spacer + playerName);
lore.add(playerUUID + spacer + UUIDPlayer );
iMeta.setLore(lore);
reportBook.setItemMeta(iMeta);
return reportBook.getItemStack();
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void createReportBooks(int page, Inventory inventory, boolean bool) {
List<Map<String, Object>> resultSet = resultSetToList();
int setget = resultSet.size();
List<Object[]> itemSet = new ArrayList<Object[]>();
int run = 0;
for (int m = 0; m < setget;) {
m++;
int insultNumber = (int) resultSet.get(run).get("insult");
int hackingNumber = (int) resultSet.get(run).get("hacking");
int griefingumber = (int) resultSet.get(run).get("griefing");
int spamNumber = (int) resultSet.get(run).get("spam");
int reportNumber = (int) resultSet.get(run).get("reportsall");
String playerName = (String) resultSet.get(run).get("playername");
String UUIDPlayer = (String) resultSet.get(run).get("uuid");
String insultString = mr.getInsultString();
String hackingString = mr.getHackingString();
String griefingString = mr.getGriefingString();
String spamString = mr.getSpamString();
String allreports = mr.getAllReportString();
String player = mr.getPlayerString();
String playerUUID = mr.getPlayerUUIDString();
String spacer = ma.getConfig().getString("Report.spacer");
String title = mr.getTitleString(playerName);
int material = 340;
ItemStackE reportBooks = new ItemStackE(title, material, 0, 1, m);
ItemMeta iMeta = reportBooks.getItemMeta();
List<String> lore = new ArrayList<String>();
lore.add(insultString + spacer + insultNumber);
lore.add(hackingString + spacer + hackingNumber);
lore.add(griefingString + spacer + griefingumber);
lore.add(spamString + spacer + spamNumber);
lore.add(allreports + spacer + reportNumber );
lore.add(player + spacer + playerName);
lore.add(playerUUID + spacer + UUIDPlayer );
iMeta.setLore(lore);
reportBooks.setItemMeta(iMeta);
items.add(reportBooks);
if (m == 45) {
itemSet.add(items.toArray());
itemSetOut.add(items.toArray());
setget -= 45;
m = 0;
items.clear();
}
run++;
}
itemSet.add(items.toArray());
itemSetOut.add(items.toArray());
items.clear();
if (bool) {
addItemsToPage(page, inventory, itemSet );
}
}
public void addItemsToPage(int page, Inventory inv, List<Object[]> list) {
Object[] itemsArray = list.get(page);
for (int i=0; i< itemsArray.length; i++) {
try {
ItemStackE item = (ItemStackE) itemsArray[i];
inv.setItem(item.getSlot(), item.getItemStack());
} catch(Exception e) {
e.printStackTrace();
}
}
}
public ItemStack getBook(int slot, int page) {
createReportBooks( 0, null, false );
Object[] itemsArray = itemSetOut.get(page);
ItemStackE item = (ItemStackE) itemsArray[slot];
return item.getItemStack();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Threads;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author rm
*/
public class Bank_Account_Operation implements Runnable{
Banck_Account_Reentrantlock bank=new Banck_Account_Reentrantlock("Abc010201243", 160000);
Random ra=new Random(10);
public static void main (String[]args){
Bank_Account_Operation obj=new Bank_Account_Operation();
Thread shady=new Thread(obj);
Thread salah=new Thread(obj);
Thread pop=new Thread(obj);
shady.currentThread().setName("shady");
salah.currentThread().setName("salah");
pop.currentThread().setName("pop");
shady.setPriority(Thread.MAX_PRIORITY);
shady.start();
salah.start();
pop.start();
}
@Override
public void run() {
for(int count=0;count<100;count++){
try {
bank.withdraw(ra.nextFloat() * 10000);
} catch (InterruptedException ex) {
}
}
}
}
|
import java.util.Scanner;
/**
*This program calcualtes the cost of a customers pizza based on its diameter and size
* @author Zachary Balean
*/
public class Main {
/**
* The method that is executed when you hit the run button.
* @param args the command line arguments
*/
public static void main(String[] args) {
// Creates a Scanner
Scanner input = new Scanner(System.in);
//Constants for mandatory pizza charges
final double LABOUR_PRICE = 0.75;
final double OVEN_PRICE = 0.99;
final double INGREDIENTS_PRICE = 0.50;
final double TAX_PRICE = 0.13;
//Messgae for customers
System.out.println("What is the size of the pizza (in cm):");
//Variable for customers pizza diameter
double pizzaSize = input.nextDouble();
//Calculates subtotal for customer and tell them subtotal
double costNoTax = (pizzaSize * INGREDIENTS_PRICE + OVEN_PRICE + LABOUR_PRICE);
System.out.println("Subtotal: " + "$" + costNoTax);
//Calculates tax and tells cost
double taxCost = (costNoTax * TAX_PRICE);
System.out.println("Taxes: " + "$" + taxCost);
//Calculates and tells costumer their total price with tax
double costWithTax = (costNoTax + taxCost);
System.out.println("Total: " + "$" + costWithTax);
//Determines which message to give user based on diameter of pizza
if(pizzaSize >= 1 && pizzaSize <= 20){
System.out.println("We are going to make you a cute little pizza!");
} else if(pizzaSize >= 21 && pizzaSize <= 40){
System.out.println("This will be delicious!");
} else {
System.out.println("Woah, big pizza! You might need a truck to get this home!");
}
}
}
|
package com.example.demo.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.work;
import com.example.demo.services.workServices;
@CrossOrigin(origins="http://localhost:3000")
@RestController
@RequestMapping("/admin")
public class workControllers {
@Autowired
workServices workservices;
@PostMapping
public ResponseEntity<work> creatework(@RequestBody work data) {
return workservices.creatework(data);
}
@GetMapping
public ResponseEntity<List<work>> getallwork () {
return workservices.getallwork();
}
@GetMapping(params = "id")
public ResponseEntity<work> getworkbyidparams (@RequestParam String id) {
return workservices.getworkbyidparams(id);
}
@GetMapping(params = "title")
public ResponseEntity<List<work>> getWorkByTitle (@RequestParam String title) {
return workservices.getWorkByTitle(title);
}
@GetMapping("/{id}")
public ResponseEntity<work> getworkbyid (@PathVariable String id) {
return workservices.getworkbyid(id);
}
@PutMapping("/{id}")
public ResponseEntity<work> updatework (@PathVariable String id,@RequestBody work workers) {
return workservices.updatework(id, workers );
}
@DeleteMapping("/{id}")
public ResponseEntity<HttpStatus> deletework(@PathVariable("id") String id){
return workservices.deletebook(id);
}
// @GetMapping("/{search}")
// public ResponseEntity<?> worksearch (@PathVariable String search ,
// @RequestParam(value = "pageNo",defaultValue = "0") int pageNo,
// @RequestParam(value="pageSize" ,defaultValue = "0") int pageSize ,
// @RequestParam(name = "sortBy" , defaultValue = "id") String sortBy)
//{
//
// return workservices.getworksearch(search,pageNo,pageSize,sortBy);
//}
}
|
package com.revature.ers.dao;
import java.util.List;
import com.revature.ers.model.User;
public interface UserDao {
public List<User> getUsers();
public List<User> getUsersByCompanyId(int companyId);
public User getUser(int id);
public User getUser(String username);
public User getLastCreatedUser();
public boolean createUser(User user);
public boolean updateUser(int id, User user);
public boolean deleteUser(int id);
}
|
package yedamOracle.com;
public class NewJavaProgram {
public static void main(String[] args) {
int result, result2, num1, num2, num3;
num1 = 10;
num2 = 20;
num3 = 0;
result = num1 + (num2 * 3) + (30 / num1) - 10;
result2 = num1 % num2;
System.out.println(result);
System.out.println(result2);
System.out.println(num3++); // num4 값이 0 이다.
System.out.println(num3); // num4 값이 이전에 ++로 1이 들어가 있는 상태라서 1로 출력된다.
System.out.println(++num3); // num4 앞에 ++ 을 붙이면 1 된 상태로 추가된다 그래서 출력값이 2이다
result += 20;
System.out.println(result);
boolean bool1, bool2, bool3;
bool1 = (1 > num1);
bool2 = (1 < num1) && (10 < num2); // A 와 B 둘 모두 true 이면 결과는 true (AND연산)
bool3 = (1 < num1) || (10 < num2); // A 와 B 둘중 하나라도 true 이면 true (OR연산)
bool1 = !bool1; // 결과가 A가 true 면 false 반대로 A가 false 면 true (NOT연산)
System.out.println(bool1);
System.out.println(bool2);
System.out.println(bool3);
System.out.println(bool1);
if (!bool1)
System.out.println("result value true");
else
System.out.println("result value true");
// bit operation (& | ^ ~ )
int a = 3, b = 2;
result = a & b;
result2 = a | b;
System.out.println(a + "&" + b + "=" + result);
System.out.println(a + "&" + b + "=" + result2);
}
}
|
package ua.edu.ucu.smartarr;
import java.util.Arrays;
public class DistinctDecorator extends SmartArrayDecorator {
public DistinctDecorator(SmartArray smartArray) {
super(smartArray);
}
@Override
public Object[] toArray() {
return Arrays.stream(smartArray.toArray()).distinct().toArray();
}
@Override
public String operationDescription() {
return "Distinct " + smartArray.operationDescription();
}
@Override
public int size() {
return this.toArray().length;
}
}
|
package com.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import objects.Joueur;
public class Reception {
private ObjectInputStream obj_in;
public Reception(InputStream in) throws IOException {
this.obj_in = new ObjectInputStream(in);
}
public Joueur getJoueur() throws ClassNotFoundException, IOException
{
Object objRecu = this.obj_in.readObject();
if (!(objRecu instanceof Joueur))
return null;
return ((Joueur) objRecu);
}
public String getString() throws ClassNotFoundException, IOException
{
Object objRecu = this.obj_in.readObject();
if (!(objRecu instanceof String))
return null;
return ((String) objRecu);
}
public Integer getInt() throws ClassNotFoundException, IOException
{
Object objRecu = this.obj_in.readObject();
if (!(objRecu instanceof Integer))
return null;
return ((Integer) objRecu);
}
public void close() throws IOException {
this.obj_in.close();
}
}
|
/**
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
*/
class Solution {
public boolean isPalindrome(String s) {
if(s == null || s.length() == 0)
return true;
int head = 0, tail = s.length() - 1;
while(head <= tail){
char chead = s.charAt(head);
char ctail = s.charAt(tail);
if(!Character.isLetterOrDigit(chead))
head++;
else if(!Character.isLetterOrDigit(ctail)){
tail--;
}
else if(Character.toLowerCase(chead) != Character.toLowerCase(ctail))
return false;
else{
head++;
tail--;
}
}
return true;
}
}
|
package com.example.test;
import com.example.main.Calculate;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import javax.inject.Inject;
import static org.junit.jupiter.api.Assertions.assertEquals;
@MicronautTest
public class ReplaceTest {
@Inject
Calculate calculate;
@Test
void doSomething() {
assertEquals(1, calculate.doSomething());
}
}
|
package homework2;
//Gustavo Magalhaes Pereira. Circle2D.java
public class Circle2D {
public double x;
public double y;
public double radius;
public Circle2D () {
this.x = 0.0;
this.y = 0.0;
this.radius = 1.0;
}
public Circle2D (double x, double y, double radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getRadius() {
return radius;
}
public double getArea() {
return Math.PI*Math.pow(radius,2);
}
public double getPerimeter() {
return 2*Math.PI*radius;
}
public boolean contains(double x, double y) {
if (x <= this.radius && y <= this.radius)
if (x >= -this.radius && y >= -this.radius)
return true;
return false;
}
public boolean contains(Circle2D circle) {
if (circle.getRadius() <= this.radius) {
if (circle.getX()+circle.getRadius() <= this.radius) {
if (circle.getY()+circle.getRadius() <= this.radius) {
return true;
}
}
}
return false;
}
public boolean overlaps(Circle2D circle) {
double hypotenuse = Math.sqrt(Math.pow(this.x-circle.getX(),2)+Math.pow(this.y-circle.getY(),2));
if (this.radius+circle.getRadius() >= hypotenuse) {
return true;
}
return false;
}
public static void main(String[] args) {
Circle2D circle = new Circle2D();
System.out.println("X value: "+circle.getX());
System.out.println("Y value: "+circle.getY());
System.out.println("Radius: "+circle.getRadius());
System.out.println("Area: "+circle.getArea());
System.out.println("Perimeter: "+circle.getPerimeter());
System.out.println("(a): "+circle.contains(1,1));
Circle2D circle2 = new Circle2D(0.0,0.0,1.0);
System.out.println("(b): "+circle.contains(circle2));
System.out.println("(c): "+circle.overlaps(circle2));
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.maizegenetics.analysis.imputation;
import net.maizegenetics.dna.map.Chromosome;
import net.maizegenetics.dna.snp.*;
import net.maizegenetics.dna.snp.genotypecall.GenotypeCallTableBuilder;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.util.ArgsEngine;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;
import static net.maizegenetics.dna.snp.GenotypeTable.UNKNOWN_DIPLOID_ALLELE;
import static net.maizegenetics.dna.snp.GenotypeTableUtils.isHeterozygous;
import static net.maizegenetics.dna.snp.NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE;
/**
*
* @author kls283
*/
public class FILLINImputationAccuracyPlugin extends AbstractPlugin {
private String maskKeyFile;
private String unimpFile;
private String donorFile;
private String outFile;
private int appoxSitesPerDonorGenotypeTable;
private double propSitesMask;
private GenotypeTable maskKey= null;
private boolean verboseOutput= true;
String[] FILLINargs;
private static ArgsEngine engine = new ArgsEngine();
private static final Logger myLogger = Logger.getLogger(FILLINImputationPlugin.class);
public static class ImputationAccuracy {
//leaving MAF related objects in for now for future paper revisions
public static int[] MAF= null;
private static double[][] all= null; //arrays held ("columns"): 0-maskedMinor, 1-maskedHet, 2-maskedMajor; each array ("rows"):0-to minor, 1-to het, 2-to major, 3-unimp, 4-total for known type
private static double[][][] mafAll= null;//sam as all, but first array holds MAF category
private static String maskKeyFile;
private static String unimpFile;
private static String donorFile;
private static String outFile;
private static int appoxSitesPerDonorGenotypeTable;
private static double propSitesMask;
private static GenotypeTable maskKey= null;
private static double[] MAFClass= null;//new double[]{0,.02,.05,.10,.20,.3,.4,.5,1};
private static boolean verboseOutput= true;
public static void initiateAccuracy(String unimpFileName, String maskKeyFileName, String donorFileName, int hapSize, double[] mafClass, double propSitesMasked) {
maskKeyFile= maskKeyFileName;
unimpFile= unimpFileName;
donorFile= donorFileName;
appoxSitesPerDonorGenotypeTable= hapSize;
MAFClass= mafClass;
propSitesMask= propSitesMasked;
GenotypeTable unimp= ImportUtils.readGuessFormat(unimpFile);
System.out.println(unimpFile+" read in with "+unimp.numberOfSites()+" sites and "+unimp.numberOfTaxa()+" taxa");
if (mafClass!=null) {//if mafClass not null, assign MAF categories to sites in unimputed
GenotypeTable[] donors= FILLINDonorGenotypeUtils.loadDonors(donorFile, appoxSitesPerDonorGenotypeTable, verboseOutput);
generateMAF(donors, unimp, mafClass);
mafAll= new double[mafClass.length][3][5];
if (verboseOutput) System.out.println("Calculating accuracy within supplied MAF categories.");
}
//mask file if not already masked (depth or proportion) and generate key
if (maskKeyFile!=null) {
if (verboseOutput) System.out.println("File already masked. Use input key file for calculating accuracy");
maskKey= ImportUtils.readGuessFormat(maskKeyFile);
//TODO put in masking by depth (methods maskFIleByDepth() already exists)
if (Arrays.equals(maskKey.physicalPositions(), unimp.physicalPositions())==false) {
maskKey= filterKey(maskKey, unimp);
}
if (maskKey==null) {
FILLINImputationPlugin.unimpAlign= maskPropSites(unimp,propSitesMask);
}
}
//else if (unimp.depth()!=null) FILLINImputationPlugin.unimpAlign= maskFileByDepth(unimp,7, 7);
else FILLINImputationPlugin.unimpAlign= maskPropSites(unimp,propSitesMask);
}
private static void generateMAF(GenotypeTable[] donorAlign, GenotypeTable unimpAlign, double[] mafClass) {
MAF= new int[unimpAlign.numberOfSites()];
for (GenotypeTable don:donorAlign) {
for (int site = 0; site < don.numberOfSites(); site++) {
int unimpSite= unimpAlign.positions().indexOf(don.positions().get(site));
if (unimpSite < 0) {MAF[unimpSite]= -1; continue;}
int search= Arrays.binarySearch(mafClass, don.minorAlleleFrequency(site));
MAF[unimpSite]= search<0?Math.abs(search)-1:search;
}
}
}
//TODO when depth works. for depths 4 or more, requires hets to be called by more than one for less depth allele. returns 2-array whre index 0 is mask and 1 is key
private static GenotypeTable maskFileByDepth(GenotypeTable a, int depthToMask, int maskDenom) {
if (verboseOutput) System.out.println("Masking file using depth\nSite depth to mask: "+depthToMask+"Divisor for physical positions to be masked: "+maskDenom);
GenotypeCallTableBuilder mask= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites());
GenotypeCallTableBuilder key= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites());
int cnt= 0;
for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) {
int taxaCnt= 0;
mask.setBaseRangeForTaxon(taxon, 0, a.genotypeAllSites(taxon));
for (int site = 0; site < a.numberOfSites(); site++) {
if (GenotypeTableUtils.isEqual(NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE, a.genotype(taxon, site))) continue;
if (a.physicalPositions()[site]%maskDenom!=0) continue;
int[] currD= a.depthForAlleles(taxon, site);
if (currD[0]+currD[1]!=depthToMask) continue;
else if ((a.isHeterozygous(taxon, site)==false) ||
(depthToMask > 3 && currD[0] > 1 && currD[1] > 1)||
(depthToMask < 4)) {
mask.setBase(taxon, site, NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE); key.setBase(taxon, site, a.genotype(taxon, site)); taxaCnt++;
}
}
if (verboseOutput) System.out.println(taxaCnt+" sites masked for "+a.taxaName(taxon)); cnt+= taxaCnt;
}
if (verboseOutput) System.out.println(cnt+" sites masked at a depth of "+depthToMask+" (site numbers that can be divided by "+maskDenom+")");
maskKey= GenotypeTableBuilder.getInstance(key.build(), a.positions(), a.taxa());
return GenotypeTableBuilder.getInstance(mask.build(), a.positions(), a.taxa());
}
private static GenotypeTable maskPropSites(GenotypeTable a, double propSitesMask) {
if (verboseOutput) System.out.println("Masking file without depth\nMasking "+propSitesMask+" proportion of sites");
GenotypeCallTableBuilder mask= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites());
GenotypeCallTableBuilder key= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites());
int presGenos= 0;
for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) {presGenos+= a.totalNonMissingForTaxon(taxon);}
int expected= (int)(propSitesMask*(double)presGenos);
int cnt= 0;
for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) {
int taxaCnt= 0;
mask.setBaseRangeForTaxon(taxon, 0, a.genotypeAllSites(taxon));
for (int site = 0; site < a.numberOfSites(); site++) {
if (Math.random()<propSitesMask && GenotypeTableUtils.isEqual(NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE, a.genotype(taxon, site))==false) {
mask.setBase(taxon, site, NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE); key.setBase(taxon, site, a.genotype(taxon, site)); taxaCnt++;
}
}
cnt+= taxaCnt;
}
if (verboseOutput) System.out.println(cnt+" sites masked randomly not based on depth ("+expected+" expected at "+propSitesMask+")");
maskKey= GenotypeTableBuilder.getInstance(key.build(), a.positions(), a.taxa());
return GenotypeTableBuilder.getInstance(mask.build(), a.positions(), a.taxa());
}
//filters for site position and chromosome. returns null if mask has fewer chromosomes or positions in chromosomes than unimp
private static GenotypeTable filterKey(GenotypeTable maskKey, GenotypeTable unimp) {
if (verboseOutput) System.out.println("Filtering user input key file...\nsites in original Key file: "+maskKey.numberOfSites());
String[] unimpNames= new String[unimp.numberOfSites()];
for (int site = 0; site < unimp.numberOfSites(); site++) {unimpNames[site]= unimp.siteName(site);}
int[] unimpPos;
int[] keyPos;
ArrayList<String> keepSites= new ArrayList<>();
if (Arrays.equals(unimp.chromosomes(), maskKey.chromosomes())==false) maskKey= matchChromosomes(unimp, maskKey);
if (maskKey==null) return null;
for (Chromosome chr:unimp.chromosomes()) {
int[] startEndUnimp= unimp.firstLastSiteOfChromosome(chr); int[] startEndKey= maskKey.firstLastSiteOfChromosome(chr);
unimpPos= Arrays.copyOfRange(unimp.physicalPositions(), startEndUnimp[0], startEndUnimp[1]+1);
keyPos= Arrays.copyOfRange(maskKey.physicalPositions(), startEndKey[0], startEndKey[1]+1);
for (int posOnChr = 0; posOnChr < unimpPos.length; posOnChr++) {//if input hapmap sites not in key, return null
if (Arrays.binarySearch(keyPos, unimpPos[posOnChr])<0) return null;
}
for (int posOnChr = 0; posOnChr < keyPos.length; posOnChr++) {//if key site in input hapmap, retain
if (Arrays.binarySearch(unimpPos, keyPos[posOnChr])>-1) {
keepSites.add(maskKey.siteName(startEndKey[0]+posOnChr));
}
}
}
FilterGenotypeTable filter= FilterGenotypeTable.getInstance(maskKey, keepSites.toArray(new String[keepSites.size()]));
GenotypeTable newMask= GenotypeTableBuilder.getGenotypeCopyInstance(filter);
if (verboseOutput) System.out.println("Sites in new mask: "+newMask.numberOfSites());
return newMask;
}
private static GenotypeTable matchChromosomes(GenotypeTable unimp, GenotypeTable maskKey) {
Chromosome[] unimpChr= unimp.chromosomes();
Chromosome[] keyChr= maskKey.chromosomes();
ArrayList<Integer> keepSites= new ArrayList<>();
for (Chromosome chr:unimpChr) { //if any of the chromosomes in input do not exist in key, return null (which then masks proportion)
if (Arrays.binarySearch(keyChr, chr)<0) return null;
}
for (Chromosome chr:keyChr) { //keep sites on key that are on matching chromosomes
if (Arrays.binarySearch(unimpChr, chr)>-1) {
int[] startEnd = maskKey.firstLastSiteOfChromosome(chr);
for (int site = startEnd[0]; site <= startEnd[1]; site++) {
keepSites.add(site);
}
}
}
FilterGenotypeTable filter= FilterGenotypeTable.getInstance(maskKey, ArrayUtils.toPrimitive(keepSites.toArray(new Integer[keepSites.size()])));
GenotypeTable matchChr= GenotypeTableBuilder.getGenotypeCopyInstance(filter);
return matchChr;
}
//this is the sample multiple r2.
private static double pearsonR2(double[][] all) {
int size= 0;
for (int x = 0; x < 3; x++) {size+= (all[x][4]-all[x][3]);}
double[][] xy= new double[2][size]; //0 is x, 1 is y
int last= 0;//the last index filled
for (double x = 0; x < 3; x++) { for (double y = 0; y < 3; y++) {
for (int fill = last; fill < last+all[(int)x][(int)y]; fill++) {
xy[0][fill]= x;
xy[1][fill]= y;
}
last= last+(int)all[(int)x][(int)y];
}}
double meanX= 0; double meanY= 0; double varX= 0; double varY= 0; double covXY= 0; double r2= 0.0;
for (int i = 0; i < xy[0].length; i++) {meanX+=xy[0][i]; meanY+= xy[1][i];}
meanX= meanX/(xy[0].length-1); meanY= meanY/(xy[1].length-1);
double currX, currY;
for (int i = 0; i < xy[0].length; i++) {
currX= xy[0][i]-meanX; currY= xy[1][i]-meanY;
varX+= currX*currX; varY+= currY*currY;
covXY+= currX*currY;
}
r2= (covXY/(Math.sqrt(varX)*Math.sqrt(varY)))*(covXY/(Math.sqrt(varX)*Math.sqrt(varY)));
if (verboseOutput) System.out.println("Unadjusted R2 value for "+size+" comparisons: "+r2);
return r2;
}
private static void accuracyOut(double[][] all, double time) {
DecimalFormat df = new DecimalFormat("0.########");
double r2= pearsonR2(all);
try {
File outputFile = new File(outFile.substring(0, outFile.indexOf(".hmp")) + "DepthAccuracy.txt");
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
outStream.writeBytes("##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor"
+ "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2\n");
outStream.writeBytes("##TotalByImputed\t"+(all[0][4]+all[1][4]+all[2][4])+"\t"+(all[0][4]+all[1][4]+all[2][4]-all[0][3]-all[1][3]-all[2][3])+"\t"+
((all[0][3]+all[1][3]+all[2][3])/(all[0][4]+all[1][4]+all[2][4]))+"\t"+all[0][4]+"\t"+all[0][0]+"\t"+all[0][1]+"\t"+all[0][2]+"\t"+all[0][3]+
"\t"+all[1][4]+"\t"+all[1][0]+"\t"+all[1][1]+"\t"+all[1][2]+"\t"+all[1][3]+"\t"+all[2][4]+"\t"+all[2][0]+"\t"+all[2][1]+"\t"+all[2][2]+
"\t"+all[2][3]+"\t"+r2+"\n");
outStream.writeBytes("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n"
+0+"\t"+0+"\t"+all[0][0]+"\t"+df.format((all[0][0])/(all[0][0]+all[0][1]+all[0][2]))+"\n"
+0+"\t"+.5+"\t"+all[0][1]+"\t"+df.format((all[0][1])/(all[0][0]+all[0][1]+all[0][2]))+"\n"
+0+"\t"+1+"\t"+all[0][2]+"\t"+df.format((all[0][2])/(all[0][0]+all[0][1]+all[0][2]))+"\n"
+.5+"\t"+0+"\t"+all[1][0]+"\t"+df.format((all[1][0])/(all[1][0]+all[1][1]+all[1][2]))+"\n"
+.5+"\t"+.5+"\t"+all[1][1]+"\t"+df.format((all[1][1])/(all[1][0]+all[1][1]+all[1][2]))+"\n"
+.5+"\t"+1+"\t"+all[1][2]+"\t"+df.format((all[1][2])/(all[1][0]+all[1][1]+all[1][2]))+"\n"
+1+"\t"+0+"\t"+all[2][0]+"\t"+df.format((all[2][0])/(all[2][0]+all[2][1]+all[2][2]))+"\n"
+1+"\t"+.5+"\t"+all[2][1]+"\t"+df.format((all[2][1])/(all[2][0]+all[2][1]+all[2][2]))+"\n"
+1+"\t"+1+"\t"+all[2][2]+"\t"+df.format((all[2][2])/(all[2][0]+all[2][1]+all[2][2]))+"\n");
outStream.writeBytes("#Proportion unimputed:\n#minor <- "+all[0][3]/all[0][4]+"\n#het<- "+all[1][3]/all[1][4]+"\n#major<- "+all[2][3]/all[2][4]+"\n");
outStream.writeBytes("#Time to impute and calculate accuracy: "+time+" seconds");
if (verboseOutput) System.out.println("##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor"
+ "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2");
if (verboseOutput) System.out.println("TotalByImputed\t"+(all[0][4]+all[1][4]+all[2][4])+"\t"+(all[0][4]+all[1][4]+all[2][4]-all[0][3]-all[1][3]-all[2][3])+"\t"+
((all[0][3]+all[1][3]+all[2][3])/(all[0][4]+all[1][4]+all[2][4]))+"\t"+all[0][4]+"\t"+all[0][0]+"\t"+all[0][1]+"\t"+all[0][2]+"\t"+all[0][3]+
"\t"+all[1][4]+"\t"+all[1][0]+"\t"+all[1][1]+"\t"+all[1][2]+"\t"+all[1][3]+"\t"+all[2][4]+"\t"+all[2][0]+"\t"+all[2][1]+"\t"+all[2][2]+
"\t"+all[2][3]+"\t"+r2);
if (verboseOutput) System.out.println("Proportion unimputed:\nminor: "+all[0][3]/all[0][4]+"\nhet: "+all[1][3]/all[1][4]+"\nmajor: "+all[2][3]/all[2][4]);
if (verboseOutput) System.out.println("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n"
+0+"\t"+0+"\t"+all[0][0]+"\t"+(all[0][0])/(all[0][0]+all[0][1]+all[0][2])+"\n"
+0+"\t"+.5+"\t"+all[0][1]+"\t"+(all[0][1])/(all[0][0]+all[0][1]+all[0][2])+"\n"
+0+"\t"+1+"\t"+all[0][2]+"\t"+(all[0][2])/(all[0][0]+all[0][1]+all[0][2])+"\n"
+.5+"\t"+0+"\t"+all[1][0]+"\t"+(all[1][0])/(all[1][0]+all[1][1]+all[1][2])+"\n"
+.5+"\t"+.5+"\t"+all[1][1]+"\t"+(all[1][1])/(all[1][0]+all[1][1]+all[1][2])+"\n"
+.5+"\t"+1+"\t"+all[1][2]+"\t"+(all[1][2])/(all[1][0]+all[1][1]+all[1][2])+"\n"
+1+"\t"+0+"\t"+all[2][0]+"\t"+(all[2][0])/(all[2][0]+all[2][1]+all[2][2])+"\n"
+1+"\t"+.5+"\t"+all[2][1]+"\t"+(all[2][1])/(all[2][0]+all[2][1]+all[2][2])+"\n"
+1+"\t"+1+"\t"+all[2][2]+"\t"+(all[2][2])/(all[2][0]+all[2][1]+all[2][2])+"\n");
outStream.close();
} catch (Exception e) {
if (verboseOutput) System.out.println(e);
}
}
private static void accuracyMAFOut(double[][][] mafAll) {
DecimalFormat df = new DecimalFormat("0.########");
if (MAF!=null && MAFClass!=null) try {
File outputFile = new File(outFile.substring(0, outFile.indexOf(".hmp")) + "DepthAccuracyMAF.txt");
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
outStream.writeBytes("##\tMAFClass\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumHets\tHetToMinor\tHetToMajor\tCorrectHet\tUnimpHet\tNumMinor\tMinorToMajor\tMinorToHet\tCorrectMinor\t"
+ "UnimpMinor\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimputedMajor\tr2\n");
for (int i= 0; i<MAFClass.length;i++) {
outStream.writeBytes("##TotalByImputed\t"+MAFClass[i]+"\t"+(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4])+"\t"+(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4]-mafAll[i][0][3]-mafAll[i][1][3]-mafAll[i][2][3])+"\t"+
((mafAll[i][0][3]+mafAll[i][1][3]+mafAll[i][2][3])/(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4]))+"\t"+mafAll[i][0][4]+"\t"+mafAll[i][0][0]+"\t"+mafAll[i][0][1]+"\t"+mafAll[i][0][2]+"\t"+mafAll[i][0][3]+
"\t"+mafAll[i][1][4]+"\t"+mafAll[i][1][0]+"\t"+mafAll[i][1][1]+"\t"+mafAll[i][1][2]+"\t"+mafAll[i][1][3]+"\t"+mafAll[i][2][4]+"\t"+mafAll[i][2][0]+"\t"+mafAll[i][2][1]+"\t"+mafAll[i][2][2]+
"\t"+mafAll[i][2][3]+"\t"+pearsonR2(mafAll[i])+"\n");
}
outStream.writeBytes("#MAFClass,Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nMAF\tx\ty\tN\tprop\n");
for (int i= 0; i<MAFClass.length;i++) { outStream.writeBytes(
MAFClass[i]+"\t"+0+"\t"+0+"\t"+mafAll[i][0][0]+"\t"+df.format((mafAll[i][0][0])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n"
+MAFClass[i]+"\t"+0+"\t"+.5+"\t"+mafAll[i][0][1]+"\t"+df.format((mafAll[i][0][1])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n"
+MAFClass[i]+"\t"+0+"\t"+1+"\t"+mafAll[i][0][2]+"\t"+df.format((mafAll[i][0][2])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n"
+MAFClass[i]+"\t"+.5+"\t"+0+"\t"+mafAll[i][1][0]+"\t"+df.format((mafAll[i][1][0])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n"
+MAFClass[i]+"\t"+.5+"\t"+.5+"\t"+mafAll[i][1][1]+"\t"+df.format((mafAll[i][1][1])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n"
+MAFClass[i]+"\t"+.5+"\t"+1+"\t"+mafAll[i][1][2]+"\t"+df.format((mafAll[i][1][2])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n"
+MAFClass[i]+"\t"+1+"\t"+0+"\t"+mafAll[i][2][0]+"\t"+df.format((mafAll[i][2][0])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n"
+MAFClass[i]+"\t"+1+"\t"+.5+"\t"+mafAll[i][2][1]+"\t"+df.format((mafAll[i][2][1])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n"
+MAFClass[i]+"\t"+1+"\t"+1+"\t"+mafAll[i][2][2]+"\t"+df.format((mafAll[i][2][2])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n");
}
outStream.writeBytes("#Proportion unimputed:\n#MAF\tminor\thet\tmajor\n");
for (int i= 0; i<MAFClass.length;i++) {
outStream.writeBytes("#"+MAFClass[i]+"\t"+mafAll[i][0][3]/mafAll[i][0][4]+"\t"+mafAll[i][1][3]/mafAll[i][1][4]+"\t"+mafAll[i][2][3]/mafAll[i][2][4]+"\n");
}
outStream.flush();
outStream.close();
} catch (Exception e) {
if (verboseOutput) System.out.println(e);
}
}
public static void checkForMAF() {
//todo exposing these variables publicly needs to be fixed
// if (MAFClass!=null) {//if mafClass not null, assign MAF categories to sites in unimputed
// generateMAF(FILLINImputationPlugin.donorAlign, FILLINImputationPlugin.unimpAlign, MAFClass);
// mafAll= new double[MAFClass.length][3][5];
// if (verboseOutput) System.out.println("Calculating accuracy within supplied MAF categories.");
// }
}
public static double calcAccuracy(GenotypeTable imputed, GenotypeTable unimpAlign, double runtime) {
all= new double[3][5];
byte diploidN= GenotypeTable.UNKNOWN_DIPLOID_ALLELE;
boolean use= false; boolean mafOn= false; int maf= -1;
checkForMAF();
if (mafAll!=null) {use= true; mafOn= true;}
for (int taxon = 0; taxon < imputed.numberOfTaxa(); taxon++) {
int keyTaxon= maskKey.taxa().indexOf(imputed.taxaName(taxon));//if key file contains fewer taxa, or different numbers, or different order
if (keyTaxon<0) continue;//if doesn't exist, skip
for (int site = 0; site < imputed.numberOfSites(); site++) {
use= (mafOn && MAF[site] > -1)?true:false;
if (use) maf= MAF[site];
byte known = maskKey.genotype(keyTaxon, site);
if (known == diploidN) continue;
byte imp = imputed.genotype(taxon, site);
if (GenotypeTableUtils.isHeterozygous(known) == true) {
all[1][4]++; if (use) mafAll[maf][1][4]++;
if (imp == diploidN) {all[1][3]++; if (use) mafAll[maf][1][3]++;}
else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[1][1]++; if (use) mafAll[maf][1][1]++;}
else if (GenotypeTableUtils.isHeterozygous(imp) == false && GenotypeTableUtils.isPartiallyEqual(imp, unimpAlign.minorAllele(site)) == true) {all[1][0]++; if (use) mafAll[maf][1][0]++;}//to minor
else if (GenotypeTableUtils.isHeterozygous(imp) == false && GenotypeTableUtils.isPartiallyEqual(imp, unimpAlign.majorAllele(site)) == true) {all[1][2]++; if (use) mafAll[maf][1][2]++;}
else {all[1][4]--; if (use) mafAll[maf][1][4]--;}//implies >2 allele states at given genotype
} else if (known == GenotypeTableUtils.getDiploidValue(unimpAlign.minorAllele(site),unimpAlign.minorAllele(site))) {
all[0][4]++; if (use) mafAll[maf][0][4]++;
if (imp == diploidN) {all[0][3]++; if (use) mafAll[maf][0][3]++;}
else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[0][0]++; if (use) mafAll[maf][0][0]++;}
else if (GenotypeTableUtils.isHeterozygous(imp) == true && GenotypeTableUtils.isPartiallyEqual(imp, known) == true) {all[0][1]++; if (use) mafAll[maf][0][1]++;}
else {all[0][2]++; if (use) mafAll[maf][0][3]++;}
} else if (known == GenotypeTableUtils.getDiploidValue(unimpAlign.majorAllele(site),unimpAlign.majorAllele(site))) {
all[2][4]++; if (use) mafAll[maf][2][4]++;
if (imp == diploidN) {all[2][3]++; if (use) mafAll[maf][2][3]++;}
else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[2][2]++; if (use) mafAll[maf][2][2]++;}
else if (GenotypeTableUtils.isHeterozygous(imp) == true && GenotypeTableUtils.isPartiallyEqual(imp, known) == true) {all[2][1]++; if (use) mafAll[maf][2][1]++;}
else {all[2][0]++; if (use) mafAll[maf][2][0]++;}
} else continue;
}
}
accuracyOut(all, runtime);
if (MAFClass!=null) accuracyMAFOut(mafAll);
return pearsonR2(all);
}
public static double[] propUnimp() {
if (all==null) {System.out.println("accuracy has not been computed"); return null;}
double[] propUnimp= new double[4];
int unimp= 0; int total= 0;
for (int allele = 0; allele < all.length; allele++) {
propUnimp[allele]= all[allele][3]/all[allele][4];
unimp+= all[allele][3]; total+= all[allele][4];;
}
propUnimp[3]= unimp/total;
return propUnimp;
}
public static double R2() {
if (all==null) {System.out.println("accuracy has not been computed"); return -1;}
return pearsonR2(all);
}
}
@Override
public void setParameters(String[] args) {
FILLINargs= Arrays.copyOf(args, args.length);
if (args.length == 0) {
printUsage();
throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n");
}
engine.add("-hmp", "-hmpFile", true);
engine.add("-o", "--outFile", true);
engine.add("-d", "--donorH", true);
engine.add("-maskKeyFile", "--maskKeyFile", true);
engine.add("-propSitesMask", "--propSitesMask", true);
engine.add("-mxHet", "--hetThresh", true);
engine.add("-minMnCnt", "--minMnCnt", true);
engine.add("-mxInbErr", "--mxInbErr", true);
engine.add("-mxHybErr", "--mxHybErr", true);
engine.add("-hybNNOff", "--hybNNOff", true);
engine.add("-mxDonH", "--mxDonH", true);
engine.add("-mnTestSite", "--mnTestSite", true);
engine.add("-projA", "--projAlign", false);
engine.add("-runChrMode", "--runChrMode", false);
engine.add("-nV", "--nonVerbose",false);
engine.add("-hapSize", "--hapSize",true);
engine.parse(args);
unimpFile = engine.getString("-hmp");
donorFile= engine.getString("-d");
outFile = engine.getString("-o");
maskKeyFile = engine.getString("-maskKeyFile");
if (engine.getBoolean("-hapSize")) {
appoxSitesPerDonorGenotypeTable = Integer.parseInt(engine.getString("-hapSize"));
}
if(engine.getBoolean("-propSitesMask")) {
propSitesMask = Double.parseDouble(engine.getString("-propSitesMask"));
}
if (engine.getBoolean("-nV")) verboseOutput=false;
}
private void printUsage() {
myLogger.info(
"\n\n\nThis plugin masks files, calls FILLINImputationPlugin and calculates accuracy by unadjusted R2 at masked sites.\n"
+ "If not provided with a masked file and associated key file, random sites masked. \n"
+ "If masked data provided, please set masked sites to missing in the file for imputation and indicate masked sites bynon-missing genotypes in the associated key file.\n"
+ "Available options for the FILLINImputationAccuracyPlugin are as follows:\n"
+ "-hmp Input HapMap file of target genotypes to impute. Accepts all file types supported by TASSEL5\n"
+ "-d Donor haplotype files from output of FILLINFindHaplotypesPlugin. Use .gX in the input filename to denote the substring .gc#s# found in donor files\n"
+ "-o Output file; hmp.txt.gz and .hmp.h5 accepted. Required\n"
+ "-hapSize Preferred haplotype block size in sites when a single donor file is used (e.g. phased whole genome) \n"
+ "-maskKeyFile An optional key file to indicate that file is already masked for accuracy calculation. Non-missing genotypes indicate masked sites. Else, will generate own mask\n"
+ "-propSitesMask The proportion of non missing sites to mask for accuracy calculation if depth is not available (default:"+propSitesMask+"\n"
+ "-mxHet Threshold per taxon heterozygosity for treating taxon as heterozygous (no Viterbi, het thresholds)\n"
+ "-minMnCnt Minimum number of informative minor alleles in the search window\n"
+ "-mxInbErr Maximum error rate for applying one haplotype to entire site window\n"
+ "-mxHybErr Maximum error rate for applying Viterbi with to haplotypes to entire site window\n"
+ "-hybNNOff Whether to model two haplotypes as heterozygotic for focus blocks\n"
+ "-mxDonH Maximum number of donor hypotheses to be explored\n"
+ "-mnTestSite Minimum number of sites to test for IBS between haplotype and target in focus block\n"
+ "-projA Create a projection alignment for high density markers (default off)\n"
+ "-nV Supress system out if flagged\n"
);
}
@Override
public DataSet performFunction(DataSet input) {
try {
long time=System.currentTimeMillis();
FILLINImputationPlugin FILLIN = new FILLINImputationPlugin();
FILLIN.setParameters(FILLINargs);
ImputationAccuracy.initiateAccuracy(unimpFile, maskKeyFile, donorFile, appoxSitesPerDonorGenotypeTable, null, propSitesMask);
FILLIN.performFunction(null);
double runtime= (double)(System.currentTimeMillis()-time)/(double)1000;
ImputationAccuracy.calcAccuracy(ImportUtils.readGuessFormat(outFile),FILLINImputationPlugin.unimpAlign,runtime);
}
finally {
fireProgress(100);
}
return null;
}
@Override
public ImageIcon getIcon() {
return null;
}
@Override
public String getButtonName() {
return "ImputeByFILLIN";
}
@Override
public String getToolTipText() {
return "Imputation that relies on a combination of HMM and Nearest Neighbor";
}
/**
* Legacy approach for measuring accuracy, but need to maintain some tests.
* @deprecated
*/
@Deprecated
public static int[] compareAlignment(String origFile, String maskFile, String impFile, boolean noMask) {
boolean taxaOut=false;
GenotypeTable oA=ImportUtils.readGuessFormat(origFile);
System.out.printf("Orig taxa:%d sites:%d %n",oA.numberOfTaxa(),oA.numberOfSites());
GenotypeTable mA=null;
if(noMask==false) {mA=ImportUtils.readGuessFormat(maskFile);
System.out.printf("Mask taxa:%d sites:%d %n",mA.numberOfTaxa(),mA.numberOfSites());
}
GenotypeTable iA=ImportUtils.readGuessFormat(impFile);
System.out.printf("Imp taxa:%d sites:%d %n",iA.numberOfTaxa(),iA.numberOfSites());
int correct=0;
int errors=0;
int unimp=0;
int hets=0;
int gaps=0;
for (int t = 0; t < iA.numberOfTaxa(); t++) {
int e=0,c=0,u=0,h=0;
int oATaxa=oA.taxa().indexOf(iA.taxaName(t));
for (int s = 0; s < iA.numberOfSites(); s++) {
if(noMask||(oA.genotype(oATaxa, s)!=mA.genotype(t, s))) {
byte ib=iA.genotype(t, s);
byte ob=oA.genotype(oATaxa, s);
if((ib==UNKNOWN_DIPLOID_ALLELE)||(ob==UNKNOWN_DIPLOID_ALLELE)) {unimp++; u++;}
else if(ib==GAP_DIPLOID_ALLELE) {gaps++;}
else if(ib==ob) {
correct++;
c++;
} else {
if(isHeterozygous(ob)||isHeterozygous(ib)) {hets++; h++;}
else {errors++;
e++;
// if(t==0) System.out.printf("%d %d %s %s %n",t,s,oA.getBaseAsString(oATaxa, s), iA.getBaseAsString(t, s));
}
}
}
}
if(taxaOut) System.out.printf("%s %d %d %d %d %n",iA.taxaName(t),u,h,c,e);
}
System.out.println("MFile\tIFile\tGap\tUnimp\tUnimpHets\tCorrect\tErrors");
System.out.printf("%s\t%s\t%d\t%d\t%d\t%d\t%d%n",maskFile, impFile, gaps, unimp,hets,correct,errors);
return new int[]{gaps, unimp,hets,correct,errors};
}
/**
* Calculates proportion imputed, homozygous proportion right, heterozygous proportion right
* @param impGT
* @param keyGT
* @return
* @deprecated a similar method is need in the core part of accuracy.
*/
@Deprecated
public static double[] compareAlignment(GenotypeTable impGT, GenotypeTable keyGT, String taxaPrefix) {
int hetKeys=0, hetCompared=0, hetRight=0;
int homoKeys=0, homoCompared=0, homoRight=0;
//if(impGT.numberOfTaxa()!=keyGT.numberOfTaxa()) throw new InputMismatchException("Number of Taxa do not match");
if(impGT.numberOfSites()!=keyGT.numberOfSites()) throw new InputMismatchException("Number of Sites do not match");
Random r=new Random();
for (int t=0; t<impGT.numberOfTaxa(); t++) {
if(taxaPrefix!=null && !impGT.taxaName(t).startsWith(taxaPrefix)) continue;
int tCompStart=homoCompared;
int tHomoRightStart=homoRight;
int key_t=keyGT.taxa().indexOf(impGT.taxaName(t));
if(key_t<0) continue;
//key_t=r.nextInt(impGT.numberOfTaxa());
//System.out.print(impGT.taxaName(t)+"\t"+keyGT.taxaName(t));
boolean report=impGT.taxaName(t).startsWith("XZ009E0126");
for (int s=0; s<impGT.numberOfSites(); s++) {
byte keyB=keyGT.genotype(key_t,s);
if(keyB==UNKNOWN_DIPLOID_ALLELE) continue;
byte impB=impGT.genotype(t,s);
if(isHeterozygous(keyB)) {
hetKeys++;
if(impB!=UNKNOWN_DIPLOID_ALLELE) {
hetCompared++;
if(keyB==impB) hetRight++;
}
} else {
homoKeys++;
if(impB!=UNKNOWN_DIPLOID_ALLELE) {
homoCompared++;
if(keyB==impB) homoRight++;
if(report) {
if(keyB!=impB) {System.out.print("Wrong\t");} else {System.out.print("Right\t");}
System.out.printf("%s %d %s %s %n",
impGT.chromosome(s).getName(),
impGT.chromosomalPosition(s),
NucleotideAlignmentConstants.getNucleotideIUPAC(keyB),
NucleotideAlignmentConstants.getNucleotideIUPAC(impB));
}
// if(keyB!=impB) System.out.printf("Wrong: %s %s %n",
// NucleotideAlignmentConstants.getNucleotideIUPAC(keyB),
// NucleotideAlignmentConstants.getNucleotideIUPAC(impB));
}
}
}
//System.out.println("\t"+(homoCompared-tCompStart)+"\t"+(homoRight-tHomoRightStart));
}
double totalKey=hetKeys+homoKeys;
double propImp=(double)(hetCompared+homoCompared)/totalKey;
double homoRightProp=(double)homoRight/(double)homoCompared;
double hetRightProp=(double)hetRight/(double)hetCompared;
return new double[]{propImp,homoRightProp,hetRightProp};
}
}
|
/**
*
*/
package de.jaroso.example.cxf.exceptions;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* ExceptionHandler
*
* <p>
* <i><small>Copyright (c) 2015 Jaroso GmbH</small></i> <br>
* <i><small>http://www.jaroso.de </small></i>
* <p>
*
* @author Marco Nitschke (m.nitschke@jaroso.de)
* @version $Revision: $ $Date: $ $Id: $
*/
@Provider
public class AFJobNotFoundExceptionHandler implements ExceptionMapper<AFJobNotFoundException> {
/*
* (non-Javadoc)
*
* @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
*/
@Override
public Response toResponse(AFJobNotFoundException exception) {
return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).type(MediaType.APPLICATION_JSON).build();
}
}
|
/*
* @Title: DateJsonDeserializer.java
* @Package: com.scf.core.serializer.json
* @author wubin
* @date 2016年9月13日 下午5:15:55
* @version 1.3.1
*/
package com.scf.core.serializer.support;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.scf.utils.DatetimeUtilies;
import com.scf.utils.ExceptionsUtilies;
/**
* json日期反序列化
* @author wubin
* @date 2016年9月13日 下午5:15:55
* @version V1.1.0
*/
public class DateTimeJsonDeserializer extends JsonDeserializer<Date> {
public static final SimpleDateFormat format = new SimpleDateFormat(DatetimeUtilies.DATE_TIME);
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
try {
return format.parse(jsonParser.getText());
} catch (ParseException e) {
throw ExceptionsUtilies.unchecked(e);
}
}
}
|
package com.cursodeandroid.whatsapp.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.cursodeandroid.whatsapp.R;
import com.cursodeandroid.whatsapp.adapter.MessageAdapter;
import com.cursodeandroid.whatsapp.config.FirebaseConfiguration;
import com.cursodeandroid.whatsapp.helper.Base64Custom;
import com.cursodeandroid.whatsapp.helper.Preferences;
import com.cursodeandroid.whatsapp.model.Message;
import com.cursodeandroid.whatsapp.model.Talk;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class TalkActivity extends AppCompatActivity {
private androidx.appcompat.widget.Toolbar toolbar;
//dados do destinatario
private String destName;
private String destId;
private String senderId;
private String senderName;
private DatabaseReference firebase;
private EditText editMessage;
private ImageButton btSend;
private ListView listView;
private ArrayList<Message> messages;
private ArrayAdapter<Message> adapter;
private ValueEventListener valueEventListenerMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_talk);
toolbar = findViewById(R.id.tb_talk);
editMessage = findViewById(R.id.editmessage);
btSend = findViewById(R.id.btsend);
listView = findViewById(R.id.lvtalks);
//dados do usuario logado
Preferences preferences = new Preferences(TalkActivity.this);
senderId = preferences.getIdent();
senderName= preferences.getName();
Bundle extra = getIntent().getExtras();
if (extra != null){
destName = extra.getString("name");
String destEmail = extra.getString("email");
destId = Base64Custom.encodeBase64(destEmail);
}
//Configura ToolBar
toolbar.setTitle(destName);
toolbar.setNavigationIcon(R.drawable.ic_action_arrow_left);
setSupportActionBar(toolbar);
//Monta lista de mensagens
messages = new ArrayList<>();
//adapter = new ArrayAdapter(TalkActivity.this, android.R.layout.simple_list_item_1, messages);
adapter = new MessageAdapter(TalkActivity.this, messages);
listView.setAdapter(adapter);
//Recuperar mensagens do firebase
firebase = FirebaseConfiguration.getFirebase().child("messages").child(senderId).child(destId);
//Listerner para mensagens
valueEventListenerMessage = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//Limpar Mensagens
messages.clear();
for (DataSnapshot dados:dataSnapshot.getChildren()){
Message message = dados.getValue(Message.class);
messages.add(message);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
firebase.addValueEventListener(valueEventListenerMessage);
//Envia Mensagem
btSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textMessage = editMessage.getText().toString();
if (textMessage.isEmpty()){
Toast.makeText(TalkActivity.this,"Digite uma Mensagem", Toast.LENGTH_LONG).show();
}
else{
Message message = new Message();
message.setIduser(senderId);
message.setMessage(textMessage);
Boolean returnSenderMessage = saveMesssage (senderId,destId,message);
if (!returnSenderMessage){
Toast.makeText(TalkActivity.this,"Mensagem nao foi salva para o remetente",Toast.LENGTH_LONG).show();
}else {
Boolean returnDestMessage = saveMesssage(destId, senderId, message);
if (!returnDestMessage){
Toast.makeText(TalkActivity.this,"Mensagem nao foi salva para o destinatário",Toast.LENGTH_LONG).show();
}
//salvar Conversa do remetente
Talk talk = new Talk();
talk.setUserId(destId);
talk.setName(destName);
talk.setMessage(textMessage);
Boolean returnSenderTalk = saveTalk(senderId,destId,talk);
if(!returnSenderTalk){
Toast.makeText(TalkActivity.this,"Conversa nao foi salva para o remetente",Toast.LENGTH_LONG).show();
}else{
talk = new Talk();
talk.setUserId(senderId);
talk.setName(senderName);
talk.setMessage(textMessage);
saveTalk(destId,senderId,talk);
//Salva Conversa para o destinatário
Boolean returnDestTalk = saveTalk(destId,senderId,talk);
if(!returnDestTalk){
Toast.makeText(TalkActivity.this,"Conversa nao foi salva para o Destinatário",Toast.LENGTH_LONG).show();}
}
editMessage.setText("");
}
}
}
});
}
private boolean saveMesssage(String senderId, String destId, Message message){
try
{
firebase = FirebaseConfiguration.getFirebase().child("messages");
firebase.child(senderId).child(destId).push().setValue(message);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
private boolean saveTalk(String senderId, String destId, Talk talk){
try{
firebase = FirebaseConfiguration.getFirebase().child("talks");
firebase.child(senderId).child(destId).setValue(talk);
return true;
}catch (Exception e ) {
e.printStackTrace();
return false;
}
}
@Override
protected void onStop() {
super.onStop();
firebase.removeEventListener(valueEventListenerMessage);
}
}
|
package merge_sorted_arrays;
import java.util.Arrays;
// https://www.interviewcake.com/question/merge-sorted-arrays
public class App {
public static void main(String[] args) {
int[] my_list = { 3, 4, 6, 10, 11, 15 };
int[] alices_list = { 1, 5, 8, 12, 14, 19 };
int[] merged_list = merge_lists(my_list, alices_list);
System.out.println("my_list: " + Arrays.toString(my_list));
System.out.println("alices_list: " + Arrays.toString(alices_list));
System.out.println("merged_list: " + Arrays.toString(merged_list));
}
public static int[] merge_lists(int[] my_list, int[] alices_list) {
int[] merged_list = new int[my_list.length + alices_list.length];
int i = 0;
int j = 0;
int k = 0;
while (i < my_list.length && j < alices_list.length) {
if (my_list[i] < alices_list[j]) {
merged_list[k] = my_list[i];
i++;
}
else {
merged_list[k] = alices_list[j];
j++;
}
k++;
}
while (i < my_list.length) {
merged_list[k] = my_list[i];
i++;
k++;
}
while (j < alices_list.length) {
merged_list[k] = alices_list[j];
j++;
k++;
}
return merged_list;
}
}
|
package cn.com.xbed.vo;
/**
* @Description:
* @author:Tom
* @create 2017-03-06 19:26
**/
public class User {
}
|
package no.uninett.adc.neo.dao;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
@Configuration
@ComponentScan(basePackages = "no.uninett.adc.neo.domain")
@EnableNeo4jRepositories(basePackages = "no.uninett.adc.neo.dao")
public class AppConfigTest extends Neo4jConfiguration {
public AppConfigTest() {
setBasePackage("no.uninett.adc.neo.domain");
}
@Bean
public GraphDatabaseService graphDatabaseService() {
return new TestGraphDatabaseFactory().newImpermanentDatabase();
}
// @Bean
// public ConversionServiceFactoryBean conversionService() {
// final Set converters = new HashSet();
//
// converters.add(new IntegerToChangeOperation());
// converters.add(new IntegerToChangeStateCode());
//
// converters.add(new ChangeOperationToInteger());
// converters.add(new ChangeStateCodeToInteger());
//
// final ConversionServiceFactoryBean bean = new
// ConversionServiceFactoryBean();
// bean.setConverters(converters);
// return bean;
// }
}
|
package com.allstate;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sameer on 2/1/17.
*/
public class Portfolio {
private String name;
public Map<String, Integer> getMapOfStocks() {
return mapOfStocks;
}
public Portfolio(String name) {
this.name = name;
}
private Map<String, Integer> mapOfStocks= new HashMap<String, Integer>();
public void addStock(String name, int noOfShares) {
if(mapOfStocks.containsKey(name)) {
int number = mapOfStocks.get(name);
number += noOfShares;
mapOfStocks.put(name, number);
} else {
mapOfStocks.put(name, noOfShares);
}
}
public boolean sellStock(String name, int noOfShares) {
if(mapOfStocks.containsKey(name) && mapOfStocks.get(name) >= noOfShares) {
int number = mapOfStocks.get(name);
number -= noOfShares;
mapOfStocks.put(name,number);
return true ;
}
return false ;
}
public String getName() {
return name;
}
}
|
package iuh.edu.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import iuh.edu.entity.DonHang;
@Repository
public class DonHangDao {
@Autowired
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<DonHang> getAll(){
return template.query("select * from DonHang", new RowMapper<DonHang>() {
public DonHang mapRow(ResultSet rs, int row) throws SQLException{
DonHang s=new DonHang();
s.setMaDonHang(rs.getString(1));
s.setTenDangNhap(rs.getString(2));
s.setTenKhachHang(rs.getString(3));
s.setDiaChi(rs.getString(4));
s.setSoDienThoai(rs.getString(5));
s.setEmail(rs.getString(6));
s.setThanhTien(rs.getDouble(7));
return s;
}
});
}
public String getMaDonHangMoiNhat(){
String sql ="SELECT TOP 1 [MaDonHang], [TenDangNhap],[TenKhachHang],[DiaChi],[SoDienThoai],[Email], [ThanhTien] FROM [dbo].[DonHang] \r\n" +
"ORDER BY [MaDonHang] DESC";
DonHang dh=template.queryForObject(sql, new BeanPropertyRowMapper<DonHang>(DonHang.class));
return dh.getMaDonHang();
}
public int save(DonHang s)
{
String sql="insert into DonHang ( TenDangNhap, TenKhachHang, DiaChi, SoDienThoai, Email, ThanhTien) values('"
+s.getTenDangNhap()+"','"+s.getTenKhachHang()+"','"+s.getDiaChi()+"','"+s.getSoDienThoai()+"','"+s.getEmail()+"','"+s.getThanhTien()+"')";
return template.update(sql);
}
}
|
public class InstanceAndClassVariables {
// Instance and a class variable don't have to be initialized because when they are declared they have a default value.
/* Default initialization.
boolean default false
byte, short, int, long, default 0
float double 0.0
char 'u\u0000' (NUL)
Everything else null
*/
// Variable scope
public void glass (int piecesOfGlass) {
int BrokenGlass = 1;
}
/* In this case there are two local variables, one is in a method see void eat (int PiecesOfGlass)
It makes it also method parameter. So the method is eat and the method parameter is int PiecesOfGlass
Second parameter is int Broken Glass. Void is saying that a method should not have a return value.
*/
}
public void useIfNeeded(boolean needed) {
if(needed) {
int brokenGlass =1;
} //brokenGlass is now 'outside' the scope of the method.
System.out.println(brokenglass); /* This will not be printed out because brokenGlass is declared in the scope of
if and not in the scope of the boolean. So its in another block of code. */
}
public class stadium
static int MAX_CAPACITY = 2000;
int capacity;
public void visitors(int realcapacity) {
if (capacity < MAX_CAPACITY) {
int newCapacity = capacity + realcapacity;
capacity = newCapacity;
}
/* This class has a class variable , instance variable and two local variable.
The class variable is MAX_Capacity , because there is a static in its declaration. Static means that it can be
accessed without creating a object or class. It is declared on line 32 and stays in the scope until the program
ends.
The instance variable is capacity and it is declared on line 33, instance variable is a variable what is used
in a class but not in a method.
The local variables are realcapacity and newcapacity because its only used in the method. Other parts are not
aware of these variables.
*/
}
|
package edu.mit.cameraCulture.vblocks.predefined;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import edu.mit.cameraCulture.vblocks.EngineActivity;
import edu.mit.cameraCulture.vblocks.Module;
import edu.mit.cameraCulture.vblocks.Sample;
public class ColorBlobDetector extends Module {
public static final String REGISTER_SERVICE_NAME = "Color Blob Detection";
private int imgWidth;
private int imgHeight;
private Scalar mLowerBound;
private Scalar mUpperBound;
private Mat mRgb_Mat;
private Mat mPyrDownMat;
private Mat mHsvMat;
private Mat mMask;
private Mat mDilatedMask;
private Mat outPut_area;
private Mat outPut_found;
private Mat outPut_rect;
private List<MatOfPoint> mContours;
private Mat mHierarchy;
private float minX, maxX, minY, maxY;
private int[] pos = new int[2];
private float[] posOutMin = new float[2];
private float[] posOutMax = new float[2];
private float[] outArea = new float[1];
private Mat mYuv;
private ColorBlobView view;
public ColorBlobDetector() {
super(REGISTER_SERVICE_NAME);
// TODO Auto-generated constructor stub
}
@OutputBool(vars = { "Found" })
@OutputMat(vars = { "RECT" })
@OutputInt(vars = { "Area" })
public ExecutionCode execute(Sample image) {
mRgb_Mat = image.getRgbMat();
synchronized (mRgb_Mat) {
Imgproc.pyrDown(mRgb_Mat, mPyrDownMat);
Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);
Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);
Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
Imgproc.dilate(mMask, mDilatedMask, new Mat());
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(mDilatedMask, contours, mHierarchy,
Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Find max contour area
double maxArea = 0;
Iterator<MatOfPoint> each = contours.iterator();
while (each.hasNext()) {
MatOfPoint wrapper = each.next();
double area = Imgproc.contourArea(wrapper);
if (area > maxArea)
maxArea = area;
}
mContours.clear();
if (maxArea > 10) {
outArea[0] = (float) maxArea;
outPut_area.put(0, 0, outArea);
image.setMat("Area", outPut_area);
// outPut_found.put(0, 0, 1);
image.setMat("Found", outPut_found);
each = contours.iterator();
while (each.hasNext()) {
MatOfPoint contour = each.next();
if (Imgproc.contourArea(contour) > 0.9 * maxArea) {
Core.multiply(contour, new Scalar(4, 4), contour);
mContours.add(contour);
contour.get(0, 0, pos);
minX = pos[0];
maxX = pos[0];
minY = pos[1];
maxY = pos[1];
for (int i = 1; i < contour.rows(); i++) {
contour.get(i, 0, pos);
if (minX > pos[0])
minX = pos[0];
if (maxX < pos[0])
maxX = pos[0];
// contour.get(i, 0, pos);
if (minY > pos[1])
minY = pos[1];
if (maxY < pos[1])
maxY = pos[1];
}
// outPut_rect.put(0, 0, minX); outPut_rect.put(0, 1,
// minY);
// outPut_rect.put(1, 0, maxX); outPut_rect.put(1, 1,
// maxY);
posOutMin[0] = minX;
posOutMin[1] = minY;
outPut_rect.put(0, 0, posOutMin);
posOutMax[0] = maxX;
posOutMax[1] = maxY;
outPut_rect.put(1, 0, posOutMax);
// Log.d("debug", "rect = (" + posOutMin[0] + ", " +
// posOutMin[1] + "), (" + posOutMax[0] + "," +
// posOutMax[1] + ")");
image.setMat("RECT", outPut_rect);
}
}
} else {
}
view.postInvalidate();
}
return null;
}
@Override
public String getName() {
return "Color Blob";
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
public static String getModuleName() {
return "Color Blob";
}
public void onCreate(EngineActivity context) {
super.onCreate(context);
mPyrDownMat = new Mat();
mHsvMat = new Mat();
mMask = new Mat();
mDilatedMask = new Mat();
mHierarchy = new Mat();
mLowerBound = new Scalar(0, 100, 100);
mUpperBound = new Scalar(30, 255, 255);
mContours = new ArrayList<MatOfPoint>();
outPut_area = new Mat(1, 1, CvType.CV_32FC1);
outPut_found = new Mat(1, 1, CvType.CV_32FC1);
outPut_rect = new Mat(2, 1, CvType.CV_32FC2);
view = new ColorBlobView(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
context.getLayout().addView(view, lp);
}
class ColorBlobView extends View {
Paint paint;
public ColorBlobView(Context context) {
super(context);
paint = new Paint();
paint.setARGB(255, 0, 255, 0);
paint.setStrokeWidth(3);
}
protected void onDraw(Canvas canvas) {
if (mYuv != null) {
float scaleH = canvas.getHeight() / imgHeight;
float scaleW = canvas.getWidth() / imgWidth;
float centerX = 0;
float centerY = 0;
for (int i = 0; i < mContours.size(); i++) {
centerX = 0;
centerY = 0;
Point[] points = mContours.get(i).toArray();
int nbPoints = points.length;
for (int j = 0; j < nbPoints; j++) {
Point v = points[j];
centerX += v.x;
centerY += v.y;
}
centerX /= nbPoints;
centerY /= nbPoints;
centerX *= scaleW;
centerY *= scaleH;
canvas.drawCircle(centerX, centerY, 30, paint);
}
}
}
}
}
|
package com.example.shreyesh.sarinstituteofmedicalscience;
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class AddPatientActivity extends AppCompatActivity {
private TextInputLayout patientName, patientEmail, patientPassword, patientConfirmPassword, patientPhone, patientAge;
private TextInputLayout patientAddress, patientNationality, patientTreatmentNeeded, patientDepartmentToVisit;
private Button registerPatient, reset;
private FirebaseAuth firebaseAuth;
private DatabaseReference patientRef;
private RadioButton maleButton, femaleButton, inpatientButton, outPatient;
private RadioGroup genderGroup, patientTypeGroup;
private Toolbar addPatientToolbar;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
//Initialize
patientAge = (TextInputLayout) findViewById(R.id.patientAge);
patientConfirmPassword = (TextInputLayout) findViewById(R.id.patientConfirmPassword);
patientEmail = (TextInputLayout) findViewById(R.id.patientEmail);
patientName = (TextInputLayout) findViewById(R.id.patientName);
patientPhone = (TextInputLayout) findViewById(R.id.patientPhone);
patientNationality = (TextInputLayout) findViewById(R.id.patientNationality);
patientAddress = (TextInputLayout) findViewById(R.id.patientAddress);
patientTreatmentNeeded = (TextInputLayout) findViewById(R.id.patientTreatmentNeeded);
patientDepartmentToVisit = (TextInputLayout) findViewById(R.id.patientDepartment);
patientPassword = (TextInputLayout) findViewById(R.id.patientPassword);
maleButton = (RadioButton) findViewById(R.id.maleRadioButton);
inpatientButton = (RadioButton) findViewById(R.id.inPaientRadioButton);
outPatient = (RadioButton) findViewById(R.id.Outpatient);
patientTypeGroup = (RadioGroup) findViewById(R.id.patientTypeRadioGroup);
femaleButton = (RadioButton) findViewById(R.id.femaleRadioButton);
genderGroup = (RadioGroup) findViewById(R.id.genderRadioGroup);
genderGroup.clearCheck();
patientTypeGroup.clearCheck();
addPatientToolbar = (Toolbar) findViewById(R.id.addPatientToolbar);
setSupportActionBar(addPatientToolbar);
getSupportActionBar().setTitle("Add Patient");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Registering Patient");
progressDialog.setMessage("Please wait while we register you...");
progressDialog.setCanceledOnTouchOutside(false);
registerPatient = (Button) findViewById(R.id.registerPatient);
reset = (Button) findViewById(R.id.resetPatient);
firebaseAuth = FirebaseAuth.getInstance();
patientRef = FirebaseDatabase.getInstance().getReference().child("patients");
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
patientAge.getEditText().setText("");
patientName.getEditText().setText("");
patientPassword.getEditText().setText("");
patientConfirmPassword.getEditText().setText("");
patientPhone.getEditText().setText("");
patientEmail.getEditText().setText("");
genderGroup.clearCheck();
}
});
patientTypeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton rb = (RadioButton) radioGroup.findViewById(i);
if (rb.getText().equals("Inpatient")) {
patientTreatmentNeeded.setVisibility(View.VISIBLE);
} else {
patientTreatmentNeeded.setVisibility(View.GONE);
}
}
});
registerPatient.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String pAge = patientAge.getEditText().getText().toString();
final String pName = patientName.getEditText().getText().toString();
final String pPhone = patientPhone.getEditText().getText().toString();
final String pPassword = patientPassword.getEditText().getText().toString();
String pConfirmPassword = patientConfirmPassword.getEditText().getText().toString();
final String pEmail = patientEmail.getEditText().getText().toString();
final String pAddress = patientAddress.getEditText().getText().toString();
final String pNationality = patientNationality.getEditText().getText().toString();
final String pDepartment = patientDepartmentToVisit.getEditText().getText().toString();
final String pTreatment = patientTreatmentNeeded.getEditText().getText().toString();
if (TextUtils.isEmpty(pAge) || TextUtils.isEmpty(pName) || TextUtils.isEmpty(pPhone) || TextUtils.isEmpty(pPassword) || TextUtils.isEmpty(pConfirmPassword) || TextUtils.isEmpty(pEmail) || TextUtils.isEmpty(pAddress) || TextUtils.isEmpty(pNationality) || TextUtils.isEmpty(pDepartment)) {
Toast.makeText(AddPatientActivity.this, "Please fill details", Toast.LENGTH_LONG).show();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(pEmail).matches()) {
Toast.makeText(AddPatientActivity.this, "Invalid Email", Toast.LENGTH_LONG).show();
return;
}
if (!pPassword.equals(pConfirmPassword)) {
Toast.makeText(AddPatientActivity.this, "Passwords do not match", Toast.LENGTH_LONG).show();
return;
}
if (pPhone.length() != 10) {
Toast.makeText(AddPatientActivity.this, "Invalid Phone Number", Toast.LENGTH_LONG).show();
return;
}
if (!maleButton.isChecked() && !femaleButton.isChecked()) {
Toast.makeText(AddPatientActivity.this, "Please select gender", Toast.LENGTH_LONG).show();
return;
}
if (!inpatientButton.isChecked() && !outPatient.isChecked()) {
Toast.makeText(AddPatientActivity.this, "Please select patient Type", Toast.LENGTH_LONG).show();
return;
}
RadioButton rb = (RadioButton) genderGroup.findViewById(genderGroup.getCheckedRadioButtonId());
final String g = rb.getText().toString();
RadioButton radioButton = (RadioButton) patientTypeGroup.findViewById(patientTypeGroup.getCheckedRadioButtonId());
final String type = radioButton.getText().toString();
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(pEmail, pPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
if (BedCount.blist.size() >= 600 && type.equals("Inpatient")) {
Toast.makeText(AddPatientActivity.this, "Bed Not Available", Toast.LENGTH_LONG).show();
return;
}
String bno = Integer.toString(++BedCount.bCount);
BedCount.blist.add(Integer.parseInt(bno));
String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference patientTypeRef;
if (type.equals("Outpatient")) {
patientTypeRef = patientRef.child("outpatients");
HashMap<String, String> patientMap = new HashMap();
patientMap.put("name", pName);
patientMap.put("age", pAge);
patientMap.put("gender", g);
patientMap.put("phone", pPhone);
patientMap.put("image", "default");
patientMap.put("address", pAddress);
patientMap.put("nationality", pNationality);
patientMap.put("department", pDepartment);
patientMap.put("id", uid);
patientTypeRef.child(uid).setValue(patientMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
Toast.makeText(AddPatientActivity.this, "Registration Successful", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(AddPatientActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressDialog.hide();
}
}
});
} else {
patientTypeRef = patientRef.child("inpatients");
HashMap<String, String> patientMap = new HashMap();
patientMap.put("name", pName);
patientMap.put("age", pAge);
patientMap.put("gender", g);
patientMap.put("phone", pPhone);
patientMap.put("image", "default");
patientMap.put("address", pAddress);
patientMap.put("nationality", pNationality);
patientMap.put("department", pDepartment);
patientMap.put("treatment", pTreatment);
patientMap.put("id", uid);
patientTypeRef.child(uid).setValue(patientMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
Toast.makeText(AddPatientActivity.this, "Registration Successful", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(AddPatientActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressDialog.hide();
}
}
});
}
} else {
Toast.makeText(AddPatientActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressDialog.hide();
}
}
});
}
});
}
}
|
package com.oracle.curd.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oracle.curd.bean.Ckin;
import com.oracle.curd.service.CkinService;
import org.springframework.beans.factory.annotation.Autowired;
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 java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
public class CkinController {
@Autowired
CkinService ckinService;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@RequestMapping(value = "/toGetAllCkin")
public String toPage(Model model){
PageHelper.startPage(1, 5);
List<Ckin> ckins = ckinService.getAll();
PageInfo<Ckin> page = new PageInfo<>(ckins, 5);
model.addAttribute("pageInfo", page);
return "getAllCkin";
}
//新增按钮跳转到新页面
@RequestMapping(value = "/toAddCkin")
public String toAddCkin(){
return "addCkin";
}
//查询
@RequestMapping(value = "/select")
public String selectByExmple(
@RequestParam(value = "pn", defaultValue = "1") Integer pn,
@RequestParam(value = "inid", required = false) String inid,
@RequestParam(value = "pname", required = false) String pname,
@RequestParam(value = "proid", required = false) String proid,
@RequestParam(value = "indate", required = false) String indate,
Model model
){
PageHelper.startPage(pn, 5);
List<Ckin> ckins = ckinService.getCkinsByExample(inid, pname, proid, indate);
PageInfo<Ckin> page = new PageInfo<>(ckins, 5);
model.addAttribute("pageInfo", page);
model.addAttribute("pname",pname);
model.addAttribute("inid",inid);
model.addAttribute("proid",proid);
model.addAttribute("indate",indate);
return "getAllCkin";
}
//新增
@RequestMapping(value = "/addCkin")
public String addCkin(
@RequestParam(value = "inid", required = false) String inid,
@RequestParam(value = "proid", required = false) String proid,
@RequestParam(value = "pname", required = false) String pname,
@RequestParam(value = "num", required = false) Integer num,
@RequestParam(value = "indate", required = false) String indate,
@RequestParam(value = "marks", required = false) String marks,
Model model
){
if ((inid==null||inid.equals("")) || (pname==null || pname.equals("")) || (proid==null || proid.equals("")) || (indate==null || indate.equals("")) || (num==null)){
model.addAttribute("errorInfoAdd", "带*项为必填项,不能为空!");
return "addCkin";
} else{
Ckin ckin = new Ckin();
ckin.setInid(inid);
ckin.setProid(proid);
ckin.setPname(pname);
ckin.setNum(num);
ckin.setMarks(marks);
try {
ckin.setIndate(sdf.parse(indate));
} catch (ParseException e) {
e.printStackTrace();
}
ckinService.addCkin(ckin);
return "getAllCkin";
}
}
//删除
@RequestMapping(value = "/delCkin")
public String removeCkin(@RequestParam(value = "inid") String inid, Model model){
ckinService.removeCkinByID(inid);
model.addAttribute("page", "ckin");
return "temp";
}
//修改按钮
@RequestMapping(value = "/toEditCkin")
public String toEditCkin(
@RequestParam(value = "inid") String inid,
@RequestParam(value = "proid") String proid,
@RequestParam(value = "pname") String pname,
@RequestParam(value = "num") Integer num,
@RequestParam(value = "indate") Date indate,
@RequestParam(value = "marks", required = false) String marks,
Model model
){
Ckin ckin = new Ckin();
ckin.setInid(inid);
ckin.setProid(proid);
ckin.setPname(pname);
ckin.setNum(num);
ckin.setIndate(indate);
ckin.setMarks(marks);
model.addAttribute("ckin", ckin);
return "editCkin";
}
//修改操作
@RequestMapping(value = "editCkin")
public String UpdateCkinById(
@RequestParam(value = "inid") String inid,
@RequestParam(value = "proid") String proid,
@RequestParam(value = "pname") String pname,
@RequestParam(value = "num") Integer num,
@RequestParam(value = "indate") String indate,
@RequestParam(value = "marks", required = false) String marks,
Model model
){
if ((pname==null || pname.equals("")) || (proid==null || proid.equals("")) || (indate==null || indate.equals("")) || (num==null || num==0)){
model.addAttribute("errorInfoEdit", "带*项为必填项,不能为空或者为0 !");
return "editCkin";
} else {
Ckin ckin = new Ckin();
ckin.setInid(inid);
ckin.setProid(proid);
ckin.setPname(pname);
ckin.setNum(num);
try {
ckin.setIndate(sdf.parse(indate));
} catch (ParseException e) {
e.printStackTrace();
}
ckin.setMarks(marks);
ckinService.updateCkinByID(ckin);
return "getAllCkin";
}
}
}
|
package gui;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DealerHandPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final int RAISE_HEIGHT = 80;
JLabel CardDisplay1;
JLabel CardDisplay2;
JLabel CardDisplay3;
JLabel CardDisplay4;
JLabel CardDisplay5;
JLabel test;
private GUIController guiController;
/**
* constructs dealer hand panel of 5 cards with their backs' visible
*/
public DealerHandPanel() {
FlowLayout playingCardLayout = new FlowLayout(FlowLayout.CENTER,20,0);
setLayout(playingCardLayout);
CardDisplay1 = new JLabel();
CardDisplay2 = new JLabel();
CardDisplay3 = new JLabel();
CardDisplay4 = new JLabel();
CardDisplay5 = new JLabel();
test = new JLabel();
resetDealerHandDisplay();
add(CardDisplay1);
add(CardDisplay2);
add(CardDisplay3);
add(CardDisplay4);
add(CardDisplay5);
}
public void setDealerCardsToOriginalPosition(){
CardDisplay1.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
CardDisplay2.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
CardDisplay3.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
CardDisplay4.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
CardDisplay5.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
repaint();
}
public void resetDealerHandDisplay(){
ImageIcon cardBack = new ImageIcon("res/graphics/classic-cards/b2fv.png");
CardDisplay1.setIcon(cardBack);
CardDisplay2.setIcon(cardBack);
CardDisplay3.setIcon(cardBack);
CardDisplay4.setIcon(cardBack);
CardDisplay5.setIcon(cardBack);
setDealerCardsToOriginalPosition();
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
/**
* setter method - enables panel to see the GUI controller
* @param the guiController reference
*/
public void setControl(GUIController guiController) {
this.guiController = guiController;
}
/**
* setter method - sets the card display
* @param the image of the card to display
* @param the card display to change (1 - 5)
*/
public void setCardDisplay(String iconName, int cardDisplay) {
switch (cardDisplay){
case 1: CardDisplay1.setIcon(new ImageIcon(iconName));
case 2: CardDisplay2.setIcon(new ImageIcon(iconName));
case 3: CardDisplay3.setIcon(new ImageIcon(iconName));
case 4: CardDisplay4.setIcon(new ImageIcon(iconName));
case 5: CardDisplay5.setIcon(new ImageIcon(iconName));
}
}
}
|
package com.megathrone.tmall.controller;
import com.comparator.*;
import com.github.pagehelper.PageHelper;
import com.megathrone.tmall.pojo.*;
import com.megathrone.tmall.service.*;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("")
public class ForeController {
@Autowired
CategoryService categoryService;
@Autowired
ProductService productService;
@Autowired
UserService userService;
@Autowired
ProductImageService productImageService;
@Autowired
PropertyValueService propertyValueService;
@Autowired
OrderService orderService;
@Autowired
OrderItemService orderItemService;
@Autowired
ReviewService reviewService;
@RequestMapping("forehome")
public String home(Model model) {
List<Category> cs = categoryService.list();
productService.fill(cs);
productService.fillByRow(cs);
model.addAttribute("cs", cs);
return "fore/home";
}
@RequestMapping("foreregister")
public String register(Model model, User user) {
String name = user.getName();
name = HtmlUtils.htmlEscape(name);
user.setName(name);
boolean exist = userService.isExist(name);
if (exist) {
String m = "用户名已经被使用,不能使用";
model.addAttribute("msg", m);
return "fore/register";
}
userService.add(user);
return "redirect:registerSuccessPage";
}
@RequestMapping("forelogin")
public String login(@RequestParam("name") String name, @RequestParam("password") String password, Model model, HttpSession session) {
name = HtmlUtils.htmlEscape(name);
User user = userService.get(name, password);
if (null == user) {
model.addAttribute("msg", "账号密码错误");
return "fore/login";
}
session.setAttribute("user", user);
return "redirect:forehome";
}
@RequestMapping("forelogout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "redirect:forehome";
}
@RequestMapping("foreproduct")
public String product(int pid, Model model) {
Product p = productService.get(pid);
List<ProductImage> productSingleImages = productImageService.list(p.getId(), ProductImageService.type_single);
List<ProductImage> productDetailImages = productImageService.list(p.getId(), ProductImageService.type_detail);
p.setProductSingleImages(productSingleImages);
p.setProductDetailImages(productDetailImages);
List<PropertyValue> pvs = propertyValueService.list(p.getId());
List<Review> reviews = reviewService.list(p.getId());
productService.setSaleAndReviewNumber(p);
model.addAttribute("reviews", reviews);
model.addAttribute("p", p);
model.addAttribute("pvs", pvs);
return "fore/product";
}
@RequestMapping("forecheckLogin")
@ResponseBody
public String checkLogin(HttpSession session) {
User user = (User) session.getAttribute("user");
if (null != user)
return "success";
return "fail";
}
@RequestMapping("foreloginAjax")
@ResponseBody
public String loginAjax(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session) {
name = HtmlUtils.htmlEscape(name);
User user = userService.get(name, password);
if (null == user) {
return "fail";
}
session.setAttribute("user", user);
return "success";
}
@RequestMapping("forecategory")
public String category(int cid, String sort, Model model) {
Category c = categoryService.get(cid);
productService.fill(c);
productService.setSaleAndReviewNumber(c.getProducts());
if (null != sort) {
switch (sort) {
case "review":
Collections.sort(c.getProducts(), new ProductReviewComparator());
break;
case "date":
Collections.sort(c.getProducts(), new ProductDateComparator());
break;
case "saleCount":
Collections.sort(c.getProducts(), new ProductSaleCountComparator());
break;
case "price":
Collections.sort(c.getProducts(), new ProductPriceComparator());
break;
case "all":
Collections.sort(c.getProducts(), new ProductAllComparator());
break;
}
}
model.addAttribute("c", c);
return "fore/category";
}
@RequestMapping("foresearch")
public String search(String keyword, Model model) {
PageHelper.offsetPage(0, 20);
List<Product> ps = productService.search(keyword);
productService.setSaleAndReviewNumber(ps);
model.addAttribute("ps", ps);
return "fore/searchResult";
}
@RequestMapping("forebuyone")
public String buyone(int pid, int num, HttpSession session) {
Product p = productService.get(pid);
int oiid = 0;
User user = (User) session.getAttribute("user");
boolean found = false;
List<OrderItem> ois = orderItemService.listByUser(user.getId());
for (OrderItem oi : ois) {
if (oi.getProduct().getId().intValue() == p.getId().intValue()) {
oi.setNumber(oi.getNumber() + num);
orderItemService.update(oi);
found = true;
oiid = oi.getId();
break;
}
}
if (!found) {
OrderItem oi = new OrderItem();
oi.setUid(user.getId());
oi.setNumber(num);
oi.setPid(pid);
orderItemService.add(oi);
oiid = oi.getId();
}
return "redirect:forebuy?oiid=" + oiid;
}
@RequestMapping("forebuy")
public String buy(Model model, String[] oiid, HttpSession session) {
List<OrderItem> ois = new ArrayList<>();
float total = 0;
for (String strid : oiid) {
int id = Integer.parseInt(strid);
OrderItem oi = orderItemService.get(id);
total += oi.getProduct().getPromotePrice() * oi.getNumber();
ois.add(oi);
}
session.setAttribute("ois", ois);
model.addAttribute("total", total);
return "fore/buy";
}
@RequestMapping("foreaddCart")
public String addCart(int pid, int num, Model model, HttpSession session) {
// Get a product from according to pid
Product p = productService.get(pid);
User user = (User) session.getAttribute("user");
boolean found = false;
List<OrderItem> ois = orderItemService.listByUser(user.getId());
for (OrderItem oi : ois) {
if (oi.getProduct().getId().intValue() == p.getId().intValue()) {
oi.setNumber(oi.getNumber() + num);
orderItemService.update(oi);
found = false;
break;
}
}
if (!found) {
OrderItem oi = new OrderItem();
oi.setUid(user.getId());
oi.setPid(pid);
oi.setNumber(num);
orderItemService.add(oi);
}
return "success";
}
//show all products in cart
@RequestMapping("forecart")
public String cart(Model model, HttpSession session) {
User user = (User) session.getAttribute("user");
List<OrderItem> ois = orderItemService.listByUser(user.getId());
model.addAttribute("ois", ois);
return "fore/cart";
}
/**
* @param model
* @param session
* @param pid
* @param number
* @return : json
* <p>
* Cart page manipulating : change
*/
@RequestMapping("forechangeOrderItem")
@ResponseBody
public String changeOrderItem(Model model, HttpSession session, int pid, int number) {
User user = (User) session.getAttribute("user");
if (null == user)
return "fail";
List<OrderItem> ois = orderItemService.listByUser(user.getId());
for (OrderItem oi : ois) {
if (oi.getProduct().getId().intValue() == pid) {
oi.setNumber(number);
orderItemService.update(oi);
break;
}
}
return "success";
}
/**
* @param model
* @param session
* @param oiid
* @return json
* <p>
* Cart page manipulating : delete
*/
@RequestMapping("foredeleteOrderItem")
@ResponseBody
public String deleteOrderItem(Model model, HttpSession session, int oiid) {
User user = (User) session.getAttribute("user");
if (null == user)
return "fail";
orderItemService.delete(oiid);
return "success";
}
// create an order
@RequestMapping("forecreateOrder")
public String createOrder(Model model, Order order, HttpSession session) {
User user = (User) session.getAttribute("user");
String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) +
RandomUtils.nextInt(10000);
order.setOrderCode(orderCode);
order.setCreateDate(new Date());
order.setUid(user.getId());
order.setStatus(OrderService.waitPay);
List<OrderItem> ois = (List<OrderItem>) session.getAttribute("ois");
float total = orderService.add(order, ois);
return "redirect:forealipay?oid=" + order.getId() + "&total=" + total;
}
@RequestMapping("forepayed")
public String payed(int oid, float total, Model model) {
Order order = orderService.get(oid);
order.setStatus(OrderService.waitDelivery);
order.setPayDate(new Date());
orderService.update(order);
model.addAttribute("o", order);
return "fore/payed";
}
@RequestMapping("forebought")
public String bought(Model model, HttpSession session) {
User user = (User) session.getAttribute("user");
List<Order> os = orderService.list(user.getId(), OrderService.delete);
orderItemService.fill(os);
model.addAttribute("os", os);
return "fore/bought";
}
@RequestMapping("foreconfirmPay")
public String confirmPay(int oid, Model model) {
Order o = orderService.get(oid);
orderItemService.fill(o);
model.addAttribute("o", o);
return "fore/confirmPay";
}
@RequestMapping("foreorderConfirmed")
public String orderConfirmed(Model model, int oid) {
Order o = orderService.get(oid);
o.setStatus(OrderService.waitReview);
o.setConfirmDate(new Date());
orderService.update(o);
return "fore/orderConfirmed";
}
@RequestMapping("foredeleteOrder")
@ResponseBody
public String deleteOrder(Model model, int oid) {
Order o = orderService.get(oid);
o.setStatus(OrderService.delete);
orderService.update(o);
return "success";
}
@RequestMapping("forereview")
public String review(Model model, int oid) {
Order o = orderService.get(oid);
orderItemService.fill(o);
Product p = o.getOrderItems().get(0).getProduct();
List<Review> reviews = reviewService.list(p.getId());
productService.setSaleAndReviewNumber(p);
model.addAttribute("p", p);
model.addAttribute("o", o);
model.addAttribute("reviews", reviews);
return "fore/review";
}
@RequestMapping("foredoreview")
public String doreview( Model model,HttpSession session,
@RequestParam("oid") int oid,
@RequestParam("pid") int pid,
String content) {
Order o = orderService.get(oid);
o.setStatus(OrderService.finish);
orderService.update(o);
Product p = productService.get(pid);
content = HtmlUtils.htmlEscape(content);
User user =(User) session.getAttribute("user");
Review review = new Review();
review.setContent(content);
review.setPid(pid);
review.setCreateDate(new Date());
review.setUid(user.getId());
reviewService.add(review);
return "redirect:forereview?oid="+oid+"&showonly=true";
}
}
|
package business.abstracts;
import java.util.List;
import entities.concretes.Category;
public interface CategoryService {
List<Category> getAll();
void add(Category category);
void update(Category category);
void delete(Category category);
}
|
/* ------------------------------------------------------------------------------
* 软件名称:IM
* 公司名称:乐多科技
* 开发作者:Yongchao.Yang
* 开发时间:2014年11月10日/2014
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.rednovo.ace.communication
* fileName:FileHelper.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.communication;
import java.io.File;
import com.rednovo.ace.constant.Constant.ChatMode;
import com.rednovo.ace.constant.Constant.MsgType;
import com.rednovo.ace.entity.Summary;
import com.rednovo.tools.PPConfiguration;
/**
* 文件助手
*
* @author yongchao.Yang/2014年11月10日
*/
public class FileHelper {
/**
* 获取客户端文件存放路径
*
* @return
* @author Yongchao.Yang
* @since 2015年3月25日上午11:19:12
*/
public static String getMsgFileSavePath() {
return PPConfiguration.getProperties("cfg.properties").getString("msg.file.save.path");
}
/**
*
* @return
* @author Yongchao.Yang
* @since 2015年4月13日下午2:39:29
*/
public static String getProfileSavePath() {
return PPConfiguration.getProperties("cfg.properties").getString("img.file.save.path");
}
/**
* 创建用户、群目录
*
* @param userId
* @author Yongchao.Yang
* @since 2015年4月13日下午6:39:14
*/
public static void createUserDir(int uidLen, int depth, String parentPath) {
if (uidLen - depth < 3) {
return;
}
int i = 0;
if (depth == 1) {
i = 1;
}
for (; i <= 9; i++) {
String path = parentPath + File.separator + i;
File newDir = new File(path);
if (!newDir.exists()) {
newDir.mkdirs();
}
createUserDir(6, depth + 1, path);
}
}
/**
* 获取消息文件存放路径
*
* @param ppId
* @return
* @author YongChao.Yang/2012-11-1/2012
*/
public static String getDir(Summary smy) {
StringBuffer basePath = new StringBuffer();
String id = "";
if ((MsgType.MEDIA_MSG_AUDIO.getValue().equals(smy.getMsgType()) || MsgType.MEDIA_MSG_PIC.getValue().equals(smy.getMsgType())) && ChatMode.PRIVATE.getValue().equals(smy.getChatMode())) {// 私聊,媒体消息
basePath.append(PPConfiguration.getProperties("cfg.properties").getString("msg.file.save.path") + File.separator + "user");
id = smy.getSenderId();
} else if ((MsgType.MEDIA_MSG_AUDIO.getValue().equals(smy.getMsgType()) || MsgType.MEDIA_MSG_PIC.getValue().equals(smy.getMsgType())) && ChatMode.GROUP.getValue().equals(smy.getChatMode())) {// 群聊,媒体消息
basePath.append(PPConfiguration.getProperties("cfg.properties").getString("msg.file.save.path") + File.separator + "group");
id = smy.getShowId();
} else if (MsgType.BACKGROUND_PHOTO_PRIVATE.getValue().equals(smy.getMsgType()) || MsgType.PHOTO_PRIVATE.getValue().equals(smy.getMsgType())) {// 上传 用户图像
basePath.append(PPConfiguration.getProperties("cfg.properties").getString("photo.file.save.path") + File.separator + "user");
id = smy.getSenderId();
} else if (MsgType.BACKGROUND_PHOTO_GROUP.getValue().equals(smy.getMsgType()) || MsgType.PHOTO_GROUP.getValue().equals(smy.getMsgType())) {// 上传 群组图像
basePath.append(PPConfiguration.getProperties("cfg.properties").getString("photo.file.save.path") + File.separator + "group");
id = smy.getShowId();
}
int len = id.length() - 3;
for (int i = 0; i < len; i++) {
basePath.append(File.separator + id.charAt(i));
}
basePath.append(File.separator + id);
return basePath.toString();
}
public static void main(String[] args) {
FileHelper.createUserDir(6, 1, PPConfiguration.getProperties("cfg.properties").getString("msg.file.save.path") + File.separator + "user");
FileHelper.createUserDir(6, 1, PPConfiguration.getProperties("cfg.properties").getString("msg.file.save.path") + File.separator + "group");
FileHelper.createUserDir(6, 1, PPConfiguration.getProperties("cfg.properties").getString("photo.file.save.path") + File.separator + "user");
FileHelper.createUserDir(6, 1, PPConfiguration.getProperties("cfg.properties").getString("photo.file.save.path") + File.separator + "group");
}
}
|
package com.pelephone_mobile.mypelephone.network.rest;
import java.io.IOException;
import java.util.Set;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import android.os.AsyncTask;
import android.util.Log;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pelephone_mobile.mypelephone.network.interfaces.IMPRestGetResponseListener;
import com.pelephone_mobile.mypelephone.network.rest.pojos.Pojo;
import com.pelephone_mobile.songwaiting.global.SWGlobal;
/**
* Created by Gali.Issachar on 24/12/13.
*/
public class RestRequests {
private static final String LONG_TOKEN_KEY = "LongToken";
public void getAndParse(IMPRestGetResponseListener listener, String url,
Class<? extends Pojo> classToParseJsonResponse, String longToken) {
new GetPasrseAsyncTask(listener, url, classToParseJsonResponse, longToken).execute();
// Thread thread = new Thread(new Runnable() {
// @Override
// public void run() {
//
// RestTemplate restTemplate = new RestTemplate();
// // Create the request body as a MultiValueMap
// MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
//
// try {
//
// // restTemplate.getMessageConverters().add(new
// // MappingJackson2HttpMessageConverter());
//
// if (!longToken.equals("")) {
//
// body.add(LONG_TOKEN_KEY, longToken);
// }
//
// // @@ofirbt - TODO - Don't get string and convert to POJO!
// // Instead, use something like: restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// // See: http://spring.io/guides/gs/consuming-rest-android/ for more details
//
//
// // Note the body object as first parameter!
// HttpEntity<?> httpEntity = new HttpEntity<Object>(body);
//
// ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity,
// String.class);
//
// if(responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) {
//
// throw new IOException();
// }
//
// String jsonStr = responseEntity.getBody();
//
//
// ObjectMapper mapper = new ObjectMapper();
// Pojo mPojo = mapper.readValue(jsonStr, classToParseJsonResponse);
//
// if (listener != null) {
//
// listener.onResponse(mPojo);
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// if (listener != null) {
// listener.onError(IMPRestGetResponseListener.ErrorsTypes.CONNECTION_ERROR);
// }
//
// } catch (RuntimeException e) {
//
// e.printStackTrace();
// if (listener != null) {
// listener.onError(IMPRestGetResponseListener.ErrorsTypes.RUNTIME_ERROR);/*
// * Todo
// * change
// * error
// * type
// */
// }
// }
//
// }
// });
// thread.setName("pelephone thread");
// thread.start();
}
class GetPasrseAsyncTask extends AsyncTask<Void, Void, Pojo>
{
private static final String TAG = "GetPasrseAsyncTask";
private IMPRestGetResponseListener mListener;
private Class<? extends Pojo> mClassToParseJsonResponse;
private String mUrl;
private String mLongToken;
public GetPasrseAsyncTask(IMPRestGetResponseListener listener, final String url,
Class<? extends Pojo> classToParseJsonResponse, String longToken)
{
mListener = listener;
mClassToParseJsonResponse = classToParseJsonResponse;
mUrl = url;
mLongToken = longToken;
}
@Override
protected Pojo doInBackground(Void... params) {
RestTemplate restTemplate = new RestTemplate();
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
try {
// restTemplate.getMessageConverters().add(new
// MappingJackson2HttpMessageConverter());
if (!mLongToken.equals("")) {
body.add(LONG_TOKEN_KEY, mLongToken);
}
// @@ofirbt - TODO - Don't get string and convert to POJO!
// Instead, use something like: restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
// See: http://spring.io/guides/gs/consuming-rest-android/ for more details
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body);
if(MPRequestUrlBuilder.IS_TO_INSERT_HOST_HEADER)
{
// Host Header Insertion
HttpHeaders headers = new HttpHeaders();
headers.add(MPRequestUrlBuilder.HOST_HEADER_KEY, MPRequestUrlBuilder.HOST_HEADER_VAL);
httpEntity = new HttpEntity<Object>(body, headers);
}
Log.i(TAG, "REQUEST:\n".concat(mUrl)+"\nHEADERS:\n"+headersToString(httpEntity));
//==============================================================================================================================================
// Changed by Michael to catch breakpoint
// ResponseEntity<String> responseEntity = restTemplate.exchange(mUrl, HttpMethod.GET, httpEntity, String.class);
ResponseEntity<String> responseEntity = null;
try {
responseEntity = restTemplate.exchange(mUrl, HttpMethod.GET, httpEntity, String.class);
} catch (Exception ex) {
throw ex;
}
//==============================================================================================================================================
if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) {
throw new IOException();
}
String jsonStr = responseEntity.getBody();
if (jsonStr != null) {
Log.i(TAG, "RESPONSE:\n".concat(jsonStr));
} else {
Log.e(TAG, "RESPONSE = NULL :-(");
}
ObjectMapper mapper = new ObjectMapper();
Pojo mPojo = mapper.readValue(jsonStr, mClassToParseJsonResponse);
return mPojo;
}
catch (IOException e)
{
e.printStackTrace();
IMPRestGetResponseListener.ErrorsTypes errorType = IMPRestGetResponseListener.ErrorsTypes.CONNECTION_ERROR;
if( mUrl.contains("PersonalBanners") )
errorType = IMPRestGetResponseListener.ErrorsTypes.PERSONAL_BANNER_ERROR;
if (mListener != null) {
mListener.onError(errorType);
return null;
}
}
catch (RuntimeException e)
{
e.printStackTrace();
IMPRestGetResponseListener.ErrorsTypes errorType = IMPRestGetResponseListener.ErrorsTypes.CONNECTION_ERROR;
if( mUrl.contains("PersonalBanner") )
errorType = IMPRestGetResponseListener.ErrorsTypes.PERSONAL_BANNER_ERROR;
if (mListener != null) {
mListener.onError(errorType);/*
* Todo
* change
* error
* type
*/
return null;
}
}
return null;
}
@Override
protected void onPostExecute(Pojo pojo)
{
if (mListener != null && pojo != null)
{
mListener.onResponse(pojo);
}
}
}
private String headersToString(HttpEntity<?> he)
{
String retVal = "";
HttpHeaders headers = he.getHeaders();
Set<String> keys = headers.keySet();
for (String key: keys)
{
retVal += key + " : "+headers.get(key)+"\n";
}
return retVal;
}
}
|
public class MaximumSubarray {
public int maxSubArray(int[] nums) {
int n = nums.length;
int [] dp = new int[n];
dp[0] = nums[0];
int max = 0;
for(int i=1;i<n;i++){
dp[i] = dp[i-1] + (dp[i-1]>0?dp[i-1]:0) ;
max = Math.max(dp[i], max);
}
return max;
}
}
|
package FactoryPattern;
public class Onion extends Veggies {
public Onion() {
super("Onion");
// TODO Auto-generated constructor stub
}
}
|
package com.revolut.moneytransfer.test.service;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.Date;
import org.apache.http.client.ClientProtocolException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.revolut.moneytransfer.entity.Account;
import com.revolut.moneytransfer.entity.Transaction;
import com.revolut.moneytransfer.factory.ServiceFactory;
import com.revolut.moneytransfer.util.Util;
public class MoneyTransferServiceTest {
private static Logger logger = LoggerFactory.getLogger(MoneyTransferServiceTest.class);
@Test
public void testSendMoneyOkey() throws URISyntaxException, ClientProtocolException, IOException {
Account account = ServiceFactory.getAccountService().getAccountsByAccountNumber(252502143);
Transaction transaction = new Transaction(252502143, 432345675, new Date(), null, new BigDecimal(2), "TRY",
"TRY", "W", 0, Util.createTokenWhenTransactionStart());
ServiceFactory.getTransactionService().insertTransaction(transaction);
ServiceFactory.getSendMoneyService().sendMoney(transaction);
Account accountAfterMoneySent = ServiceFactory.getAccountService().getAccountsByAccountNumber(252502143);
BigDecimal accountBalance = account.getBalance().subtract(new BigDecimal(2));
assertTrue(accountBalance.compareTo(accountAfterMoneySent.getBalance()) == 0);
}
@Test
public void testAcceptMoney() throws URISyntaxException, ClientProtocolException, IOException {
Account account = ServiceFactory.getAccountService().getAccountsByAccountNumber(432345675);
Transaction transaction = new Transaction(252502143, 432345675, new Date(), null, new BigDecimal(2), "TRY",
"TRY", "W", 0, Util.createTokenWhenTransactionStart());
ServiceFactory.getTransactionService().insertTransaction(transaction);
ServiceFactory.getSendMoneyService().acceptMoney(transaction);
Account accountAfterMoneySent = ServiceFactory.getAccountService().getAccountsByAccountNumber(432345675);
BigDecimal accountBalance = account.getBalance().add(new BigDecimal(2));
assertTrue(accountBalance.compareTo(accountAfterMoneySent.getBalance()) == 0);
}
}
|
package com.examples.mockito;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.Spy;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* Spy or the spy() method can be used to wrap a real object. Every call, unless specified otherwise, is delegated
* to the object.
*/
public class MockitoSpyTest {
@Ignore
public void testLinkedListSpyWrong() {
// Lets mock a LinkedList
List<String> list = new LinkedList<>();
List<String> spy = spy(list);
// this does not work
// real method is called so spy.get(0)
// throws IndexOutOfBoundsException (list is still empty)
when(spy.get(0)).thenReturn("foo");
assertEquals("foo", spy.get(0));
}
@Test
public void testLinkedListSpyCorrect() {
// Lets mock a LinkedList
List<String> list = new LinkedList<>();
List<String> spy = spy(list);
// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
assertEquals("foo", spy.get(0));
}
// The @Spy Annotation
@Spy
List<String> spyList = new ArrayList<String>();
@Ignore // doesn't like mix and matching
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
spyList.add("one");
spyList.add("two");
Mockito.verify(spyList).add("one");
Mockito.verify(spyList).add("two");
assertEquals(2, spyList.size());
}
}
|
package com.example.prog3.alkasaffollowup.ViewHolders;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.example.prog3.alkasaffollowup.R;
/**
* Created by prog3 on 3/26/2018.
*/
public class InvoicesViewHolder extends RecyclerView.ViewHolder {
public TextView txtprojref,txtinvoice,txtinvoiceamount,txtinvoicedate;
public CardView cview;
public InvoicesViewHolder(View v) {
super(v);
txtprojref=v.findViewById(R.id.txtprojref);
txtinvoice=v.findViewById(R.id.txtinvoice);
txtinvoiceamount=v.findViewById(R.id.txtinvoiceamount);
txtinvoicedate=v.findViewById(R.id.txtinvoicedate);
cview=v.findViewById(R.id.cview);
}
}
|
/*
* 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 server.rooms;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author luisburgos
*/
public class SeatsRoom {
public SeatsRoom(int port) throws IOException {
ServerSocket server = new ServerSocket(port);
while (true) {
Socket client = server.accept();
System.out.println("Aceptado de" + client.getInetAddress());
SeatsRoomHandler chatHandler = new SeatsRoomHandler(client);
chatHandler.start();
}
}
public static void main(String[] args) {
if(args.length != 1){
throw new RuntimeException("Sintaxis: ChatServer <port>");
}
try {
new SeatsRoom(Integer.parseInt(args[0]));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
package tradingmaster.model;
public interface IPortfolio {
// void init(Map params);
//
// void onFirstCandle(Candle c);
//
// void onLastCandle(Candle c);
//
// void buy(BigDecimal price, BigDecimal amount, Candle c);
//
// void sell(BigDecimal price, BigDecimal amount, Candle c);
}
|
package com.zc.pivas.docteradvice.dtsystem.autocheck.req;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
/**
*
* 医嘱自动检查结果类
*
* @author cacabin
* @version 0.1
*/
@XmlAccessorType(XmlAccessType.FIELD)
public class Allergic
{
private String type;
private String name;
private String code;
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
}
|
package org.example.codingtest.oneLevel;
/**
* 행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다.
* 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요.
**/
public class AddOfMatrix {
public static void main(String[] args) {
int[][] arr1 = {{1,2},
{2,3}};
int[][] arr2 = {{3,4},
{5,6}};
int[][] arr3 = {{1,2}};
int[][] arr4 = {{3,4}};
solution(arr1, arr2);
// solution(arr3, arr4);
}
public static int[][] solution(int[][] arr1, int[][] arr2) {
int x = arr1.length;
int y =arr1[0].length;
int[][] answer = new int[x][y];
for (int a=0;a<x;a++){
for (int b=0;b<y;b++){
answer[a][b] = arr1[a][b] + arr2[a][b];
System.out.println("answer["+a+"]["+b+"]="+ answer[a][b]);
}
}
return answer;
}
}
|
/*package com.bnrc.util.collectwifi;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class Thread_send_json1 extends Thread {
private static final String TAG = "Thread_send_json";
private List<Map<String, String>> mInfo;
private Handler mHandler;
private String mUrl = "http://10.108.104.217:8080/NewOne/JsonServlet";
private CollectWifiDBHelper mCollectWifiDBHelper;
public Thread_send_json(Context pContext, Handler pHandler) {
this.mHandler = pHandler;
mCollectWifiDBHelper = CollectWifiDBHelper.getInstance(pContext);
Log.i(TAG, "url is " + mUrl);
}
@Override
public void run() {
// TODO Auto-generated method stub
mInfo = mCollectWifiDBHelper.FindScanData();
if (mInfo.size() > 0) {
try {
// 请求数据
HttpClient hClient = new DefaultHttpClient();
HttpPost request = new HttpPost(mUrl);
JSONArray jArray = new JSONArray();
for (Map<String, String> map : mInfo) {
// 请求json报文
// 先封装一个 JSON 对象
JSONObject param = new JSONObject();
try {
param.put("Time", map.get("时间"));
param.put("Lat", map.get("纬度"));
param.put("Lon", map.get("经度"));
param.put("SSID", map.get("SSID"));
param.put("MAC", map.get("MAC"));
param.put("Level", map.get("Level"));
param.put("LocType", map.get("LocType"));
param.put("LocRadius", map.get("LocRadius"));
param.put("LocSpeed", map.get("LocSpeed"));
jArray.put(param);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 绑定到请求 Entry
StringEntity se = new StringEntity(jArray.toString(), "UTF-8");
request.setEntity(se);
// 发送请求
HttpResponse response = hClient.execute(request);
Log.i(TAG, "response.getStatusCode: "
+ response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
String responseMsg = EntityUtils.toString(response
.getEntity());
Log.i(TAG, "responseMsg is " + responseMsg);
Message msg = new Message();
Bundle bundle = new Bundle();// 存放数据
bundle.putString("responseMsg", responseMsg);
msg.setData(bundle);
msg.what = 0x11;
mHandler.sendMessage(msg); // 向Handler发送消息,更新UI
}
if (hClient != null) {
hClient.getConnectionManager().shutdown();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
*/
|
package cn.itcast.spring.IntegrateWeb;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class ServletUserService extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
UserService userService = (UserService)applicationContext.getBean("userService");
userService.sayHello();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
package pages;
import org.openqa.selenium.WebDriver;
public class UserHomePage extends BasePage {
public UserHomePage(WebDriver driver) {
super(driver);
}
public UserHomePage verifySignIn(){
//System.out.println(driver.getTitle());
verifyTitle("Amazon.com.au: Shop online for Electronics, Apparel, Toys, Books, DVDs & more");
return this;
}
}
|
module hellofx {
requires com.youthlin.i18n;
requires com.almasb.fxgl.all;
requires logback.classic;
requires logback.core;
requires slf4j.api;
opens com.youthlin.example.javafx to javafx.fxml;
exports com.youthlin.example.javafx;
}
|
package com.worldchip.bbpawphonechat.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.worldchip.bbpawphonechat.R;
public class MySlipButton extends View implements OnTouchListener{
private Bitmap bg_on;
private Bitmap bg_off;
private Bitmap slip_btn_on;
private Bitmap slip_btn_off;
private boolean mIsOn;
private OnChangedListener ChgLsn;
private boolean isChgLsnOn = false;
public MySlipButton(Context context) {
super(context);
initView();
}
public MySlipButton(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView(){
bg_on = BitmapFactory.decodeResource(getResources(),R.drawable.togglebutton_bg_on);
bg_off = BitmapFactory.decodeResource(getResources(),R.drawable.togglebutton_bg);
slip_btn_on = BitmapFactory.decodeResource(getResources(),R.drawable.togglebutton_src);
slip_btn_off = BitmapFactory.decodeResource(getResources(),R.drawable.togglebutton_close_src);
setOnTouchListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Matrix matrix = new Matrix();
Paint paint = new Paint();
if(mIsOn){
canvas.drawBitmap(bg_on, matrix, paint);
float x = bg_on.getWidth()-slip_btn_on.getWidth();
canvas.drawBitmap(slip_btn_on, x, 0, paint);
}else{
canvas.drawBitmap(bg_off, matrix, paint);
canvas.drawBitmap(slip_btn_off, 0, 0, paint);
}
System.out.println("---MySlipButton---onDraw---"+mIsOn);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(mIsOn){
setmIsOn(false);
}else{
setmIsOn(true);
}
System.out.println("---event.getx--==--"+event.getX()+"---event.getY--==--"+event.getY());
break;
case MotionEvent.ACTION_MOVE:
break;
default:
break;
}
ChgLsn.OnChanged(mIsOn);
invalidate();
return false;
}
public boolean ismIsOn() {
return mIsOn;
}
public void setmIsOn(boolean mIsOn) {
this.mIsOn = mIsOn;
}
public void setOnChangedListener(OnChangedListener l) {
isChgLsnOn = true;
ChgLsn = l;
}
public interface OnChangedListener {
abstract void OnChanged(boolean CheckState);
}
}
|
package com.jtexplorer.entity.dto;
import com.jtexplorer.entity.enums.RequestEnum;
import lombok.Data;
import lombok.ToString;
import java.math.BigDecimal;
import java.util.List;
/**
* JsonResult class
*
* @author 苏友朋
* @date 2019/03/01 09:03
*/
@Data
@ToString
public class JsonResult {
private boolean success;
private long totalSize;
private String tip;
private String failReason;
private List root;
private BigDecimal amount;
public void buildNew(boolean success, long totalSize, String tip, String failReason, List root) {
this.tip = tip;
this.failReason = failReason;
this.root = root;
this.success = success;
this.totalSize = totalSize;
}
public void buildFalseNew(String tip, String failReason) {
this.tip = tip;
this.failReason = failReason;
this.success = false;
}
public void buildTrueNew(long totalSize, List root) {
this.root = root;
this.success = true;
this.totalSize = totalSize;
}
public void buildTrueNew() {
this.success = true;
}
public void buildFalseNew(RequestEnum requestEnum) {
this.tip = requestEnum.getCode();
this.failReason = requestEnum.getMeaning();
this.success = false;
}
public void buildFalseNew(RequestEnum requestEnum, String reason) {
this.tip = requestEnum.getCode();
this.failReason = requestEnum.getMeaning() + reason;
this.success = false;
}
}
|
package com.lambda.iith.dashboard.MainFragments;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lambda.iith.dashboard.AutostartManager;
import com.lambda.iith.dashboard.BackgroundTasks.GetNextBus;
import com.lambda.iith.dashboard.Cabsharing.CabSharing;
import com.lambda.iith.dashboard.Init;
import com.lambda.iith.dashboard.Launch;
import com.lambda.iith.dashboard.MainActivity;
import com.lambda.iith.dashboard.R;
import com.lambda.iith.dashboard.Timetable.Timetable;
import org.honorato.multistatetogglebutton.MultiStateToggleButton;
import org.honorato.multistatetogglebutton.ToggleButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import Adapters.HomeTimeTableAdapter;
import Adapters.RecyclerViewAdapter_CSHOME;
import Model.Lecture;
public class HomeScreenFragment extends Fragment {
public static SharedPreferences sharedPreferences;
public static ArrayList<String> courseList;
public static ArrayList<String> courseSegmentList;
public static ArrayList<String> slotList;
public static ArrayList<String> CourseName;
//Fragment to be displayed on Home screen which will have 3 cards as layout.
private CardView bus, mess, timetable, cab;
private RecyclerView CabSharing;
private TextView mess1;
private final ArrayList<String> mEmails = new ArrayList<>();
private View view;
private RecyclerView myRV;
private SharedPreferences sharedPref;
private TextView t1, t2, t3, t4, mealName , b1 , b2 , b3 , b4;
private MultiStateToggleButton toggleButton;
private ConstraintLayout constraintLayout;
private final ArrayList<Lecture> lectures1 = new ArrayList<>();
private final ArrayList<String> T1 = new ArrayList<>();
private final ArrayList<String> T2 = new ArrayList<>();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_screen, container, false);
constraintLayout = view.findViewById(R.id.busview);
mess = view.findViewById(R.id.MessCard);
myRV = view.findViewById(R.id.Timetable_Recycler);
view.findViewById(R.id.MessScroll);
mealName = view.findViewById(R.id.textView15);
cab = view.findViewById(R.id.CabCard);
mess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragmentlayout, new MessMenu()).commit();
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_mess);
}
});
myRV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_acads);
}
});
timetable = view.findViewById(R.id.TimetableCard);
timetable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_acads);
}
});
bus = view.findViewById(R.id.BusCard);
bus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragmentlayout, new FragmentBS()).commit();
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_bus);
}
});
cab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), com.lambda.iith.dashboard.Cabsharing.CabSharing.class));
}
});
final float scale = getResources().getDisplayMetrics().density;
t1 = view.findViewById(R.id.toLing);
t2 = view.findViewById(R.id.toODF);
toggleButton = view.findViewById(R.id.BusToggleHome);
toggleButton.setValue(0);
t3 = view.findViewById(R.id.toLing2);
t4 = view.findViewById(R.id.toODF2);
b1 = view.findViewById(R.id.textView23);
b2 = view.findViewById(R.id.textView24);
b3 = view.findViewById(R.id.textView5);
b4 = view.findViewById(R.id.textView7);
double width2 = convertPxToDp(getContext(), Launch.width / 3);
ViewGroup.LayoutParams params = t1.getLayoutParams();
params.width = (int) ((width2 - 7) * scale + 0.5f);
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
t1.setLayoutParams(params);
t2.setLayoutParams(params);
t3.setLayoutParams(params);
t4.setLayoutParams(params);
b1.setLayoutParams(params);
b2.setLayoutParams(params);
b3.setLayoutParams(params);
b4.setLayoutParams(params);
toggleButton.setOnValueChangedListener(new ToggleButton.OnValueChangedListener() {
@Override
public void onValueChanged(int value) {
busmake(true);
}
});
CabSharing = view.findViewById(R.id.cs_home_recycler);
CabSharing.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_acad_info);
}
});
mess1 = view.findViewById(R.id.menu_home);
mess1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragmentlayout, new MessMenu()).commit();
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_mess);
}
});
mealName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragmentlayout, new MessMenu()).commit();
MainActivity.bottomNavigationView.setSelectedItemId(R.id.nav_mess);
}
});
sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPreferences = sharedPref;
cabCardMake(sharedPref.getBoolean("cab", true));
busmake(sharedPref.getBoolean("bus", true));
messmake(sharedPref.getBoolean("mess", true));
timetablemake(sharedPref.getBoolean("timetable", true));
if (sharedPreferences.getBoolean("RequestAutostart", false)) {
AutostartManager autostartManager = new AutostartManager(getContext());
sharedPreferences.edit().putBoolean("RequestAutostart", false).commit();
}
return view;
}
public double convertPxToDp(Context context, double px) {
return px / context.getResources().getDisplayMetrics().density;
}
private void busmake(boolean b) {
if (b) {
bus.setVisibility(View.VISIBLE);
new GetNextBus(sharedPreferences , toggleButton.getValue()).execute(t1 , t2 ,t3,t4);
} else {
bus.setVisibility(View.GONE);
}
}
private void messmake(boolean b) {
if (b) {
mess.setVisibility(View.VISIBLE);
JSONObject data = new JSONObject();
JSONObject data1 = new JSONObject();
JSONObject JO1 = new JSONObject();
try {
JSONObject JA;
if(sharedPreferences.getString("MESSJSON", "NULL").equals("NULL")){
Init init = new Init();
JO1 = new JSONObject(Init.DEF);
}
else{
JO1 = new JSONObject(sharedPreferences.getString("MESSJSON" , "NULL"));}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (sharedPref.getInt("MESSDEF", 1) == 1) {
data = JO1.getJSONObject("UDH");
data1 = JO1.getJSONObject("UDH Additional");
} else {
data = JO1.getJSONObject("LDH");
data1 = JO1.getJSONObject("LDH Additional");
}
int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
String string1 = "10:30:00";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "14:30:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
String string3 = "18:30:00";
Date time3 = new SimpleDateFormat("HH:mm:ss").parse(string3);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(time3);
String string4 = "22:30:00";
Date time4 = new SimpleDateFormat("HH:mm:ss").parse(string4);
Calendar calendar4 = Calendar.getInstance();
calendar4.setTime(time4);
Calendar calendarn = Calendar.getInstance();
Date d = calendarn.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate = dateFormat.format(d);
Date timen = new SimpleDateFormat("HH:mm:ss").parse(formattedDate);
ArrayList<String> a1 = new ArrayList<>();
a1.add("Sunday");
a1.add("Monday");
a1.add("Tuesday");
a1.add("Wednesday");
a1.add("Thursday");
a1.add("Friday");
a1.add("Saturday");
JSONObject JO = data.getJSONObject(a1.get(day - 1));
JSONObject JO11 = data1.getJSONObject(a1.get(day - 1));
JSONObject JO3 = data1.getJSONObject(a1.get(day % 7));
JSONObject JO2 = data.getJSONObject(a1.get(day % 7));
if (timen.before(time1)) {
mealName.setText("Today's Breakfast");
JSONArray L = JO.getJSONArray("Breakfast");
JSONArray L1 = JO11.getJSONArray("Breakfast");
mess1.setText(parseMeal(L, L1));
} else if (timen.after(calendar1.getTime()) && timen.before(calendar2.getTime())) {
//checkes whether the current time is between 10:30:00 and 14:30:00.
mealName.setText("Today's Lunch");
JSONArray L = JO.getJSONArray("Lunch");
JSONArray L1 = JO11.getJSONArray("Lunch");
mess1.setText(parseMeal(L, L1));
} else if (timen.after(calendar2.getTime()) && timen.before(calendar3.getTime())) {
mealName.setText("Today's Snacks");
JSONArray L = JO.getJSONArray("Snacks");
JSONArray L1 = JO11.getJSONArray("Snacks");
mess1.setText(parseMeal(L, L1));
} else if (timen.after(calendar3.getTime()) && timen.before(calendar4.getTime())) {
mealName.setText("Today's Dinner");
JSONArray L = JO.getJSONArray("Dinner");
JSONArray L1 = JO11.getJSONArray("Dinner");
mess1.setText(parseMeal(L, L1));
} else if (timen.after(time4)) {
mealName.setText("Tomorrow's Breakfast");
JSONArray L = JO2.getJSONArray("Breakfast");
JSONArray L1 = JO3.getJSONArray("Breakfast");
mess1.setText(parseMeal(L, L1));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
mess.setVisibility(View.GONE);
}
}
private String parseMeal(JSONArray JA1, JSONArray JA2) {
String string = "";
try {
for (int i = 0; i < JA1.length(); i++) {
string += (i + 1) + ".\u00A0" + JA1.getString(i).replace(" ", "\u00A0") + " ";
}
string += " \n\n";
string += "Extras:";
string += " \n";
for (int i = 0; i < JA2.length(); i++) {
string += (i + 1) + ".\u00A0" + JA2.getString(i).replace(" ", "\u00A0") + " ";
}
} catch (JSONException e) {
e.printStackTrace();
}
return string;
}
private void timetablemake(boolean b) {
if (b) {
try {
timetable.setVisibility(View.VISIBLE);
courseList = getArrayList("CourseList");
courseSegmentList = getArrayList("Segment");
slotList = getArrayList("SlotList");
CourseName = getArrayList("CourseName");
if (courseList != null) {
daily(sharedPref.getString("DefaultSegment", "12"));
}
} catch (Exception e) {
}
} else {
timetable.setVisibility(View.GONE);
}
}
private void cabCardMake(boolean b) {
if (b) {
if (sharedPref.getBoolean("Registered", false)) {
CabGet();
} else {
mEmails.clear();
mEmails.add("You are not using this feature");
cab.setVisibility(View.VISIBLE);
CabSharing = view.findViewById(R.id.cs_home_recycler);
RecyclerViewAdapter_CSHOME adapter = new RecyclerViewAdapter_CSHOME(getContext(), mEmails);
CabSharing.setAdapter(adapter);
CabSharing.setLayoutManager(new LinearLayoutManager(getContext()));
return;
}
} else {
cab.setVisibility(View.GONE);
}
}
private void CabGet() {
try {
mEmails.clear();
JSONArray JA3 = new JSONArray(sharedPref.getString("CabShares", null));
JSONObject JO3;
for (int j = 0; j < JA3.length(); j++) {
JO3 = (JSONObject) JA3.get(j);
mEmails.add(JO3.getString("Email"));
CabSharing = view.findViewById(R.id.cs_home_recycler);
RecyclerViewAdapter_CSHOME adapter = new RecyclerViewAdapter_CSHOME(getContext(), mEmails);
CabSharing.setAdapter(adapter);
CabSharing.setLayoutManager(new LinearLayoutManager(getContext()));
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
cab.setVisibility(View.VISIBLE);
}
@Override
public void onResume() {
super.onResume();
cabCardMake(sharedPref.getBoolean("cab", true));
busmake(sharedPref.getBoolean("bus", true));
messmake(sharedPref.getBoolean("mess", true));
timetablemake(sharedPref.getBoolean("timetable", true));
}
private ArrayList<String> getArrayList(String key) {
SharedPreferences prefs = sharedPref;
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {
}.getType();
return gson.fromJson(json, type);
}
private void daily(String segment) {
lectures1.clear();
T1.clear();
T2.clear();
int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
switch (day) {
case 2: {
dailyCreate("ABCDPQWX", segment);
return;
}
case 3: {
dailyCreate("DEFGRSYZ", segment);
return;
}
case 4: {
dailyCreate("BCAGF", segment);
return;
}
case 5: {
dailyCreate("CABEQPWX", segment);
return;
}
case 6: {
dailyCreate("EFDGSRYZ", segment);
return;
}
case 7:
case 1: {
dailyCreate("", segment);
return;
}
}
}
private void dailyCreate(String string, String segment) {
ArrayMap<String, Lecture> course = Timetable.courseMap.get((Integer.parseInt(segment.substring(0, 1)) - 1) / 2);
String[] start = {"09:00", "10:00", "11:00", "12:00", "14:30", "16:00", "17:30", "19:00"};
String[] end = {"10:00", "11:00", "12:00", "13:00", "16:00", "17:30", "19:00", "20:30"};
int temp = 0;
for (int i = 0; i < string.length(); i++) {
if (!course.get(string.substring(i, i + 1)).getCourseId().equals("")) {
lectures1.add(course.get(string.substring(i, i + 1)));
T1.add(start[i]);
T2.add(end[i]);
temp++;
}
}
if (temp == 0) {
Lecture lecture = new Lecture();
lecture.setCourse("NO LECTURES TODAY! Enjoy");
lectures1.add(lecture);
T1.add("");
T2.add("");
}
HomeTimeTableAdapter adapter = new HomeTimeTableAdapter(getContext(), lectures1, T1, T2);
myRV.setAdapter(adapter);
LinearLayoutManager layout = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
myRV.setLayoutManager(layout);
return;
}
}
|
package com.pratik.ms.controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.pratik.ms.model.Employee;
@RestController
@RequestMapping(value="/registration")
public class RegistrationController {
@RequestMapping(value="/test")
public String Test()
{
return "Test";
}
@RequestMapping(value="/register-employee", method = RequestMethod.POST, consumes="application/json", produces="application/json")
public @ResponseBody String register(@RequestBody Employee employee) {
System.out.println("Employee: " + employee);
return "registration success, please login";
}
}
|
package com.niit.backend.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.niit.backend.dao.Empdao;
import com.niit.backend.model.Employee;
@Repository("EmplService")
@Transactional
@Service
public class ImplService implements EmpService{
@Autowired
private Empdao empdao;
@Override
public List<Employee> getEmployeeList() {
return empdao.getEmployeeList();
}
@Override
public Employee getEmployee(int emplId) {
return empdao.getEmployee(emplId);
}
@Override
public boolean addEmployee(Employee emp) {
empdao.addEmployee(emp);
return true;
}
@Override
public boolean updateEmployee(Employee emp) {
empdao.updateEmployee(emp);
return true;
}
@Override
public boolean deleteEmployee(int emplId) {
empdao.deleteEmployee(emplId);
return false;
}
@Override
public Employee findbyId(int emplId) {
return empdao.getEmployee(emplId);
}
}
|
package org.point85.domain.http;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* OAuthAccessToken contains methods for handling an OAuth 2.0 access token
*
*/
public class OAuthAccessToken {
// expiration threshold (seconds)
private Duration threshold = Duration.ofSeconds(3600);
private String tokenType = "Bearer";
private String accessToken;
private Integer expiresIn;
private String refreshToken;
// when token was granted
private LocalDateTime obtainedOn;
public OAuthAccessToken() {
obtainedOn = LocalDateTime.now();
}
public OAuthAccessToken(String accessToken) {
obtainedOn = LocalDateTime.now();
this.accessToken = accessToken;
}
public Integer getExpiresIn() {
return this.expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public LocalDateTime getObtainedOn() {
return obtainedOn;
}
/**
* Determine duration before the access token will expire
*
* @return Duration before expiration
*/
public Duration determineTimeToLive() {
Duration elapsed = obtainedOn != null ? Duration.between(obtainedOn, LocalDateTime.now()) : Duration.ZERO;
return expiresIn != null ? Duration.ofSeconds(expiresIn).minus(elapsed) : Duration.ZERO;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String type) {
tokenType = type;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* Determine if the access token is going to expire by comparing the time to
* live to the threshold duration
*
* @return True if will expire soon, else false
*/
public boolean willExpire() {
boolean willExpire = false;
if (determineTimeToLive() != null) {
willExpire = determineTimeToLive().minus(threshold).isNegative();
}
return willExpire;
}
/**
* Determine if this token has access and refresh tokens
*
* @return True if valid, else false
*/
public boolean isValid() {
return this.accessToken != null && this.refreshToken != null;
}
public Duration getThreshold() {
return this.threshold;
}
public void setThreshold(Duration threshold) {
this.threshold = threshold;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Token: " + accessToken).append('\n');
sb.append("Refresh Token: " + refreshToken).append('\n');
sb.append("Expiration (sec): " + expiresIn).append('\n');
sb.append("Type: " + tokenType).append('\n');
sb.append("TTL: " + determineTimeToLive());
return sb.toString();
}
}
|
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IAndOCharStream {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f = new File("d:/Java/test.txt");
try (FileReader fr = new FileReader(f)) {
char[] all = new char[(int)f.length()];
fr.read(all);
for (char b : all) {
System.out.println(b);
}
}
catch (IOException e) {
e.printStackTrace();
}
try (FileWriter fr = new FileWriter(f)) {
String data = "hahah";
char[] cs = data.toCharArray();
fr.write(cs);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.redsun.platf.web.framework;
import com.redsun.platf.util.LogUtils;
import org.slf4j.Logger;
import org.springframework.web.servlet.mvc.AbstractController;
/**
* <p>Title: com.walsin.platf.web.framework.LoggingSupportController</p>
* <p>Description: 共用Log物件</p>
* <p>Copyright: Copyright (c) 2010</p>
* <p>Company: FreeLance</p>
*
* @author Jason Huang
* @version 1.0
*/
public abstract class LoggingSupportController extends AbstractController {
protected Logger _logger = LogUtils.getLogger(getClass());
/**
* Log 等級為 DEBUG.
*
* @param message 要 log 的訊息
*/
protected void debug(String message) {
if (_logger.isDebugEnabled()) {
_logger.debug(message);
}
}
/**
* Log 等級為 DEBUG.
*
* @param message 要 log 的訊息
* @param cause 錯誤的 exception.
*/
protected void debug(String message, Throwable cause) {
if (_logger.isDebugEnabled()) {
_logger.debug(message, cause);
}
}
/**
* Log 等級為 INFO.
*
* @param message 要 log 的訊息
*/
protected void info(String message) {
_logger.info(message);
}
/**
* Log 等級為 INFO.
*
* @param message 要 log 的訊息
* @param cause 錯誤的 exception.
*/
protected void info(String message, Throwable cause) {
_logger.info(message, cause);
}
/**
* Log 等級為 WARN.
*
* @param message 要 log 的訊息
*/
protected void warn(String message) {
_logger.warn(message);
}
/**
* Log 等級為 WARN.
*
* @param message 要 log 的訊息
* @param cause 錯誤的 exception.
*/
protected void warn(String message, Throwable cause) {
_logger.warn(message, cause);
}
/**
* Log 等級為 ERROR.
*
* @param message 要 log 的訊息
*/
protected void error(String message) {
_logger.error(message);
}
/**
* Log 等級為 ERROR.
*
* @param ex
*/
protected void error(Throwable ex) {
_logger.error(ex.getMessage(), ex);
}
/**
* Log 等級為 ERROR.
*
* @param message 要 log 的訊息
* @param cause 錯誤的 exception.
*/
protected void error(String message, Throwable cause) {
_logger.error(message, cause);
}
/**
* Log 等級為 FATAL.
*
* @param message 要 log 的訊息
*/
protected void fatal(String message) {
_logger.error(message);
}
/**
* Log 等級為 FATAL.
*
* @param message 要 log 的訊息
* @param cause 錯誤的 exception.
*/
protected void fatal(String message, Throwable cause) {
_logger.error(message, cause);
}
}
|
package utils;
import bean.AdminLoginBean;
import bean.StudentInfoBean;
import bean.StudentLoginBean;
import java.util.ArrayList;
import java.util.List;
public class LoginUtils {
private JDBCUtils mJDBCUtils = JDBCUtils.getInstance();
public LoginUtils() {
mJDBCUtils.getConnection();
}
public String login(String username, String password, int type) {
String res = "登录失败";
List<Object> params = new ArrayList<Object>();
params.add(username);
params.add(password);
if (type == 0) {
// 学生登录
String sql = "select * from STUDENT_LOGIN_INFO where u_account = ? and u_password = ?";
try {
StudentLoginBean bean = mJDBCUtils.findSimpleRefResult(sql, params, StudentLoginBean.class);
if (bean != null) {
String account = bean.getuAccount();
List<Object> mparams = new ArrayList<Object>();
mparams.add(account);
String msql = "select * from STUDENT_INFO where s_account = ?";
StudentInfoBean sinfo = mJDBCUtils.findSimpleRefResult(msql, mparams, StudentInfoBean.class);
if(sinfo != null){
Constants.loginUser = sinfo;
}
res = "登录成功";
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (type == 1) {
// 管理员登录
String sql = "select * from ADMIN_LOGIN_INFO where a_account = ? and a_password = ?";
try {
AdminLoginBean bean = mJDBCUtils.findSimpleRefResult(sql, params, AdminLoginBean.class);
if (bean != null) {
Constants.loginUser = bean;
res = "登录成功";
}
} catch (Exception e) {
e.printStackTrace();
}
}
return res;
}
private void logOut() {
Constants.loginUser = null;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (mJDBCUtils != null) {
mJDBCUtils.releaseConn();
mJDBCUtils = null;
}
System.out.println(this.getClass().toString() + "销毁了");
}
}
|
package model.player;
public enum PlayerType
{
Batsman, Bowler, BattingAllrounder, BowlingAllrounder,
Allrounder, WicketkeeperBatsman
}
|
package icw.bankingdriver;
import icw.bankingdriver.BankAccount;
/*
Next, design a checking account class,
also derived from the generic account class.
It should have the following member functions:
withdraw:
Before the base class function is called,
this function will determine if a withdrawal (a check written)
will cause the balance to go below $0.
If the balance goes below $0,
a service charge of $15 will be taken from the account.
(The withdrawal will not be made.)
If there isn’t enough in the account to pay the service charge,
the balance will become negative and the customer will owe the negative amount to the bank.
monthlyProc:
Before the base class function is called,
this function adds the monthly fee of $5 plus $0.10 per withdrawal (check written)
to the base class variable that holds the monthly service charges.
*/
/**
*
* @author bernice.templeman001
*/
public class Checking extends BankAccount {
public Checking(double balance, double annualInterestRate) {
super(balance, annualInterestRate);
}
@Override
public void withdraw(double amount)
{
}
}
|
package cz.muni.fi.pa165.monsterslayers.dao;
import cz.muni.fi.pa165.monsterslayers.entities.ClientRequest;
import org.springframework.data.repository.CrudRepository;
/**
* Client request repository interface extending spring CrudRepository
*
* @author Maksym Tsuhui
*/
public interface ClientRequestRepository extends CrudRepository<ClientRequest, Long> {
/**
* Finds client request with specified title (title is unique)
* @param title specified title
* @return client request with specified title
*/
ClientRequest findByTitle(String title);
}
|
package it.polito.tdp.imdb.model;
import java.util.*;
import org.jgrapht.Graph;
import org.jgrapht.Graphs;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;
import it.polito.tdp.imdb.db.ImdbDAO;
public class Model {
ImdbDAO DAO;
private List <Integer> anno = new LinkedList<Integer>();
private Map <Integer,Director> idMap = new HashMap <Integer,Director>();
private Graph<Director, DefaultWeightedEdge> grafo;
public Model() {
DAO= new ImdbDAO();
}
public List<Integer> boxAnnoCrea() {
anno.add(2004);
anno.add(2005);
anno.add(2006);
return anno;
}
public void creaGrafo(int x) {
grafo= new SimpleWeightedGraph<Director, DefaultWeightedEdge>(DefaultWeightedEdge.class);
Graphs.addAllVertices(grafo,DAO.getVertici(x, idMap));
for(Adiacenza a : DAO.getArchi(idMap)) {
if(grafo.containsVertex(a.getD1()) && grafo.containsVertex(a.getD2())) {
Graphs.addEdgeWithVertices(grafo,a.getD1(),a.getD2(), a.getPeso());
}
}
System.out.println("Creato grafo con:\n#VERTICI: "+grafo.vertexSet().size()+"#ARCHI: "+grafo.edgeSet().size());
}
}
|
package commands.client.game;
import java.util.List;
import java.util.Set;
import commands.server.ingame.HeroSelectionInGameServerCommand;
import commands.server.ingame.HeroSelectionTimeoutInGameServerCommand;
import commands.server.ingame.InGameServerCommand;
import core.client.game.operations.Operation;
import core.client.game.operations.mechanics.HeroSelectionOperation;
import core.heroes.Hero;
import core.player.PlayerCompleteServer;
public class EmperorHeroSelectionGameClientCommand extends AbstractSingleTargetOperationGameClientCommand {
private static final long serialVersionUID = 1L;
private final List<Hero> availableHeroes;
public EmperorHeroSelectionGameClientCommand(PlayerCompleteServer target, List<Hero> availableHeroes) {
super(target.getPlayerInfo());
this.availableHeroes = availableHeroes;
this.timeoutMS = 30000; // allow each player to spend 30s on hero selection
}
@Override
protected boolean shouldClearGamePanel() {
return false;
}
@Override
protected Operation getOperation() {
return new HeroSelectionOperation(availableHeroes);
}
@Override
public Set<Class<? extends InGameServerCommand>> getAllowedResponseTypes() {
return Set.of(HeroSelectionInGameServerCommand.class);
}
@Override
public InGameServerCommand getDefaultResponse() {
return new HeroSelectionTimeoutInGameServerCommand();
}
@Override
public void setResponseTimeoutMS(int timeMS) {
// disable changing timeout
}
@Override
protected String getMessageForOthers() {
return "Waiting on " + target.getName() + " to select a hero";
}
}
|
package com.github.riyaz.bakingapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import com.github.riyaz.bakingapp.model.Recipe;
/**
* Created on 23 Aug, 2018
*
* @author Riyaz
*/
public class InjectRecipeActivityTestRule<T extends Activity> extends ActivityTestRule<T> {
private Class<T> activityClass;
private String extrasToUse;
private Recipe recipeToProvide;
public InjectRecipeActivityTestRule(Class<T> activityClass) {
super(activityClass);
this.activityClass = activityClass;
}
public InjectRecipeActivityTestRule<T> provide(@NonNull String extra, @NonNull Recipe recipe){
this.extrasToUse = extra;
this.recipeToProvide = recipe;
return this;
}
@Override protected Intent getActivityIntent() {
// get the context
Context target = InstrumentationRegistry.getInstrumentation().getTargetContext();
// create new Intent
return new Intent(target, activityClass)
.putExtra(extrasToUse, recipeToProvide);
}
}
|
package model.error;
public class ErrorPosicionInvalida extends Exception {
}
|
package com.delrima.webgene.arch.client.validation.validators;
import com.delrima.webgene.arch.client.validation.Validator;
/**
* <p>
* Validate a double value
* </p>
*
* @author bhavesh.thakker@ihg.com
* @since Sep 22, 2008
*
*/
public class DoubleValidator implements Validator {
public static final DoubleValidator INSTANCE = new DoubleValidator();
/** Creates a new instance of DoubleValidator */
private DoubleValidator() {
}
public boolean isValid(Object value) {
if (value == null) {
return false;
}
try {
new Double(value.toString());
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
}
|
package sqldata;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import po.MatchPO;
import po.MatchResult;
import po.PlayerPO;
import po.PlayerPerformancePO;
import po.Position;
import po.TeamPO;
import po.TeamPerformancePO;
import util.DBConnectionPool;
public class MatchLoader {
private ArrayList<MatchPO> matchList = null;
public MatchLoader(){
matchList = new ArrayList<>();
}
public ArrayList<MatchPO> getMatchList(String beginString, String endString){
Statement statement = null;
String matchQuery = "select * from matchinfo where date >= '"
+ beginString
+ "' and date <= '"
+ endString
+ "' order by date asc";
try{
statement = DBConnectionPool.getInstance().getStatement();
ResultSet matchSet = statement.executeQuery(matchQuery);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
while(matchSet.next()){
MatchPO match = new MatchPO();
String[] dates = sdf.format(matchSet.getDate("date")).split("-");
Calendar.Builder builder = new Calendar.Builder();
builder.setDate(Integer.parseInt(dates[0]),Integer.parseInt(dates[1])-1, Integer.parseInt(dates[2]));
match.setDate(builder.build());
TeamPerformancePO homeTP = getTeamPerformance(matchSet.getString("gameid"), matchSet.getString("hometeamid"),
matchSet.getString("hometeamabbr"), matchSet.getInt("hometeampts"));
homeTP.setIsHome(true);
homeTP.setMatchIndex(matchList.size());
match.putTeamPerformance(homeTP.getTeamAbbr(), homeTP);
TeamPO homeTeam = DataCache.getInstance().getTeamMap().get(homeTP.getTeamAbbr());
try{
homeTeam.addMatchIndex(matchList.size());
}catch(NullPointerException e){
System.err.println(homeTP.getTeamAbbr());
}
TeamPerformancePO visitorTP = getTeamPerformance(matchSet.getString("gameid"), matchSet.getString("visitorteamid"),
matchSet.getString("visitorteamabbr"), matchSet.getInt("visitorteampts"));
visitorTP.setIsHome(false);
visitorTP.setMatchIndex(matchList.size());
TeamPO visitorTeam = DataCache.getInstance().getTeamMap().get(visitorTP.getTeamAbbr());
try{
visitorTeam.addMatchIndex(matchList.size());
}catch(NullPointerException e){
System.err.println(visitorTP.getTeamAbbr());
}
if(homeTP.getTotalPoints() > visitorTP.getTotalPoints()){
homeTP.setResult(MatchResult.WIN);
visitorTP.setResult(MatchResult.LOSE);
}else{
homeTP.setResult(MatchResult.LOSE);
visitorTP.setResult(MatchResult.WIN);
}
match.putTeamPerformance(visitorTP.getTeamAbbr(), visitorTP);
Date matchDate = match.getDate().getTime();
ArrayList<Integer> indexList = null;
HashMap<Date, ArrayList<Integer>> dateMap = DataCache.getInstance().getDateMatchMap();
if(dateMap.containsKey(matchDate)){
indexList = dateMap.get(matchDate);
indexList.add(matchList.size());
}else{
indexList = new ArrayList<Integer>();
indexList.add(matchList.size());
dateMap.put(matchDate, indexList);
}
matchList.add(match);
}
} catch (Exception e) {
System.err.println("Problems with sql loading match of season: "
+ beginString +" to " + endString);
e.printStackTrace();
} finally{
try {
statement.close();
} catch (SQLException e) {
System.err.println("Statement close failure");
e.printStackTrace();
}
}
return matchList;
}
private TeamPerformancePO getTeamPerformance(String gameid,String teamID,String teamAbbr, int teamPTS) throws SQLException{
String homeTeamQuery = "select * from periodpts where gameid = '"
+ gameid
+ "' and teamid = '"
+ teamID
+ "' order by periodnum asc";
Statement statement = DBConnectionPool.getInstance().getStatement();
ResultSet periodSet = statement.executeQuery(homeTeamQuery);
TeamPerformancePO tp = new TeamPerformancePO();
tp.setTeamAbbr(teamAbbr);
tp.setTotalPoints(teamPTS);
while(periodSet.next()){
tp.addPeriodPoints(periodSet.getInt("pts"));
}
String homePlayerQuery = "select * from playerdata where gameid = '"
+ gameid
+ "' and teamid = '"
+ teamID
+ "'";
ResultSet playerSet = statement.executeQuery(homePlayerQuery);
while(playerSet.next()){
PlayerPerformancePO pp = new PlayerPerformancePO();
pp.setPlayerName(playerSet.getString("playername"));
pp.setIsStarter(true);
switch (playerSet.getString("pos")) {
case "F":
pp.setPosition(Position.F);
break;
case "C":
pp.setPosition(Position.C);
break;
case "G":
pp.setPosition(Position.G);
break;
default:
pp.setIsStarter(false);
break;
}
pp.setTime(playerSet.getInt("sec"));
pp.setShotHitCnt(playerSet.getInt("shotmade"));
pp.setShotAttemptCnt(playerSet.getInt("shotatt"));
pp.setThreeHitCnt(playerSet.getInt("3made"));
pp.setThreeAttemptCnt(playerSet.getInt("3att"));
pp.setPenaltyHitCnt(playerSet.getInt("ftmade"));
pp.setPenaltyAttemptCnt(playerSet.getInt("ftatt"));
pp.setOffReboundCnt(playerSet.getInt("oreb"));
pp.setDefReboundCnt(playerSet.getInt("dreb"));
pp.setReboundCnt(playerSet.getInt("reb"));
pp.setAssistCnt(playerSet.getInt("ast"));
pp.setStealCnt(playerSet.getInt("stl"));
pp.setBlockCnt(playerSet.getInt("blk"));
pp.setTurnoverCnt(playerSet.getInt("tov"));
pp.setFoulCnt(playerSet.getInt("foul"));
pp.setPoints(playerSet.getInt("pts"));
pp.setTeam(playerSet.getString("teamabbr"));
pp.setHasDouble(hasDouble(pp));
pp.setMatchIndex(matchList.size());
tp.putPlayerPerformance(pp.getPlayerName(), pp);
PlayerPO player = DataCache.getInstance().getPlayerMap().get(pp.getPlayerName());
player.addTeam(pp.getTeam());
player.addMatchIndex(matchList.size());
}
return tp;
}
private boolean hasDouble(PlayerPerformancePO playerPerformance){
int DDCounter = 0;
int[] statistic = {playerPerformance.getPoints(),playerPerformance.getReboundCnt(),
playerPerformance.getAssistCnt(),playerPerformance.getStealCnt(),
playerPerformance.getBlockCnt()};
for(int i=0 ; i<4 ; ++i){
if (statistic[i] >= 10) DDCounter++;
}
if(DDCounter>=2) return true;
else return false;
}
}
|
package jenkins.plugins.hipchat;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.assertFalse;
import static org.junit.Assert.assertArrayEquals;
public class StandardHipChatServiceTest {
@Test
public void publishWithBadHostShouldNotRethrowExceptions() {
StandardHipChatService service = new StandardHipChatService("badhost", "token", "room", "from", false);
service.publish("message");
}
@Test
public void shouldSetADefaultHost() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room", "from", false);
assertEquals("api.hipchat.com", service.getHost());
}
@Test
public void shouldBeAbleToOverrideHost() {
StandardHipChatService service = new StandardHipChatService("some.other.host", "token", "room", "from", false);
assertEquals("some.other.host", service.getHost());
}
@Test
public void shouldSplitTheRoomIds() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room1,room2", "from", false);
assertArrayEquals(new String[]{"room1", "room2"}, service.getRoomIds());
}
@Test
public void shouldTrimTheRoomIds() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room1, room2", "from", false);
assertArrayEquals(new String[]{"room1", "room2"}, service.getRoomIds());
}
@Test
public void shouldNotSplitTheRoomsIfNullIsPassed() {
StandardHipChatService service = new StandardHipChatService(null, "token", null, "from", false);
assertArrayEquals(new String[0], service.getRoomIds());
}
@Test
public void shouldProvideADefaultFrom() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room", null, false);
assertEquals("Build Server", service.getFrom());
}
@Test
public void shouldBeAbleToOverrideFrom() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room", "from", false);
assertEquals("from", service.getFrom());
}
@Test
public void shouldOverrideAPIToVersion2() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room", "from", true);
assertTrue(service.isV2API());
}
@Test
public void shouldAPIDefaultToVersion1() {
StandardHipChatService service = new StandardHipChatService(null, "token", "room", "from", false);
assertFalse(service.isV2API());
}
}
|
package com.ctt;
import org.mybatis.spring.annotation.MapperScan;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
@SpringBootApplication
@EnableScheduling
@ComponentScan(value = "com.ctt.*")
@MapperScan(basePackages = "com.ctt.mapper")
public class FilePreviewApplication {
public static void main(String[] args) {
Properties properties = System.getProperties();
System.out.println(properties.get("user.dir"));
SpringApplication.run(FilePreviewApplication.class, args);
/**
* CANCELLED(1):表示当前结点已取消调度。当timeout或被中断(响应中断的情况下),会触发变更为此状态,进入该状态后的结点将不会再变化。
* SIGNAL(-1):表示后继结点在等待当前结点唤醒。后继结点入队时,会将前继结点的状态更新为SIGNAL。
* CONDITION(-2):表示结点等待在Condition上,当其他线程调用了Condition的signal()方法后,CONDITION状态的结点将从等待队列转移到同步队列中,等待获取同步锁。
* PROPAGATE(-3):共享模式下,前继结点不仅会唤醒其后继结点,同时也可能会唤醒后继的后继结点。
* 0:新结点入队时的默认状态。
*/
ReentrantLock reentrantLock = new ReentrantLock();
reentrantLock.tryLock(1,TimeUnit.MILLISECONDS)
}
}
|
/*
* © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
* verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted
* to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
*/
package cern.molr.inspector.jdi;
import com.sun.jdi.ClassType;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.event.ClassPrepareEvent;
import org.jdiscript.handlers.OnClassPrepare;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
/**
* An {@link OnClassPrepare} implementation which keeps track of new implementations of a given class (or interface).
* Whenever a class that has not been initialised before is added, the callback given in the constructor is called.
* This class is not thread safe.
*/
public class ClassInstantiationListener implements OnClassPrepare {
private static final Logger LOGGER = LoggerFactory.getLogger(ClassInstantiationListener.class);
private final Consumer<ClassType> implementorCallback;
private final String implementorClass;
private Set<ClassType> currentImplementations = new HashSet<>();
/**
* Creates a new listener instructed to search for implementations of the given class. The callback will be
* called everytime a class or subclass is instantiated that has <i>not</i> been instantiated - i. e. created
* for the first time.
*
* @param implementorClass The class or interface to search for.
* @param implementorCallback A callback to call whenever a new (unique) class instance is created.
*/
public ClassInstantiationListener(String implementorClass, Consumer<ClassType> implementorCallback) {
this.implementorClass = implementorClass;
this.implementorCallback = implementorCallback;
}
@Override
public void classPrepare(ClassPrepareEvent event) {
final ReferenceType referenceType = event.referenceType();
if (referenceType == null) {
LOGGER.warn("No reference type defined in class preparation event: {}", event);
} else if (referenceType instanceof ClassType) {
final ClassType classType = (ClassType) referenceType;
if (isClassEquals(classType, implementorClass) && !currentImplementations.contains(classType)) {
currentImplementations.add(classType);
implementorCallback.accept(classType);
}
}
}
/**
* Tests if the given {@link ClassType} is representing the same class as the given {@link Class} by comparing their
* full path names.
*
* @param type The class type to test.
* @return True if the classes are considered the same.
*/
static boolean isClassEquals(ClassType type, String className) {
return type.name().equals(className);
}
}
|
package com.gcc.controller;
import com.gcc.entity.Citys;
import com.gcc.interceptor.RequireLogin;
import com.gcc.service.CitysService;
import com.gcc.vo.CityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* (Citys)Table layer controller
*
* @author an yushi
* @since 2020-12-10 09:57:17
*/
@RestController
@RequestMapping("citys")
public class CitysController {
@Autowired
private CitysService citysService;
/**
* Query matching data through cityVO
*
* @param cityVO
* @return List<Citys>
*/
@PostMapping("select")
public List<Citys> select(@RequestBody CityVO cityVO) {
return citysService.select(cityVO);
}
/**
* Query all Citys data
*
* @param
* @return List<Citys>
*/
@GetMapping("selectAllCitys")
@RequireLogin(seconds = 5, maxCount = 5, needLogin = true)
public List<Citys> selectAllCitys() {
return citysService.selectAllCitys();
}
/**
* insert Citys
*
* @param cityVO
* @return Citys
*/
@PostMapping("insert")
@RequireLogin(seconds = 5, maxCount = 5, needLogin = true)
public Citys insertCitys(@RequestBody CityVO cityVO) {
return citysService.insertCitys(cityVO);
}
/**
* delete Citys
*
* @param cityId
* @return boolean
*/
@DeleteMapping("delete")
@RequireLogin(seconds = 5, maxCount = 5, needLogin = true)
public boolean deleteCitys(@RequestParam Integer cityId) {
return citysService.deleteById(cityId);
}
/**
* Update the specified City data
*
* @param cityVO
* @return Citys
*/
@PutMapping("update")
@RequireLogin(seconds = 5, maxCount = 5, needLogin = true)
public Citys updateCitys(@RequestBody CityVO cityVO) {
return citysService.updateCitys(cityVO);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.ext.matlab.worker;
import com.activeeon.proactive.license_saver.client.LicenseSaverClient;
import org.objectweb.proactive.core.ProActiveException;
import org.ow2.proactive.scheduler.ext.common.util.IOTools;
import org.ow2.proactive.scheduler.ext.matlab.common.PASolveMatlabGlobalConfig;
import org.ow2.proactive.scheduler.ext.matlab.common.PASolveMatlabTaskConfig;
import org.ow2.proactive.scheduler.ext.matlab.common.exception.MatlabInitException;
import org.ow2.proactive.scheduler.ext.matlab.common.exception.MatlabTaskException;
import org.ow2.proactive.scheduler.ext.matlab.common.exception.UnreachableLicenseProxyException;
import org.ow2.proactive.scheduler.ext.matlab.common.exception.UnsufficientLicencesException;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
/**
* MatlabConnectionRImpl this class
*
* @author The ProActive Team
*/
public class MatlabConnectionRImpl implements MatlabConnection {
/** System-dependent line separator */
public static final String nl = System.getProperty("line.separator");
/** Pattern used to remove Matlab startup message from logs */
private static final String startPattern = "---- MATLAB START ----";
/** Startup Options of the Matlab process */
protected String[] startUpOptions;
/** Location of the Matlab process */
protected String matlabLocation;
/** Full Matlab code which will be executed by the Matlab process */
protected StringBuilder fullcommand = new StringBuilder();
/** File used to store MATLAB code to be executed */
protected File mainFuncFile;
/** Directory where the MATLAB process should start (Localspace) */
protected File workingDirectory;
/** File used to capture MATLAB process output (in addition to Threads) */
protected File logFile;
/** Stream used for debug output */
private final PrintStream outDebug;
/** The temp directory */
private final String tmpDir;
/** The ProActive node name */
private final String nodeName;
/** Timeout for the matlab process startup x 10 ms */
protected static final int TIMEOUT_START = 6000;
/** Debug mode */
protected boolean debug;
/** MATLAB Process */
protected Process process;
/** Lock used to prevent process destroy while starting up */
protected Boolean running = false;
/** Licensing Proxy Server Client */
private LicenseSaverClient lclient;
/** Matlab configuration of the current job */
PASolveMatlabGlobalConfig paconfig;
/** Matlab configuration of the current task */
PASolveMatlabTaskConfig tconfig;
public MatlabConnectionRImpl(final String tmpDir, final PrintStream outDebug, final String nodeName) {
this.tmpDir = tmpDir;
this.outDebug = outDebug;
this.nodeName = nodeName;
}
public void acquire(String matlabExecutablePath, File workingDir, PASolveMatlabGlobalConfig paconfig,
PASolveMatlabTaskConfig tconfig) throws MatlabInitException {
this.matlabLocation = matlabExecutablePath;
this.workingDirectory = workingDir;
this.debug = paconfig.isDebug();
this.paconfig = paconfig;
this.tconfig = tconfig;
this.startUpOptions = paconfig.getStartupOptions();
this.logFile = new File(tmpDir, "MatlabStart" + nodeName + ".log");
this.mainFuncFile = new File(workingDir, "PAMain.m");
if (!mainFuncFile.exists()) {
try {
mainFuncFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (paconfig.getLicenseServerUrl() != null) {
try {
this.lclient = new LicenseSaverClient(paconfig.getLicenseServerUrl());
} catch (ProActiveException e) {
throw new MatlabInitException(new UnreachableLicenseProxyException(
"License Proxy Server at url " + paconfig.getLicenseServerUrl() +
" could not be contacted.", e));
}
}
}
public void init() {
fullcommand.append("function PAmain()" + nl);
fullcommand.append("disp('" + startPattern + "');" + nl);
fullcommand.append("try" + nl);
}
public void release() {
synchronized (running) {
if (process != null) {
try {
process.destroy();
process = null;
} catch (Exception e) {
}
}
running = false;
}
}
public void execCheckToolboxes(String command) {
fullcommand.append(command);
}
public void evalString(String command) throws MatlabTaskException {
fullcommand.append(command + nl);
}
public Object get(String variableName) throws MatlabTaskException {
throw new UnsupportedOperationException();
}
public void put(String variableName, Object value) throws MatlabTaskException {
throw new UnsupportedOperationException();
}
public void launch() throws Exception {
fullcommand.append("catch ME" + nl + "disp('Error occured in .');" + nl + "disp(getReport(ME));" +
nl + "end" + nl + "exit();");
PrintStream out = null;
try {
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(mainFuncFile)));
} catch (FileNotFoundException e) {
sendAck(false);
throw e;
}
out.println(fullcommand);
out.flush();
out.close();
synchronized (running) {
process = createMatlabProcess("cd('" + this.workingDirectory + "');PAMain();");
running = true;
}
IOTools.LoggingThread lt1;
if (debug) {
lt1 = new IOTools.LoggingThread(process, "[MATLAB]", System.out, System.err, outDebug, null,
null, "License checkout failed");
} else {
lt1 = new IOTools.LoggingThread(process, "[MATLAB OUT]", System.out, System.err, startPattern,
null, "License checkout failed");
}
Thread t1 = new Thread(lt1, "OUT MATLAB");
t1.setDaemon(true);
t1.start();
File ackFile = new File(workingDirectory, "matlab.ack");
File nackFile = new File(workingDirectory, "matlab.nack");
int cpt = 0;
while (!ackFile.exists() && !nackFile.exists() && (cpt < TIMEOUT_START) && !lt1.patternFound &&
running) {
try {
int exitValue = process.exitValue();
sendAck(false);
// lt1.goon = false; unnecessary as matlab process exited
throw new MatlabInitException("Matlab process exited with code : " + exitValue);
} catch (Exception e) {
// ok process still exists
}
Thread.sleep(10);
cpt++;
}
if (ackFile.exists()) {
ackFile.delete();
}
if (nackFile.exists()) {
nackFile.delete();
sendAck(false);
lt1.goon = false;
throw new UnsufficientLicencesException();
}
if (lt1.patternFound) {
process.destroy();
process = null;
lt1.goon = false;
sendAck(false);
throw new UnsufficientLicencesException();
}
if (cpt >= TIMEOUT_START) {
process.destroy();
process = null;
lt1.goon = false;
sendAck(false);
throw new MatlabInitException("Timeout occured while starting Matlab");
}
if (!running) {
lt1.goon = false;
sendAck(false);
throw new MatlabInitException("Task killed while initialization");
}
sendAck(true);
int exitValue = process.waitFor();
if (exitValue != 0) {
throw new MatlabInitException("Matlab process exited with code : " + exitValue +
" after task started.");
}
}
protected void sendAck(boolean ack) throws Exception {
if (lclient != null) {
try {
lclient.notifyLicenseStatus(tconfig.getRid(), ack);
} catch (Exception e) {
throw new UnreachableLicenseProxyException(
"Error while sending ack to License Proxy Server at url " +
paconfig.getLicenseServerUrl(), e);
}
}
}
protected Process createMatlabProcess(String runArg) throws Exception {
// Attempt to run MATLAB
final ArrayList<String> commandList = new ArrayList<String>();
commandList.add(this.matlabLocation);
commandList.addAll(Arrays.asList(this.startUpOptions));
commandList.add("-logfile");
commandList.add(logFile.toString());
commandList.add("-r");
commandList.add(runArg);
String[] command = (String[]) commandList.toArray(new String[commandList.size()]);
ProcessBuilder b = new ProcessBuilder();
// invalid on windows, it affects the starter only
b.directory(this.workingDirectory);
b.command(command);
// Fix for SCHEDULING-1309: If MATLAB client uses RunAsMe option the MATLAB
// worker jvm can crash if the client user has never started any MATLAB
// session on the worker host
// Since the user profile can be missing on Windows with RunAsMe, by setting
// the MATLAB_PREFDIR variable to a writable dir (can be non-writable on Windows with RunAsMe)
// the MATLAB doesn't crash no more
Map<String, String> env = b.environment();
// Transmit the prefdir as env variable
String matlabPrefdir = System.getProperty(MatlabExecutable.MATLAB_PREFDIR);
if (matlabPrefdir != null) {
env.put("MATLAB_PREFDIR", matlabPrefdir);
}
// Transmit the tmpdir as env variable
String matlabTmpvar = System.getProperty(MatlabExecutable.MATLAB_TASK_TMPDIR);
if (matlabTmpvar != null) {
env.put("TEMP", matlabTmpvar);
env.put("TMP", matlabTmpvar);
}
return b.start();
}
}
|
package com.example.demo.service.impl;
import com.example.demo.service.CaptureImgService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.net.URLEncoder;
/**
* Created by HuangYanfei on 2018/11/8.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class CaptureImgServiceImplTest {
@Autowired
CaptureImgService captureImgService;
@Test
public void test(){
try {
String path=captureImgService.captureImg(null,
"pdfRadar?companyId=" + URLEncoder.encode("", "utf8")
+ "&keyValue=" + URLEncoder.encode("", "utf8"), "600px*500px");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package car_rent.rent;
public enum GearBox {
AUTO, MANUAL
}
|
package com.jim.mybatis.model.mapper;
import com.jim.mybatis.model.po.Privilege;
public interface PrivilegeMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
int insert(Privilege record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
int insertSelective(Privilege record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
Privilege selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
int updateByPrimaryKeySelective(Privilege record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table privileges
*
* @mbggenerated Thu Sep 21 01:16:58 CST 2017
*/
int updateByPrimaryKey(Privilege record);
}
|
package com.saasxx.core.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.hibernate.cache.ehcache.EhCacheRegionFactory;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import com.saasxx.framework.Lang;
import com.saasxx.framework.dao.jdbc.JpaProxyDataSource;
import com.saasxx.framework.dao.orm.jpa.ImplicitNamingStrategyCompliantImpl;
import com.saasxx.framework.dao.orm.jpa.JpaCommentListener;
import com.saasxx.framework.io.FilePool;
import com.saasxx.framework.lang.Springs;
import com.saasxx.framework.startup.StartupListener;
import net.sf.log4jdbc.sql.jdbcapi.DataSourceSpy;
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(value = Constants.BACKAGE_DAO)
@MapperScan(Constants.BACKAGE_DAO)
@Configuration
@EnableAspectJAutoProxy
@ComponentScan({Constants.BACKAGE_DAO, Constants.BACKAGE_SERVICE, Constants.BACKAGE_STARTUP})
public class MainConfig {
private Environment env = Springs.getEnvironment("classpath:${spring.profiles.active}/config.properties");
@Autowired
ApplicationContext ac;
@Bean
public DataSource dataSource() {
String jndiName = env.getProperty("db.jndi_name");
if (!Lang.isEmpty(jndiName)) {
JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
try {
dsLookup.setResourceRef(false);
return dsLookup.getDataSource(jndiName);
} catch (Exception e) {
dsLookup.setResourceRef(true);
return dsLookup.getDataSource(jndiName);
}
}
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
dataSource.setTestWhileIdle(false);
return new DataSourceSpy(dataSource);
}
@Bean
public DataSource jpaProxyDataSource() {
return new JpaProxyDataSource();
}
@Bean
public StartupListener startupListenerDev() {
StartupListener startupListener = new StartupListener();
startupListener.setBasePackages(Constants.BACKAGE_STARTUP);
return startupListener;
}
@Bean
public JpaCommentListener jpaCommentListener() {
JpaCommentListener jpaCommentListener = new JpaCommentListener();
jpaCommentListener.setEntityManagerFactory(ac.getBean(EntityManagerFactory.class));
jpaCommentListener.setActiveProfiles("dev");
return jpaCommentListener;
}
@Bean
public PlatformTransactionManager transactionManager() throws ClassNotFoundException {
return new JpaTransactionManager(entityManagerFactory().getObject());
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan(Constants.BACKAGE_SCHEMA);
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
Properties jpaProperties = new Properties();
// SQL generation / debugging
jpaProperties.put(AvailableSettings.FORMAT_SQL, false);
jpaProperties.put(AvailableSettings.SHOW_SQL, false);
jpaProperties.put(AvailableSettings.HBM2DDL_AUTO, env.getProperty(AvailableSettings.HBM2DDL_AUTO));
jpaProperties.put(AvailableSettings.GENERATE_STATISTICS, true);
// Second level caching
jpaProperties.put(AvailableSettings.USE_SECOND_LEVEL_CACHE, true);
jpaProperties.put(AvailableSettings.USE_QUERY_CACHE, env.getProperty(AvailableSettings.USE_QUERY_CACHE));
jpaProperties.put(AvailableSettings.USE_STRUCTURED_CACHE, true);
// for redis cache implement
// jpaProperties.put(AvailableSettings.CACHE_REGION_FACTORY,
// SingletonRedisRegionFactory.class.getName());
// jpaProperties.put(AvailableSettings.CACHE_REGION_PREFIX,
// "hibernate-redis");
// jpaProperties.put(AvailableSettings.USE_STRUCTURED_CACHE, true);
// jpaProperties.put(AvailableSettings.CACHE_PROVIDER_CONFIG,
// env.getActiveProfiles()[0] + "/cache/hibernate-redis.properties");
// for ehcache implement
jpaProperties.put(AvailableSettings.CACHE_REGION_FACTORY, EhCacheRegionFactory.class.getName());
jpaProperties.put(AvailableSettings.CACHE_REGION_PREFIX, "hibernate-ehcache");
jpaProperties.put("net.sf.ehcache.configurationResourceName",
env.getActiveProfiles()[0] + "/cache/hibernate-ehcache.xml");
//
// We
// only
// have
// one
// active
// profile
jpaProperties.put(AvailableSettings.DIALECT, env.getProperty(AvailableSettings.DIALECT));
jpaProperties.put(AvailableSettings.IMPLICIT_NAMING_STRATEGY,
ImplicitNamingStrategyCompliantImpl.class.getCanonicalName());
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
String basePackage = Constants.BACKAGE_DAO;
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackage.replace('.', '/')
+ "/" + "**/*.xml";
sessionFactory.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
// 配置分页信息
PageHelper pageHelper = new PageHelper();
Properties pageHelperProperties = new Properties();
pageHelperProperties.put("dialect", "mysql");
pageHelperProperties.put("offsetAsPageNum", true);
pageHelperProperties.put("rowBoundsWithCount", true);
pageHelperProperties.put("pageSizeZero", true);
pageHelperProperties.put("reasonable", true);
pageHelper.setProperties(pageHelperProperties);
sessionFactory.setPlugins(new Interceptor[]{pageHelper});
sessionFactory.setDataSource(jpaProxyDataSource());
return sessionFactory.getObject();
}
@Bean
public FilePool filePool() {
return new FilePool(env.getProperty("filepool.path"));
}
}
|
/*
* @(#) IFileInfoService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.fileinfo.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.esum.appframework.service.IBaseService;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2008/07/31 01:49:44 $
*/
public interface IFileInfoService extends IBaseService {
Object insert(Object object);
Object update(Object object);
Object delete(Object object);
Object fileInfoDetail(Object object);
Object fileInfoPageList(Object object);
void saveFileInfoExcel(Object object,
HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
|
package com.birivarmi.birivarmiapp.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="BV_CITY_AREA")
@DiscriminatorValue("BV_CITY_AREA")
public class CityArea extends BirivarmiItem{
@ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST})
@JoinColumn(name="CITY_ID", insertable=true, updatable=true, nullable=false)
private City city;
@Column(name="NAME", length=255, nullable=false)
private String name;
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.gsccs.sme.test;
import java.util.Date;
import java.util.List;
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 com.gsccs.sme.api.domain.Sneed;
import com.gsccs.sme.api.domain.base.Dict;
import com.gsccs.sme.api.service.AreaServiceI;
import com.gsccs.sme.api.service.DictServiceI;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:dubbo-server-consumer.xml")
public class AreaServiceTest {
@Autowired
private AreaServiceI areaAPI;
@Test
public void list() {
String areastr = areaAPI.getAreaStr(620102008);
System.out.println("end ###############"+areastr);
}
}
|
package com.jalsalabs.ticklemyphonefull;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GMailSender extends Authenticator {
private String mailhost = "smtp.gmail.com";
private String password;
private Session session;
private String user;
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (this.type == null) {
return "application/octet-stream";
}
return this.type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", this.mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
props.put("mail.smtp.starttls.enable", "true");
this.session = Session.getDefaultInstance(props, this);
}
/* Access modifiers changed, original: protected */
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.user, this.password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients, String attach_filename) throws Exception {
try {
MimeMessage message = new MimeMessage(this.session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
MimeBodyPart body1 = new MimeBodyPart();
MimeBodyPart attachMent = new MimeBodyPart();
attachMent.setDataHandler(new DataHandler(new FileDataSource(new File(attach_filename))));
attachMent.setFileName(attach_filename);
attachMent.setDisposition("attachment");
Multipart multipart = new MimeMultipart();
body1.setText(body);
multipart.addBodyPart(body1);
multipart.addBodyPart(attachMent);
message.setContent(multipart);
if (recipients.indexOf(44) > 0) {
message.setRecipients(RecipientType.TO, InternetAddress.parse(recipients));
} else {
message.setRecipient(RecipientType.TO, new InternetAddress(recipients));
}
Transport.send(message);
} catch (Exception e) {
TML_Library.Debug("ERROR1****************" + e);
}
return;
}
}
|
package de.fusion.deluxeenchantments.config;
import java.util.List;
public interface ConfigReader {
boolean contains();
int getInt();
boolean getBoolean();
String getString();
List<?> getList();
Object getObject();
}
|
package com.oa.role.service;
import java.util.List;
import com.oa.page.form.Page;
import com.oa.role.form.RoleInfo;
public interface RoleInfoService {
public void addRoleInfo(RoleInfo roleInfo);
public List<RoleInfo> selectAllRoleInfo();
public List<RoleInfo> selectRoleInfoByPage(final Page<RoleInfo> page);
public RoleInfo selectRoleInfoByName(String roleName);
public RoleInfo selectRoleInfoById(int roleId);
public void updateRoleInfo(RoleInfo roleInfo);
public void deleteRoleInfo(Integer roleId);
}
|
package com.desarollounder.undermetal;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class AdapterLocalAll extends RecyclerView.Adapter<AdapterLocalAll.LocalViewHolder> {
ArrayList<clsLocal> locales;
private Context context;
private Activity activity;
public static class LocalViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView localNombre, latLocal, lonLocal, localId, localDir;
ImageView eventoImg;
LocalViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.card_view);
localNombre = (TextView)itemView.findViewById(R.id.local_nombre);
localDir = (TextView)itemView.findViewById(R.id.local_dir);
localId = (TextView)itemView.findViewById(R.id.local_id);
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intent intent = new Intent(v.getContext(),ActivityLocalDetalle.class)
.putExtra("IdLocal",localId.getText());
v.getContext().startActivity(intent);
}
});
}
}
AdapterLocalAll(Context context, ArrayList<clsLocal> locales){
this.context = context;
this.locales = locales;
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public LocalViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_local_all, viewGroup, false);
LocalViewHolder nvh = new LocalViewHolder(v);
return nvh;
}
@Override
public void onBindViewHolder(LocalViewHolder localViewHolder, int i) {
localViewHolder.localNombre.setText(locales.get(i).getNombreLocal());
localViewHolder.localDir.setText(locales.get(i).getDirLocal());
localViewHolder.localId.setText(String.valueOf(locales.get(i).getIdLocal()));
}
@Override
public int getItemCount() {
return locales.size();
}
}
|
package com.example.apprunner.User.menu2_profile_event.Adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.apprunner.R;
import com.example.apprunner.ResultQuery;
import com.example.apprunner.User.menu2_profile_event.Activity.ShowDistanceEventActivity;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MenuEventUserAdapter extends RecyclerView.Adapter<MenuEventUserAdapter.Holder> {
List<ResultQuery> eventList;
Context context;
public MenuEventUserAdapter(Context context,List<ResultQuery> eventList) {
this.context = context;
this.eventList = eventList;
}
@NonNull
@Override
public MenuEventUserAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_user_view_statistics,parent,false);
return new MenuEventUserAdapter.Holder(view);
}
@Override
public void onBindViewHolder(@NonNull MenuEventUserAdapter.Holder holder, int position) {
final ResultQuery event = eventList.get(position);
final Intent intent = ((Activity) context).getIntent();
final String type = intent.getExtras().getString("type");
final String first_name = intent.getExtras().getString("first_name");
final String last_name = intent.getExtras().getString("last_name");
final int id_user = intent.getExtras().getInt("id_user");
Picasso.with(context).load(event.getPic_event()).into(holder.iv_image);
holder.tv_event_name_menu_event_user.setText(event.getName_event());
holder.tv_producer_name_menu_event_user.setText(event.getName_producer());
holder.btn_statics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent (context, ShowDistanceEventActivity.class);
intent.putExtra("id_add", event.get_eventID());
intent.putExtra("first_name",first_name);
intent.putExtra("last_name", last_name);
intent.putExtra("type", type);
intent.putExtra("id_user", id_user);
intent.putExtra("name_event", event.getName_event());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return eventList.size();
}
public class Holder extends RecyclerView.ViewHolder {
ImageView iv_image;
TextView tv_event_name_menu_event_user,tv_producer_name_menu_event_user;
Button btn_statics;
public Holder(@NonNull View itemView) {
super(itemView);
iv_image = (ImageView)itemView.findViewById(R.id.iv_image);
tv_event_name_menu_event_user = (TextView)itemView.findViewById(R.id.tv_event_name_menu_event_user);
tv_producer_name_menu_event_user = (TextView)itemView.findViewById(R.id.tv_producer_name_menu_event_user);
btn_statics = (Button)itemView.findViewById(R.id.btn_statics);
}
}
}
|
package com.prep.glossary;
public class MethodOverriding {
public int sum(int a,int b){
return a+b;
}
public float sum(float a,float b){
return a+b;
}
}
|
package com.fbse.recommentmobilesystem.XZHL0730;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.fbse.recommentmobilesystem.R;
public class XZHL0730_Adapter extends BaseAdapter{
LayoutInflater inflater;
List<XZHL0730_Bean> list;
public XZHL0730_Adapter(Context context,List<XZHL0730_Bean> list,ListView listView){
this.inflater=LayoutInflater.from(context);
this.list=list;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public XZHL0730_Bean getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder holder=null;
if(convertView==null){
holder=new ViewHolder();
convertView=inflater.inflate(R.layout.xzhl0710_listitem,null);
holder.tv1=(TextView)convertView.findViewById(R.id.xiaoshouId);
holder.tv2=(TextView)convertView.findViewById(R.id.shangpinName);
holder.tv3=(TextView)convertView.findViewById(R.id.shangpinId);
holder.tv4=(TextView)convertView.findViewById(R.id.guige);
holder.tv5=(TextView)convertView.findViewById(R.id.danjia);
holder.tv6=(TextView)convertView.findViewById(R.id.zongjine);
convertView.setTag(holder);
}else{
holder=(ViewHolder)convertView.getTag();
}
holder.tv1.setText(getItem(position).getXiaoshouId());
holder.tv2.setText(getItem(position).getShangpinName());
holder.tv3.setText(getItem(position).getShangpinId());
holder.tv4.setText(getItem(position).getGuige()+" -");
holder.tv5.setText("单价:"+getItem(position).getDanjia()+" * "+"数量:"+getItem(position).getShuliang()+" =");
holder.tv6.setText("总金额:"+getItem(position).getZongjine());
return convertView;
}
class ViewHolder{
TextView tv1;
TextView tv2;
TextView tv3;
TextView tv4;
TextView tv5;
TextView tv6;
}
}
|
package com.mpowa.android.powapos.apps.powatools.util;
/**
* Created by Powa on 5/28/15.
*/
public class HtmlFormatter {
String htmlPageInit;
String htmlPageEnd;
StringBuffer tableInit = new StringBuffer();
String tableEnd;
public HtmlFormatter(){
htmlPageInit = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" " +
"\"http://www.w3.org/TR/html4/strict.dtd\"> " +
"<HTML>" +
" <HEAD>" +
"<style>" +
"table, th, td {" +
"border: 1px solid black;" +
"border-collapse: collapse;" +
"background-color: #f1f1c1;" +
"}" +
"th, td {" +
" padding: 5px;" +
"}" +
"th {" +
" text-align: left;" +
"}" +
"</style>" +
" <TITLE>PowaPOS android report</TITLE>" +
" </HEAD>" +
" <BODY>";
htmlPageEnd = " </BODY>" +
"</HTML>";
tableInit.append("<table style=\"width:100%\">" +
" <tr>" +
" <th>Name</th>" +
" <th>Info</th>" +
" </tr>");
tableEnd = "</table>";
}
public void addLine(String line){
htmlPageInit = htmlPageInit + "<H4><p>"+ line +"</p></H4><br>";
}
public void addTableRow(String colName, String colInfo){
tableInit.append("<tr>" +
" <td>" + colName + "</td>" +
" <td>" + colInfo + "</td>" +
" </tr>");
}
public String getHtmlTable(){
tableInit.append(tableEnd);
return htmlPageInit + tableInit.toString() + htmlPageEnd;
}
public String getHtmlPage(){
return htmlPageInit + htmlPageEnd;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.