blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
cbf9e7983369f7f228fe5498ed3968e7c5f2f177
|
Java
|
mnitchev/MovieTheater
|
/100kina/src/main/java/stoKina/services/UserContext.java
|
UTF-8
| 437
| 2.15625
| 2
|
[] |
no_license
|
package stoKina.services;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import stoKina.model.User;
@SessionScoped
public class UserContext implements Serializable {
private static final long serialVersionUID = -5185469629320384569L;
private User currentUser;
public User getCurrentUser(){
return currentUser;
}
public void setCurrentUser(User newUser){
this.currentUser = newUser;
}
}
| true
|
87bc7e087a9df02460dfdfdb637deb71db06767f
|
Java
|
aaronhowser1/Document-Your-Mod-Mod
|
/src/main/java/com/aaronhowser1/dymm/api/configuration/ConfigurationManager.java
|
UTF-8
| 3,205
| 2.796875
| 3
|
[] |
no_license
|
package com.aaronhowser1.dymm.api.configuration;
import net.minecraftforge.common.config.Configuration;
import javax.annotation.Nonnull;
/**
* Handles the loading and the retrieval of the {@link Configuration} objects
* that the implementation or entries may specify.
*
* @since 2.0.0
*/
public interface ConfigurationManager {
/**
* Obtains a {@link Configuration} with the specified {@code name} and
* {@code version}.
*
* <p>The {@code Configuration} object is guaranteed to exist and to be
* saved and loaded as needed. The client shouldn't need to care about the
* internal mechanics of the saving and loading mechanism.</p>
*
* <p>Implementations are free to create configurations on-the-fly or cache
* them in case of performance concerns. By contract, though, every change
* made to the {@code Configuration} object must persist across restarts of
* the game.</p>
*
* @param name
* The name of the configuration to load: must be unique and
* non-{@code null}.
* @param version
* The version of the configuration to load: must not be {@code null}.
* Clients should use a version string that respects the specifics of
* Semantic Versioning, but no checks are performed in this regard
* by the implementation.
* @return
* A {@link Configuration} object that can be freely manipulated. The
* configuration object may have been created on-the-fly or loaded
* from disk. It is anyway guaranteed not to be {@code null} and to
* persist changes made to it.
*
* @since 2.0.0
*/
@Nonnull Configuration getVersionedConfigurationFor(@Nonnull final String name, @Nonnull final String version);
/**
* Obtains a {@link Configuration} with the specified {@code name}.
*
* <p>The {@code Configuration} object is guaranteed to exist and to be
* saved and loaded as needed. The client shouldn't need to care about the
* internal mechanics of the saving and loading mechanism.</p>
*
* <p>Implementations are free to create configurations on-the-fly or cache
* them in case of performance concerns. By contract, though, every change
* made to the {@code Configuration} object must persist across restarts of
* the game.</p>
*
* <p>Differently from
* {@link #getVersionedConfigurationFor(String, String)}, the returned
* configuration is version-agnostic. Nevertheless, implementations can
* use a versioned config file with a default version. Clients should not
* assume either behavior to occur.</p>
*
* @param name
* The name of the configuration to load: must be unique and
* non-{@code null}.
* @return
* A {@link Configuration} object that can be freely manipulated. The
* configuration object may have been created on-the-fly or loaded
* from disk. It is anyway guaranteed not to be {@code null} and to
* persist changes made to it.
*
* @since 2.0.0
*/
@Nonnull Configuration getConfigurationFor(@Nonnull final String name);
}
| true
|
f7689609ea754ac1384739e8389364d193c7b2cc
|
Java
|
meister4ever/quigon
|
/Engine/src/main/java/parser/SupportedAction.java
|
UTF-8
| 1,048
| 2.765625
| 3
|
[] |
no_license
|
package parser;
public class SupportedAction {
private int numberOfItemsAffected;
private String actionID;
public SupportedAction(int numberOfItemsAffected, String actionID) {
this.numberOfItemsAffected = numberOfItemsAffected;
this.actionID = actionID.toLowerCase();
}
public Boolean isEqual(String actionID) {
if (actionID.length() < this.actionID.length()) {
return false;
} else if (actionID.length() == this.actionID.length()) {
return this.actionID.equals(actionID) && this.numberOfItemsAffected == 0;
} else {
String itemsString = actionID.substring(this.actionID.length() + 1);
return (this.actionID.regionMatches(true, 0, actionID, 0, this.actionID.length())
&& itemsString.split(" ").length == this.numberOfItemsAffected);
}
}
public int getNumberOfItemsAffected() {
return this.numberOfItemsAffected;
}
public String getActionID() {
return this.actionID;
}
}
| true
|
79ea3f66654d4a43a24d440044ebf3a239faf27f
|
Java
|
alexbbb13/ABCDraw
|
/core/src/com/group/abcdraw/eventloops/outputevents/GlobalDraw.java
|
UTF-8
| 4,081
| 2.8125
| 3
|
[] |
no_license
|
package com.group.abcdraw.eventloops.outputevents;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.group.abcdraw.model.MainScreenModel;
import com.group.abcdraw.ui.shapes.CompleteCircle;
import com.group.abcdraw.ui.shapes.IncompleteCircle;
import com.group.abcdraw.ui.shapes.Line;
import com.group.abcdraw.ui.shapes.TouchCircle;
import java.util.List;
import sun.applet.Main;
/* A helper class for drawing shapes like Circles and Lines
Not really an event, but called each render cycle
Not added to events queue, but rather directly called from the GameScreen
The shape drawing must de done after the sprite drawing
*/
public class GlobalDraw {
public static void drawCircles(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer){
shapeRenderer.setProjectionMatrix(spriteBatch.getProjectionMatrix());
//draw all completed circles
shapeRenderer.setColor(25/255f, 142/255f, 174/255f, .8f);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
List<CompleteCircle> completeCircles = MainScreenModel.getInstance().getCompleteCircles();
for (int i = 0; i < completeCircles.size(); i++) {
shapeRenderer.circle(completeCircles.get(i).getX(), completeCircles.get(i).getY(), completeCircles.get(i).getRadius());
}
//draw touch circle
if (MainScreenModel.getInstance().getTouchCircle() != null) {
shapeRenderer.setColor(Color.ORANGE);
TouchCircle touchCircle = MainScreenModel.getInstance().getTouchCircle();
shapeRenderer.circle(touchCircle.getX(), touchCircle.getY(), touchCircle.getRadius());
}
shapeRenderer.end();
//draw next / inactive circle
if (MainScreenModel.getInstance().getIncompleteCircle() != null) {
shapeRenderer.setProjectionMatrix(spriteBatch.getProjectionMatrix());
shapeRenderer.setColor(Color.ORANGE);
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
IncompleteCircle incompleteCircle = MainScreenModel.getInstance().getIncompleteCircle();
shapeRenderer.circle(incompleteCircle.getX(), incompleteCircle.getY(), incompleteCircle.getRadius());
Gdx.gl.glLineWidth(7);
shapeRenderer.end();
}
}
public static void drawLines(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer){
shapeRenderer.setProjectionMatrix(spriteBatch.getProjectionMatrix());
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.setColor(218/255f, 165/255f, 32/255f, 1.0f);
for (Line l :MainScreenModel.getInstance().getLines()) {
shapeRenderer.line(l.getX1(), l.getY1(), l.getX2(), l.getY2());
}
//if touch isn't null draw from complete circle to finger
if(MainScreenModel.getInstance().getFinalCompleteCircle() == null || MainScreenModel.getInstance().getIncompleteCircle() == null)
{
Gdx.gl.glLineWidth(7);
shapeRenderer.end();
return;
}
if (MainScreenModel.getInstance().getTouchCircle() != null)
{
shapeRenderer.line(MainScreenModel.getInstance().getFinalCompleteCircle().getX(),
MainScreenModel.getInstance().getFinalCompleteCircle().getY(),
MainScreenModel.getInstance().getTouchCircle().getX(),
MainScreenModel.getInstance().getTouchCircle().getY());
}
//if touch is null draw line to last "checkpoint"
else
{
shapeRenderer.line(MainScreenModel.getInstance().getFinalCompleteCircle().getX(),
MainScreenModel.getInstance().getFinalCompleteCircle().getY(),
MainScreenModel.getInstance().getIncompleteCircle().getX(),
MainScreenModel.getInstance().getIncompleteCircle().getY());
}
Gdx.gl.glLineWidth(7);
shapeRenderer.end();
}
}
| true
|
431b9ffce11c4beaa08266f55b565066da92d641
|
Java
|
wenMN1994/BOS
|
/bos_parent/bos_dao/src/main/java/com/hafele/bos/dao/impl/FunctionDaoImpl.java
|
UTF-8
| 2,340
| 2.203125
| 2
|
[] |
no_license
|
package com.hafele.bos.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.hafele.bos.dao.IFunctionDao;
import com.hafele.bos.dao.base.impl.BaseDaoImpl;
import com.hafele.bos.domain.Function;
/**
* <p>Title: FunctionDaoImpl</p>
* <p>Description: 权限管理Dao接口实现</p>
* @author Dragon.Wen
* @date Aug 21, 2018
*/
@Repository
public class FunctionDaoImpl extends BaseDaoImpl<Function> implements IFunctionDao {
/**
* 重写父类的findAll方法
*/
@Override
public List<Function> findParentNodeAll() {
String hql = "FROM Function f WHERE f.parentFunction IS NULL";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql);
return list;
}
@Override
public List<Function> findFunctionListByUserId(String id) {
String hql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles"
+ " r LEFT OUTER JOIN r.users u WHERE u.id = ?";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql, id);
return list;
}
@Override
public List<Function> findAllMenu() {
String hql = "FROM Function f WHERE f.generatemenu = '1' AND type = '1' ORDER BY f.zindex ASC";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql);
return list;
}
@Override
public List<Function> findMenuByUserId(String id) {
String hql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles"
+ " r LEFT OUTER JOIN r.users u WHERE u.id = ? AND f.generatemenu = '1' "
+ "ORDER BY f.zindex DESC";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql, id);
return list;
}
@Override
public List<Function> findAllSystemMenu() {
String hql = "FROM Function f WHERE f.generatemenu = '1' AND type = '0' ORDER BY f.zindex ASC";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql);
return list;
}
@Override
public List<Function> findSystemMenuByUserId(String id) {
String hql = "SELECT DISTINCT f FROM Function f LEFT OUTER JOIN f.roles"
+ " r LEFT OUTER JOIN r.users u WHERE u.id = ? AND f.generatemenu = '1' AND f.type = '0' "
+ "ORDER BY f.zindex DESC";
List<Function> list = (List<Function>) this.getHibernateTemplate().find(hql, id);
return list;
}
}
| true
|
0af9a440b9be39e054302fdb9def8d4e052f1e41
|
Java
|
wllnon/SiRenXinYi
|
/app/src/main/java/com/test/wllnon/sirenxinyi/utils/network/GsonRequest.java
|
UTF-8
| 3,070
| 2.234375
| 2
|
[] |
no_license
|
package com.test.wllnon.sirenxinyi.utils.network;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;
/**
* Created by Administrator on 2016/4/19.
*/
public class GsonRequest<T> extends Request<T> {
private static final int TIME_OUT = 10000;
private final Response.Listener<T> mListener;
private static Gson mGson = GsonUtils.newInstance().getGson();
private Class<T> mClass;
private Map<String, String> mParams;
private Type mType;
public GsonRequest(int method, Map<String, String> params, String url, Class<T> clazz, Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
mClass = clazz;
mListener = listener;
mParams = params;
setMyRetryPolicy();
}
public GsonRequest(int method, Map<String, String> params, String url, Type type, Response.Listener<T> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
mType = type;
mListener = listener;
mParams = params;
setMyRetryPolicy();
}
private void setMyRetryPolicy() {
setRetryPolicy(new DefaultRetryPolicy(TIME_OUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public GsonRequest(String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Method.GET, null, url, clazz, listener, errorListener);
}
public GsonRequest(String url, Type type, Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Method.GET, null, url, type, listener, errorListener);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParams;
}
@SuppressWarnings("unchecked")
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
if (mType == null)
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
else
return (Response<T>) Response.success(mGson.fromJson(jsonString, mType),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
| true
|
92333008d497bff83995fa6cb918cc18e7f78ec6
|
Java
|
xMAGWAJx/JGBC2020
|
/src/test/java/lesson11/userserviceanduserrepository/UserServiceTest.java
|
UTF-8
| 654
| 2.296875
| 2
|
[] |
no_license
|
package lesson11.userserviceanduserrepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class UserServiceTest {
private UserService victim;
private MockUserRepository mockUserRepositoryDataBase;
@BeforeEach
public void setUp() {
this.mockUserRepositoryDataBase = new MockUserRepository();
this.victim = new UserService(mockUserRepositoryDataBase);
}
@Test
void addUser_ShouldReturnTrue() {
victim.addUser(new User("TestName", 20));
assertTrue(mockUserRepositoryDataBase.isMockTriggered);
}
}
| true
|
d62bd569f328a66bf3aafd4a77a5a66b30f16654
|
Java
|
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
|
/ast_results/dschuermann_faster-gps/libraries/RootCommands/src/main/java/org/sufficientlysecure/rootcommands/RootCommands.java
|
UTF-8
| 838
| 1.71875
| 2
|
[] |
no_license
|
// isComment
package org.sufficientlysecure.rootcommands;
import org.sufficientlysecure.rootcommands.util.Log;
public class isClassOrIsInterface {
public static boolean isVariable = true;
public static int isVariable = isIntegerConstant;
public static final String isVariable = "isStringConstant";
/**
* isComment
*/
public static boolean isMethod() {
boolean isVariable = true;
try {
Shell isVariable = isNameExpr.isMethod();
Toolbox isVariable = new Toolbox(isNameExpr);
if (isNameExpr.isMethod()) {
isNameExpr = true;
}
isNameExpr.isMethod();
} catch (Exception isParameter) {
isNameExpr.isMethod(isNameExpr, "isStringConstant", isNameExpr);
}
return isNameExpr;
}
}
| true
|
9ec0d989c402a16f45f4e600aec0487a2a7e2628
|
Java
|
augustoSiqueira/edumobi
|
/src/br/com/edu_mob/report/RelatorioDesempenhoSimulado.java
|
UTF-8
| 492
| 1.851563
| 2
|
[] |
no_license
|
package br.com.edu_mob.report;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import br.com.edu_mob.entity.infra.ResultadoSimuladoDTO;
public class RelatorioDesempenhoSimulado extends Relatorio {
public RelatorioDesempenhoSimulado(List<ResultadoSimuladoDTO> listaAlunos, @SuppressWarnings("rawtypes") Map parametros, InputStream caminho) {
super();
this.caminho = caminho;
this.lista = listaAlunos;
this.parametros = parametros;
}
}
| true
|
5804cd38bf1d21e22782e16be761b4f316118332
|
Java
|
brooklynphotos/photos
|
/src/main/java/photos/brooklyn/images/model/.svn/text-base/MerrillResponse.java.svn-base
|
UTF-8
| 767
| 1.9375
| 2
|
[
"MIT"
] |
permissive
|
package photos.brooklyn.images.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("d")
@JsonIgnoreProperties(ignoreUnknown=true)
public class MerrillResponse {
@JsonProperty("ActivityRows")
private List<Activity> activities;
private int totalPages;
public List<Activity> getActivities() {
return activities;
}
public void setActivities(List<Activity> activities) {
this.activities = activities;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
}
| true
|
9f2aa4dec4859a42af6d1a9d32665d7317abed76
|
Java
|
syed-ahamed04/ion-java
|
/src/com/amazon/ion/impl/bin/_Private_IonRawWriter.java
|
UTF-8
| 3,390
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazon.ion.impl.bin;
import com.amazon.ion.IonWriter;
import java.io.IOException;
/**
* An {@link IonWriter} with no symbol table management.
*
* @deprecated This is a private API subject to change without notice.
*/
@Deprecated
public interface _Private_IonRawWriter extends IonWriter
{
/**
* Sets the current field name to the given symbol ID. It is up to the
* caller to make sure the given symbol ID has a mapping in the current
* context's symbol table. The pending field name symbol is cleared when the
* current value is written via stepIn() or one of the write*() methods.
* @param sid - a symbol ID
*/
public void setFieldNameSymbol(int sid);
/**
* Sets the full list of pending annotations to the given symbol IDs. Any
* pending annotation symbol IDs are cleared. It is up to the caller to make
* sure the given symbol IDs have mappings in the current context's symbol
* table. The contents of the given array are copied into this writer, so
* the caller does not need to preserve the array. The list of pending
* annotation symbol IDs is cleared when the current value is written via
* stepIn() or one of the write*() methods.
* @param sids - symbol IDs representing the annotation symbols for the
* current value
*/
public void setTypeAnnotationSymbols(int... sids);
/**
* Adds the given symbol ID to the list of pending annotation symbol IDs. It
* is up to the caller to make sure the given symbol ID has a mapping in the
* current context's symbol table. The list of pending annotation symbol IDs
* is cleared when the current value is written via stepIn() or one of the
* write*() methods.
* @param sid - a symbol ID
*/
public void addTypeAnnotationSymbol(int sid);
/**
* Directly write the given symbol ID to represent a symbol value. It is up
* to the caller to make sure the given symbol ID has a mapping in the
* current context's symbol table.
* @param sid - a symbol ID
* @throws IOException
*/
public void writeSymbolToken(int sid) throws IOException;
/**
* Writes a portion of the byte array out as an IonString value. This
* copies the portion of the byte array that is written.
*
* @param data well-formed UTF-8-encoded bytes to be written.
* May be {@code null} to represent {@code null.string}.
* @param offset offset of the first byte in value to write
* @param length number of bytes to write from value
* @see IonWriter#writeClob(byte[], int, int)
* @see IonWriter#writeBlob(byte[], int, int)
*/
public void writeString(byte[] data, int offset, int length)
throws IOException;
}
| true
|
e9d89552809ffed8abd9dded4c9b838dce651f2f
|
Java
|
quocbao28/QTium
|
/src/Selenium-TestNG/Actions/ScrumBoard/InstallmentBuyingPage.java
|
UTF-8
| 2,277
| 2.21875
| 2
|
[] |
no_license
|
package ScrumBoard;
import static org.testng.Assert.assertTrue;
import com.logigear.selenium.QTiumAssert;
import com.logigear.selenium.QTiumAutomation;
public class InstallmentBuyingPage {
public static synchronized InstallmentBuyingPage getInstallmentBuyingPage()
{
if(instance == null)
instance = new InstallmentBuyingPage();
return instance;
}
private static InstallmentBuyingPage instance = null;
public void selectInstallmentBuyingMethod(String installmentMethod) {
if(installmentMethod == "HOME")
QTiumAutomation.click(InstallmentBuyingPageEntity.HOME_CREDIT_BUTTON);
else
QTiumAutomation.click(InstallmentBuyingPageEntity.FE_CREDIT_BUTTON);
}
public void fillInformationInstallmentBuying(String clientName, String clientPhone, String clientId, String clientBirthDay, String clientBirthMonth,
String clientBirthYear, int clientCity, int clientDistrict, String clientAddress, String clientGuarantorPhone) {
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_NAME_TEXTBOX, clientName);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_PHONE_NUMBER_TEXTBOX, clientPhone);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_ID_TEXTBOX, clientId);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_BIRTH_DAY_TEXTBOX, clientBirthDay);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_BIRTH_MONTH_TEXTBOX, clientBirthMonth);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_BIRTH_YEAR_TEXTBOX, clientBirthYear);
QTiumAutomation.selectByIndex(InstallmentBuyingPageEntity.CLIENT_CITY_DROPDOWN, clientCity);
QTiumAutomation.selectByIndex(InstallmentBuyingPageEntity.CLIENT_DICSTRICT_DROPDOWN, clientDistrict);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_ADDRESS_TEXTBOX, clientAddress);
QTiumAutomation.enter(InstallmentBuyingPageEntity.CLIENT_GUARANTOR_PHONE_NUMBER_TEXTBOX, clientGuarantorPhone);
QTiumAutomation.scrollPageToElement(InstallmentBuyingPageEntity.ADD_ORDER_BUTTON);
QTiumAutomation.click(InstallmentBuyingPageEntity.ADD_ORDER_BUTTON);
}
public void checkInstallmentBuyingResult() {
boolean isPagedisplayed = QTiumAutomation.isElementDisplayed(OrderResultPageEntity.SUCCESSFULLY_ORDER_LABEL);
QTiumAssert.verifyTrue(isPagedisplayed);
}
}
| true
|
abb6fc75c581ae826ef828d7f4fd60132d3e258f
|
Java
|
rami-alkhooli/Asteroids_Game_SS20
|
/AsteroidsGame/LevelFifth.java
|
UTF-8
| 735
| 2.78125
| 3
|
[] |
no_license
|
import processing.core.*;
public class LevelFifth implements Level
{
/**
* This method is used to determine the speed of the flying asteroids in the fifth level.
*
* @returns the speed of the flying asteroids in the fifth level.
**/
public int determineSpeed() {return 4;}
/**
* This method is used to determine the amount of the asteroids to generate in the fifth level.
*
* @returns the amount of the generated asteroids in the fifth level.
**/
public int determineAmount() {return 7;}
/**
* This method is used to determine the number of items to generate in the fifth level.
*
* @returns the number of the items generated in the fifth level.
**/
public int determineItems() {return 7;}
}
| true
|
e87147e6f956a00c6a63ed8c4a5f628b28f76f5c
|
Java
|
husniddinprogrammer/TezTop
|
/src/main/java/Husniddin/repository/XabarTuriRepo.java
|
UTF-8
| 337
| 1.890625
| 2
|
[] |
no_license
|
package Husniddin.repository;
import Husniddin.entity.XabarTuri;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface XabarTuriRepo extends JpaRepository<XabarTuri,Long> {
public List<XabarTuri> findAllByOrderById();
}
| true
|
cca136de2b52cb8e2607ed94f86e1406ea0f9301
|
Java
|
Bhargavadeepu/TshirtWholesalers
|
/app/src/main/java/com/akuna/Tshirtwholesalers/Tshirtwholesalers/UserScreens/ProgrssbarActivity.java
|
UTF-8
| 777
| 1.914063
| 2
|
[] |
no_license
|
package com.akuna.Tshirtwholesalers.Tshirtwholesalers.UserScreens;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import com.akuna.Tshirtwholesalers.Tshirtwholesalers.R;
public class ProgrssbarActivity extends AppCompatActivity {
public static ProgrssbarActivity instance = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progrssbar);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
/* getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);*/
instance = this;
}
}
| true
|
5f5ad4d3b5b34232f88ccce99c4f79720e343816
|
Java
|
jaepgh/Princenton_Algorithms_1
|
/01.WEEK_1/ASSIGNMENT/percolator/PercolationStats.java
|
UTF-8
| 2,444
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
/*
* 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.
*/
/**
*
* @author jaep2
*/
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.StdOut;
public class PercolationStats {
private static final double MULTIPLIER = 1.96;
private final double stdDeviation;
private final double mean;
private final int experiments;
public PercolationStats(int n, int trials) // perform trials independent experiments on an n-by-n grid
{
if (n <= 0 || trials <= 0) {
throw new IllegalArgumentException("Incorrect arguments");
}
this.experiments = trials;
final double[] results = new double[experiments];
for (int i = 0; i < this.experiments; i++) {
Percolation percolator = new Percolation(n);
while (!percolator.percolates()) {
int randomX = StdRandom.uniform(1, n + 1);
int randomY = StdRandom.uniform(1, n + 1);
percolator.open(randomX, randomY);
}
results[i] = percolator.numberOfOpenSites() / Math.pow(n, 2);
}
stdDeviation = StdStats.stddev(results);
mean = StdStats.mean(results);
}
public double mean() // sample mean of percolation threshold
{
return this.mean;
}
public double stddev() // sample standard deviation of percolation threshold
{
return this.stdDeviation;
}
public double confidenceLo() // low endpoint of 95% confidence interval
{
return this.mean() - MULTIPLIER * stddev()
/ Math.sqrt(this.experiments);
}
public double confidenceHi() // high endpoint of 95% confidence interval
{
return this.mean() + MULTIPLIER * stddev()
/ Math.sqrt(this.experiments);
}
public static void main(String[] args) {
PercolationStats tester = new PercolationStats(
Integer.parseInt(args[0]), Integer.parseInt(args[1]));
tester.output();
}
private void output() {
StdOut.printf("mean\t\t\t= %f\n"
+ "stddev\t\t\t= %f\n"
+ "95%% confidence interval\t= %f, %f\n",
this.mean(), stddev(),
confidenceLo(), confidenceHi());
}
}
| true
|
82e21d3443233fadf8e03c193ba9010ecb87b614
|
Java
|
Boombarm/onlinejudge
|
/Java/URI_BEECROWD/GRAPH/P2854_Family_Tree.java
|
UTF-8
| 3,216
| 3.1875
| 3
|
[] |
no_license
|
package URI.Accepted.GRAPH.sourcecode;
/**
* @author Teerapat Phokhonwong
* @Onlinejudge: URI ONLINE JUDGE
* @Categories: GRAPH
* @Problem: 2854 - Family Tree
* @Link: https://www.urionlinejudge.com.br/judge/en/problems/view/2854
* @Timelimit: 1 sec
* @Status: Accepted
* @Memory:
* @Submission: 2/25/19, 5:37:32 PM
* @Runtime: 0.100s
* @Solution: unionSet
* @Note:
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class P2854_Family_Tree {
static int m, n;
static int[] p;
private static class Node {
int id;
String name;
LinkedList<Node> relation;
public Node(int id, String name) {
this.id = id;
this.name = name;
this.relation = new LinkedList<>();
}
void addRelation(Node node) {
this.relation.add(node);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] st = br.readLine().split(" ");
m = Integer.parseInt(st[0]);
n = Integer.parseInt(st[1]);
HashMap<String, Node> Human = new HashMap();
int humanId = 1;
for (int i = 0; i < n; i++) {
st = br.readLine().split(" ");
String nameA = st[0];
String relation = st[1];
String nameB = st[2];
Node humanA = Human.get(nameA);
Node humanB = Human.get(nameB);
if (humanA == null) {
humanA = new Node(humanId, nameA);
Human.put(nameA, humanA);
humanId++;
}
if (humanB == null) {
humanB = new Node(humanId, nameB);
Human.put(nameB, humanB);
humanId++;
}
humanA.addRelation(humanB);
humanB.addRelation(humanA);
}
boolean[] v = new boolean[m + 1];
p = new int[m + 1];
for (int i = 1; i <= m; i++) {
p[i] = i;
}
for (Map.Entry<String, Node> entry : Human.entrySet()) {
Node cur = entry.getValue();
LinkedList<Node> Q = new LinkedList<>();
if (v[cur.id]) continue;
Q.add(cur);
v[cur.id] = true;
while (!Q.isEmpty()) {
Node node = Q.poll();
int setA = findFamily(node.id);
for (Node curLink : node.relation) {
if (v[curLink.id]) continue;
v[curLink.id] = true;
int setB = findFamily(curLink.id);
unionSet(setA, setB);
Q.add(curLink);
}
}
}
int totalFamily = 0;
for (int i = 1; i <= m; i++) {
if (p[i] == i) totalFamily++;
}
System.out.println(totalFamily);
}
static int findFamily(int pId) {
if (p[pId] == pId) return pId;
return findFamily(p[pId]);
}
static void unionSet(int s, int t) {
p[t] = s;
}
}
| true
|
7cac006899b30bbc83fb3b35e16e98e782078e55
|
Java
|
Ganeshj09/MyFolder
|
/abstraction/EletricGuitar.java
|
UTF-8
| 514
| 2.984375
| 3
|
[] |
no_license
|
package com.demo.abstraction;
public class EletricGuitar extends StringInstrument{
public EletricGuitar() {
super();
this.name = "Guitar" ;
this.numberofstrings = 6;
}
public EletricGuitar (int numberofstrings) {
super();
this.name = "Guitar" ;
this.numberofstrings = numberofstrings ;
}
public void play ()
{
System.out.println("An electric" + numberofstrings + "-string" + name + "is rocking");
}
@Override
public void playfootball() {
// TODO Auto-generated method stub
}
}
| true
|
02fdd69d5275262d813be2e21b7c2bfe269f2559
|
Java
|
Pragadesh/march
|
/src/main/java/org/pg/march/lc/string/BraceExpansion.java
|
UTF-8
| 2,224
| 3.390625
| 3
|
[] |
no_license
|
package org.pg.march.lc.string;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/*
* https://leetcode.com/problems/brace-expansion/
*/
public class BraceExpansion {
// public String[] expand(String S) {
// char[] chArr = S.toCharArray();
// List<String> res = expand(chArr, 0, chArr.length - 1);
// String[] resArr = new String[res.size()];
// return res.toArray(resArr);
// }
public List<String> braceExpansionII(String expression) {
char[] chArr = expression.toCharArray();
Set<String> res = expand(chArr, 0, chArr.length - 1);
List<String> ans = new ArrayList<>(res);
Collections.sort(ans);
return ans;
}
public Set<String> expand(char[] chArr, int start, int end) {
if(start > end) return new HashSet<>();
Set<String> res = new HashSet<>();
Deque<Set<String>> deque = new LinkedList<>();
deque.offer(new HashSet<>(Arrays.asList("")));
char operation = '*';
for (int i = start; i <= end; i++) {
char ch = chArr[i];
if (ch == '{') {
int j = i + 1, p = 1;
while (chArr[j] != '}' || p > 1) {
if (chArr[j] == '{') {
p++;
} else if (chArr[j] == '}') {
p--;
}
j++;
}
Set<String> nestedWords = expand(chArr, i+1, j-1);
i = j;
if(operation == '*') {
deque.offer(merge(deque.pollLast(), nestedWords));
}else {
operation = '*';
deque.offer(nestedWords);
}
} else if(Character.isAlphabetic(ch)) {
Set<String> set = new HashSet<>(Arrays.asList(Character.toString(ch)));
if(operation == '*') {
deque.offer(merge(deque.pollLast(), set));
}else {
operation = '*';
deque.offer(set);
}
}
// if (ch == ',' || i == chArr.length - 1) {
if (ch == ',') {
operation = ',';
}
}
while(!deque.isEmpty()) {
res.addAll(deque.pollLast());
}
return res;
}
private Set<String> merge(Set<String> list1, Set<String> list2) {
Set<String> res = new HashSet<>();
for(String str1 : list1) {
for(String str2 : list2) {
res.add(str1 + str2);
}
}
return res;
}
}
| true
|
aa3a1f30143eaa12d0456498a02b613a4de64064
|
Java
|
DongMing0103/RMc
|
/kzscrm-util/src/main/java/com/hd/kzscrm/common/enums/ResponseCode.java
|
UTF-8
| 1,147
| 2.640625
| 3
|
[] |
no_license
|
package com.hd.kzscrm.common.enums;
public enum ResponseCode {
// 关联类型,0未明确,1主账户,2子账户
EXCEPTION("0", "未明确"),
CANTEEN("1", "商户后台"), QY_MGR("2", "企业管理后台"), ADMIN_MGR("3", "系统平台"), ILLEGAL_ARG ("4", "ERROR"), SUCCESS ("5", "SUCCESS");
/**
* 枚举code
*/
private String code;
/**
* 枚举value
*/
private String value;
/**
* 构造函数
*
* @param code
* @param value
*/
private ResponseCode(String code, String value) {
this.code = code;
this.value = value;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
/**
* 通过枚举<code>code</code>获得枚举。
*
* @param code
* 权限值
* @return testEnum 权限值枚举
*/
public static String getValueByCode(String code) {
for (UserTypeEnum userTypeEnum : UserTypeEnum.values()) {
if (code.equals(userTypeEnum.getCode())) {
return userTypeEnum.getValue();
}
}
return null;
}
}
| true
|
9d1eea8171fa6f2d60b4ab5b8b3713f762298259
|
Java
|
danieltistoj/ProyectoBD
|
/src/Clases/Modulo.java
|
UTF-8
| 8,728
| 2.28125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Clases;
import Clases.ConexionMySQL;
import Clases.Bitacoratxt;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Usuario
*/
public class Modulo {
private JTable tabla;
private Bitacoratxt escribir;
private DefaultTableModel modelo;
private JLabel labelNum, labelFecha;
// private ConexionMySQL conexion;
public VariableGlobal conexion;
/*
private String localhost,puerto,baseDeDatos,
usuario,contra, codigo;
*/
private String[] datosInsertar;
public Modulo() {
conexion = new VariableGlobal();
escribir = new Bitacoratxt();
}
public Modulo(boolean sinBase) {
conexion = new VariableGlobal("");
escribir = new Bitacoratxt();
}
public String generarCodigo(String formaParametro, String tabla, String letra) {
int entero;
String numero = "";
String ultimoNum = "";
String nuevoCodigo = "";
try {
conexion.conexionMySQL.EjecutarConsulta("SELECT MAX(" + formaParametro + ") FROM " + tabla);
ResultSet rs = conexion.conexionMySQL.getResulSet();
if (rs.next()) {
ultimoNum = rs.getString(1);
}
if (ultimoNum == null) {
nuevoCodigo = letra + "0001";
} else {
char r1 = ultimoNum.charAt(2);
char r2 = ultimoNum.charAt(3);
char r3 = ultimoNum.charAt(4);
char r4 = ultimoNum.charAt(5);
String cadena = "";
cadena = "" + r1 + r2 + r3 + r4;
entero = Integer.parseInt(cadena);
Codigo codigo = new Codigo();
codigo.generarCodigo(entero);
nuevoCodigo = letra + codigo.getCodigo();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return nuevoCodigo;
}
public String fecha() {
LocalDate fecha1 = LocalDate.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return fecha1.format(dtf);
}
public boolean esEntero(String id) {
boolean entero = false;
try {
Integer.parseInt(id);
entero = true;
} catch (Exception e) {
}
return entero;
}
public boolean esFlotante(String abono) {
boolean entero = false;
try {
Float.parseFloat(abono);
entero = true;
} catch (Exception e) {
}
return entero;
}
public boolean existeRegistro(String parametro, String tabla, String formaParametro) {
boolean existe = false;
try {
conexion.conexionMySQL.EjecutarConsulta("SELECT COUNT(*) FROM " + tabla + " WHERE " + formaParametro + " = " + parametro + "");
ResultSet rs = conexion.conexionMySQL.getResulSet();
rs.next();
if (rs.getInt(1) > 0) {
existe = true;
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return existe;
}
public int cantidadDeRegistros(String formaId, String tabla) {
int numid = 0;
try {
conexion.conexionMySQL.EjecutarConsulta("select count(" + formaId + ")num from " + tabla);
ResultSet rs = conexion.conexionMySQL.getResulSet();
while (rs.next()) {
numid = Integer.parseInt(rs.getString("num"));
}
} catch (SQLException ex) {
Logger.getLogger(Modulo.class.getName()).log(Level.SEVERE, null, ex);
}
return numid;
}
public void nuevoRegistro(String colummnas, String parametro, String tabla) {//insertar un registro en cualquier tabla
conexion.conexionMySQL.EjecutarInstruccion("insert into " + tabla + " (" + colummnas + ")\n"
+ "values(" + parametro + ")");
}
public void modificarRegistro(String tabla, String datosModificar, String formaId, String id) {
conexion.conexionMySQL.EjecutarInstruccion("UPDATE " + tabla + " SET " + datosModificar + " WHERE " + formaId + " = " + id);
}
public String getDato(String formaId, String id, String tabla, String parametro) {
String dato = "";
conexion.conexionMySQL.EjecutarConsulta("SELECT * FROM " + tabla + " WHERE " + formaId + " = " + id);
ResultSet rs = conexion.conexionMySQL.getResulSet();
try {
while (rs.next()) {
dato = rs.getString(parametro);
}
} catch (SQLException ex) {
Logger.getLogger(Modulo.class.getName()).log(Level.SEVERE, null, ex);
}
return dato;
}
public void eliminarRegistro(String idRegistro, String tabla, String formaId) {
conexion.conexionMySQL.EjecutarInstruccion("DELETE FROM " + tabla + " WHERE " + formaId + " = " + idRegistro);
}
public String getUltimoId(String formaId, String tabla) {
String id = "";
try {
conexion.conexionMySQL.EjecutarConsulta("SELECT MAX(" + formaId + ")As ultimo FROM " + tabla);
ResultSet rs = conexion.conexionMySQL.getResulSet();
while (rs.next()) {
id = rs.getString("ultimo");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return id;
}
public boolean existeEnTabla(String id, JTable tabla, int columna) {
boolean existe = false;
int iD;
iD = Integer.parseInt(id);
for (int i = 0; i < tabla.getRowCount(); i++) {
if (iD == Integer.parseInt(String.valueOf(tabla.getValueAt(i, columna)))) {
existe = true;
}
}
return existe;
}
public void limpiarTabla(DefaultTableModel modelo, JTable tabla) {
int fila = tabla.getRowCount();
for (int i = fila - 1; i >= 0; i--) {
modelo.removeRow(i);
}
}
//Verifica que la base de datos que esta en el fichero es existe en el gestor de base de datos
public boolean existeLaBase(){
boolean existe = false;
try {
String baseDatos = "";
Fichero fichero = new Fichero();
baseDatos = fichero.obterBase();
conexion.conexionMySQL.EjecutarConsulta("show databases");
ResultSet rs = conexion.conexionMySQL.getResulSet();
while(rs.next()){
if(baseDatos.equals(rs.getString("Database"))){
existe = true;
}
}
} catch (SQLException ex) {
Logger.getLogger(Modulo.class.getName()).log(Level.SEVERE, null, ex);
}
return existe;
}
public boolean existeLaBase(String nombreBase){
boolean existe = false;
try {
conexion.conexionMySQL.EjecutarConsulta("show databases");
ResultSet rs = conexion.conexionMySQL.getResulSet();
while(rs.next()){
if(nombreBase.equals(rs.getString("Database"))){
existe = true;
}
}
} catch (SQLException ex) {
Logger.getLogger(Modulo.class.getName()).log(Level.SEVERE, null, ex);
}
return existe;
}
public void insertarEnTabla(String[] datos, DefaultTableModel modelo) {
this.modelo = modelo;
this.modelo.addRow(datos);
}
public void quitarFila(int fila, DefaultTableModel modelo) {
modelo.removeRow(fila);
}
public JTable getTabla() {
return tabla;
}
public void setTabla(JTable tabla) {
this.tabla = tabla;
}
public DefaultTableModel getModelo() {
return modelo;
}
public void setModelo(DefaultTableModel modelo) {
this.modelo = modelo;
}
public JLabel getLabelNum() {
return labelNum;
}
public void setLabelNum(JLabel labelNum) {
this.labelNum = labelNum;
}
public JLabel getLabelFecha() {
return labelFecha;
}
public void setLabelFecha(JLabel labelFecha) {
this.labelFecha = labelFecha;
}
}
| true
|
73b155f4989c43064a246fd4356e2e6f6878758e
|
Java
|
Siwoo-Kim/siwoo-blog
|
/src/test/java/com/siwoo/springblog/domain/TestBasicDate.java
|
UTF-8
| 1,180
| 2.78125
| 3
|
[] |
no_license
|
package com.siwoo.springblog.domain;
import org.junit.Test;
import java.time.LocalDate;
import java.time.Period;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
/**
* @author SiWoo Kim,
* @version 1.0.0
* @email sm123tt@gmail.com
* @github : https://github.com/Siwoo-Kim
* @since 2018-05-10 오후 4:03
**/
public class TestBasicDate {
@Test
public void daysAgo() {
LocalDate created = LocalDate.of(2018, 5, 8);
LocalDate upadted = LocalDate.of(2018, 5, 9);
BasicDate basicDate = new BasicDate(created, upadted);
Period period = Period.between(upadted, LocalDate.now());
assertEquals(basicDate.daysAgo(), period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days ago");
basicDate = new BasicDate(created, null);
period = Period.between(created, LocalDate.now());
assertEquals(basicDate.daysAgo(), period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days ago");
basicDate = new BasicDate(null, null);
assertEquals(basicDate.daysAgo(), "Time not saved");
}
}
| true
|
1a4d72c41313bf959afaddb2bf0d2364cced9f72
|
Java
|
sivaprasadreddynooli/Java_Basics
|
/FirstPackage/UserInput.java
|
UTF-8
| 693
| 3.59375
| 4
|
[] |
no_license
|
//import java.util.*;
package FirstPackage;
import java.util.Scanner;
public class UserInput {
public static void main( String[] args)
{
Scanner s1 = new Scanner(System.in);
System.out.println("enter some number");
int user_input = s1.nextInt();
System.out.println("the entered numner is "+ user_input);
Scanner s2 = new Scanner(System.in);
System.out.println("enter some string");
String user_string = s2.nextLine();
System.out.println(user_string);
Scanner s3 = new Scanner(System.in);
System.out.println("enter a decmical number");
float user_float = s3.nextFloat();
System.out.println(user_float);
s1.close();
s2.close();
s3.close();
}
}
| true
|
596a6ee0ee719a7cfae5bf93c4ec7069f0a6f15c
|
Java
|
OleksandrYemolenko/FastOrde
|
/app/src/main/java/com/sashaermolenko/fastorder/Login/PassActivity.java
|
UTF-8
| 3,737
| 2.203125
| 2
|
[] |
no_license
|
package com.sashaermolenko.fastorder.Login;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.sashaermolenko.fastorder.Handler;
import com.sashaermolenko.fastorder.MainActivity;
import com.sashaermolenko.fastorder.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static com.sashaermolenko.fastorder.MainActivity.STORAGE_NAME;
public class PassActivity extends AppCompatActivity {
private String title;
private Button btn;
private Intent intent;
public static String phone = "+380676988515", firstname = "Oleg", secondname = "Fomenko";
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_pass);
title = "Authentication";
setTitle(title);
btn = (Button) findViewById(R.id.btn_pass);
context = this;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sp = context.getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("isLogined", true);
editor.putString("phone", phone);
editor.commit();
new AsyncRequest().execute();
intent = new Intent(PassActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
class AsyncRequest extends AsyncTask<Void, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Void... voids) {
String content = Handler.sendRequest(Handler.createLink("clients.getGroups"), "GET");
System.out.println("CONTENT ====== " + content);
JSONObject obj = null;
try {
obj = new JSONObject(content);
JSONArray arr = obj.getJSONArray("response");
obj = arr.getJSONObject(0);
System.out.println(obj);
content = Handler.sendRequest(Handler.createLink("clients.createClient", "client_name=" + secondname, "phone=" + phone, "client_groups_id_client="+obj.get("client_groups_id"), "client_sex=0"), "post");
obj = new JSONObject(content);
} catch (JSONException e) {
System.out.println(e);
}
return obj;
}
@Override
protected void onPostExecute(JSONObject obj) {
SharedPreferences sp = context.getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
System.out.println(obj);
try {
editor.putString("id", obj.get("response").toString());
System.out.println(sp.getString("id", "Errrorrrr"));
} catch (JSONException e) {
editor.putString("id", "0");
e.printStackTrace();
}
editor.commit();
}
}
}
| true
|
b00bac989fbac288b7c7422e8e530e26f02705d8
|
Java
|
ct850230163/springboot-common
|
/src/main/java/cn/vpclub/demo/common/model/utils/web/FTPUtils.java
|
UTF-8
| 3,423
| 2.578125
| 3
|
[] |
no_license
|
package cn.vpclub.demo.common.model.utils.web;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by WeiPin on 2016/3/19.
*/
@Slf4j
public class FTPUtils {
protected FTPUtils() {
}
private static FTPClient ftp;
/**
* 获取ftp连接
*
* @param f
* @return
* @throws Exception
*/
public static boolean connectFtp(Ftp f) {
try {
ftp = new FTPClient();
boolean flag = false;
int reply;
if (f.getPort() == null) {
ftp.connect(f.getIpAddr(), 21);
} else {
ftp.connect(f.getIpAddr(), f.getPort());
}
ftp.login(f.getUserName(), f.getPwd());
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return flag;
}
ftp.changeWorkingDirectory(f.getPath());
flag = true;
return flag;
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
/**
* 关闭ftp连接
*/
public static void closeFtp() {
if (ftp != null && ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
} catch (IOException e) {
throw Exceptions.unchecked(e);
}
}
}
/**
* ftp上传文件
*
* @param
* @throws Exception
*/
public static void upload(Ftp f, byte[] byteData, String fileName) {
try {
InputStream input = byte2Input(byteData);
if (null != f.getPath() && !"".equals(f.getPath())) {
ftp.makeDirectory(f.getPath());
ftp.changeWorkingDirectory(f.getPath());
} else {
ftp.changeToParentDirectory();
}
ftp.storeFile(fileName, input);
input.close();
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
public static byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
/**
* 下载链接配置
*
* @param f
* @param remoteBaseDir 远程目录
* @throws Exception
*/
public static byte[] startDown(Ftp f, String remoteBaseDir) {
try {
if (FTPUtils.connectFtp(f)) {
InputStream inputStream = ftp.retrieveFileStream(remoteBaseDir);
return input2byte(inputStream);
} else {
log.error("链接失败!");
}
return new byte[0];
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
}
| true
|
39b1dce67b16f4a987318dd3f5f09850b146c0e6
|
Java
|
shuanger051/SiteDemo
|
/qwebsite-front/src/main/java/cn/qweb/cms/front/directive/IndexFloatingListDirective.java
|
UTF-8
| 2,051
| 2.078125
| 2
|
[] |
no_license
|
package cn.qweb.cms.front.directive;
import cn.qweb.cms.biz.service.IndexFloatingService;
import cn.qweb.cms.biz.service.dto.IndexFloatingDTO;
import cn.qweb.cms.biz.service.query.IndexFloatingQUERY;
import cn.qweb.cms.core.freemarker.BaseDirective;
import cn.qweb.cms.core.freemarker.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by xuebj on 2017/4/10.
*/
@Component("index_floating")
public class IndexFloatingListDirective extends BaseDirective implements TemplateDirectiveModel{
/**
* 位置
*/
private final String PARAM_POSITION = "position";
/**
* 是否显示
*/
private final String PARAM_IS_ENABLED = "isEnabled";
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
String position = DirectiveUtils.getString(PARAM_POSITION,params);
String isEnabled = DirectiveUtils.getString(PARAM_IS_ENABLED,params);
IndexFloatingQUERY queryBean = new IndexFloatingQUERY();
queryBean.setPage(1);
queryBean.setPageSize(100);
if(StringUtils.isBlank(isEnabled)){
isEnabled = "1"; //默认获取显示状态
}
queryBean.setIsEnabled(isEnabled);
List<IndexFloatingDTO> floatings;
if(StringUtils.isNotBlank(position)){
queryBean.setFloatingPosition(position);
}
floatings = indexFloatingService.list(queryBean).getData();
setListVar(floatings,env,params,body);
}
@Autowired
private IndexFloatingService indexFloatingService;
}
| true
|
da56fcfd238624a051ea78088e5b685d0f35af73
|
Java
|
AmaniAnane/spring-project
|
/gestion_livraison/src/main/java/com/example/demo/entities/Produit.java
|
UTF-8
| 1,196
| 2.1875
| 2
|
[] |
no_license
|
package com.example.demo.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Produit implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Long getReference() {
return reference;
}
public void setReference(Long reference) {
this.reference = reference;
}
public String getMarque() {
return marque;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setMarque(String marque) {
this.marque = marque;
}
public float getPrix() {
return prix;
}
public void setPrix(float prix) {
this.prix = prix;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id ;
private Long reference;
private String marque ;
private float prix ;
@OneToMany(mappedBy="Ps")
private Collection <livraisonproduit> livraisonproduit;
public Produit() {
super();
// TODO Auto-generated constructor stub
}
}
| true
|
9e04335139157df2a01ffaba694b81374bcab1a3
|
Java
|
YasCueLav/Tesis
|
/Proyecto/Tesis-Asistencias/src/java/Model/VMAsistenciaAlmunoJustificativo.java
|
UTF-8
| 1,692
| 2.390625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.sql.Date;
/**
*
* @author Yasmin
*/
public class VMAsistenciaAlmunoJustificativo {
int idAsistencias;
int legajo;
String nombre;
String apellido;
String texto;
Date fecha;
public VMAsistenciaAlmunoJustificativo() {
}
public VMAsistenciaAlmunoJustificativo(int idAsistencias, int legajo, String nombre, String apellido, String texto, Date fecha) {
this.idAsistencias = idAsistencias;
this.legajo = legajo;
this.nombre = nombre;
this.apellido = apellido;
this.texto = texto;
this.fecha = fecha;
}
public int getIdAsistencias() {
return idAsistencias;
}
public int getLegajo() {
return legajo;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public String getTexto() {
return texto;
}
public Date getFecha() {
return fecha;
}
public void setIdAsistencias(int idAsistencias) {
this.idAsistencias = idAsistencias;
}
public void setLegajo(int legajo) {
this.legajo = legajo;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public void setTexto(String texto) {
this.texto = texto;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
}
| true
|
f1f06ff5b70118ff022afb064eb828504ccaa5b2
|
Java
|
cgq199746/bdc-pro
|
/bdczyxt/admin/src/main/java/com/admin/dao/primary/PubUserLoginLogDao.java
|
UTF-8
| 606
| 1.765625
| 2
|
[] |
no_license
|
package com.admin.dao.primary;
import com.admin.controller.bdc.req.PubUserLoginLogReq;
import com.bdc.common.base.CrudDao;
import com.bdc.entity.primary.UserLoginLog;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ClassName 类名:AdminLogDao
* @Description 功能说明:后台日志dao
*/
@Mapper
@Repository
public interface PubUserLoginLogDao extends CrudDao<UserLoginLog> {
/**
* 查询日志
* @return
*/
List<UserLoginLog> findLogList(PubUserLoginLogReq logReq);
void deleteAll();
}
| true
|
ae57e2b13cb89b92da086071837cd70bccf24e16
|
Java
|
humbleitem/mathFunctionMaster
|
/MathematicalFunctionMaster/src/randomAlgorithm/RandomAlgorithm.java
|
UTF-8
| 2,952
| 2.703125
| 3
|
[] |
no_license
|
package randomAlgorithm;
import java.util.ArrayList;
import algorithm.Attribute;
import algorithm.Instance;
import algorithm.WeaponAlgorithm;
import computeValue.ComputeFactory;
import computeValue.ComputeValue;
import computeValue.FunctionComputeValue;
import geneticAlgorithm.ChromOneD;
public class RandomAlgorithm implements WeaponAlgorithm {
private RandomInstance randombest;
private Attribute AT;
private FunctionComputeValue FCV;
private ArrayList<RandomInstance> randomList;
private int populationNum;
private int terminateCondition;
private int TN;
private int numX;
private double startVariable;
private double endVariable;
public RandomAlgorithm(Attribute AT, int TN) {
this.AT = AT;
this.TN = TN;
ComputeFactory computeFactory = new ComputeFactory(AT);
FCV = computeFactory.getFunctionCompute();
numX = AT.getNumX();
startVariable = AT.getStartVariable();
endVariable = AT.getEndVariable();
randombest = new RandomInstance(numX);
randombest.setValue(Double.MAX_VALUE);
randomList = new ArrayList<RandomInstance>();
}
@Override
public void findAnswer() {
// TODO Auto-generated method stub
for (int i = 0; i <= terminateCondition; i++) {
if (AT.getExchangeNum() == 1) {
if (i % 100 == 0) {
System.out.println(randombest.getBestValue());
}
}
randomListUpdate();
compareBest();
}
// System.out.println(randombest.getBestValue());
}
@Override
public void setPopulation(ArrayList<Instance> population) {
randomList.clear();
for (Instance instance : population) {
RandomInstance randomInstance = new RandomInstance(numX);
randomInstance.setRandomPos(instance.getBestPos());
randomInstance.setValue(instance.getBestValue());
randomList.add(randomInstance);
}
compareBest();
}
@Override
public void setStopCondition(int time) {
terminateCondition = time;
}
@Override
public ArrayList<Instance> getPopulation() {
// TODO Auto-generated method stub
ArrayList<Instance> population = new ArrayList<Instance>();
for (RandomInstance random : randomList) {
population.add(random);
}
return population;
}
public void compareBest() {
for (RandomInstance random : randomList) {
if (random.getBestValue() < randombest.getBestValue()) {
randombest.setRandomPos(random.getBestPos());
randombest.setValue(random.getBestValue());
}
}
}
public void randomListUpdate() {
for (RandomInstance random : randomList) {
for (int i = 0; i < numX; i++) {
random.getBestPos()[i] = Math.random() * (endVariable - startVariable) - endVariable;
}
random.setValue(FCV.computeValue(random.getBestPos()));
}
}
@Override
public double getIndividualPos() {
return randombest.getBestPos()[TN];
}
@Override
public Instance getBestLocalAnswer() {
return randombest;
}
@Override
public void setGlobalBestParticle(Instance instance) {
// TODO Auto-generated method stub
}
}
| true
|
089c0af75416affaa57b97f31f3c2d3d905c3e1c
|
Java
|
skewcat/java-demo
|
/kafka-mongodb/src/main/java/com/asiainfo/breeze/consumer/ConsumerRunner.java
|
UTF-8
| 12,369
| 2.125
| 2
|
[] |
no_license
|
package com.asiainfo.breeze.consumer;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import com.asiainfo.breeze.conf.Configration;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.asiainfo.breeze.util.InstanceHolder;
import com.mongodb.MongoClient;
import com.mongodb.ReadConcern;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
/**
* breeze-consumer启动线程
*
* @author kelgon
*/
public class ConsumerRunner {
private static final Logger log = Logger.getLogger(ConsumerRunner.class);
/**
* 初始化MongoDB client
*/
private static boolean initMongo() {
try {
log.info("loading mongo.properties...");
//构造MongoDB集群serverList
String servers = Configration.MONGODB_PROPS.getProperty("mongo.servers");
if ("".equals(servers) || servers == null) {
log.error("mongo.servers must not be null or empty!");
return false;
}
List<ServerAddress> serverList = new ArrayList<>();
for (String s : servers.split(",")) {
String[] addr = s.split(":");
ServerAddress sa = new ServerAddress(addr[0], Integer.parseInt(addr[1]));
serverList.add(sa);
}
//构造MongoDB身份认证对象
String recordDbName = Configration.MONGODB_PROPS.getProperty("breeze.recordDbname");
if ("".equals(recordDbName) || recordDbName == null) {
log.error("record.dbname must not be null or empty!");
return false;
}
String recordCredentials = Configration.MONGODB_PROPS.getProperty("breeze.recordCredentials");
List<MongoCredential> mCreList = new ArrayList<>();
if (!"".equals(recordCredentials) && recordCredentials != null) {
String[] cre = recordCredentials.split(":");
MongoCredential credential = MongoCredential.createScramSha1Credential(cre[0], recordDbName, cre[1].toCharArray());
mCreList.add(credential);
}
//从配置文件加载MongoDB客户端参数
Builder options = new Builder();
if (Configration.MONGODB_PROPS.containsKey("mongo.connectionsPerHost"))
options.connectionsPerHost(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.connectionsPerHost")));
if (Configration.MONGODB_PROPS.containsKey("mongo.connectTimeout"))
options.connectTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.connectTimeout")));
if (Configration.MONGODB_PROPS.containsKey("mongo.heartbeatConnectTimeout"))
options.heartbeatConnectTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.heartbeatConnectTimeout")));
if (Configration.MONGODB_PROPS.containsKey("mongo.heartbeatFrequency"))
options.heartbeatFrequency(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.heartbeatFrequency")));
if (Configration.MONGODB_PROPS.containsKey("mongo.heartbeatSocketTimeout"))
options.heartbeatSocketTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.heartbeatSocketTimeout")));
if (Configration.MONGODB_PROPS.containsKey("mongo.maxConnectionIdleTime"))
options.connectTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.maxConnectionIdleTime")));
if (Configration.MONGODB_PROPS.containsKey("mongo.maxConnectionLifeTime"))
options.maxConnectionLifeTime(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.maxConnectionLifeTime")));
if (Configration.MONGODB_PROPS.containsKey("mongo.maxWaitTime"))
options.maxWaitTime(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.maxWaitTime")));
if (Configration.MONGODB_PROPS.containsKey("mongo.minConnectionsPerHost"))
options.minConnectionsPerHost(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.minConnectionsPerHost")));
if (Configration.MONGODB_PROPS.containsKey("mongo.minHeartbeatFrequency"))
options.minHeartbeatFrequency(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.minHeartbeatFrequency")));
if (Configration.MONGODB_PROPS.containsKey("mongo.readConcern")) {
String readConcern = Configration.MONGODB_PROPS.getProperty("mongo.readConcern");
if ("default".equalsIgnoreCase(readConcern))
options.readConcern(ReadConcern.DEFAULT);
if ("local".equalsIgnoreCase(readConcern))
options.readConcern(ReadConcern.LOCAL);
if ("majority".equalsIgnoreCase(readConcern))
options.readConcern(ReadConcern.MAJORITY);
}
if (Configration.MONGODB_PROPS.containsKey("mongo.readPreference")) {
String readPreference = Configration.MONGODB_PROPS.getProperty("mongo.readPreference");
if ("primary".equalsIgnoreCase(readPreference))
options.readPreference(ReadPreference.primary());
if ("primaryPreferred".equalsIgnoreCase(readPreference))
options.readPreference(ReadPreference.primaryPreferred());
if ("secondary".equalsIgnoreCase(readPreference))
options.readPreference(ReadPreference.secondary());
if ("secondaryPreferred".equalsIgnoreCase(readPreference))
options.readPreference(ReadPreference.secondaryPreferred());
if ("nearest".equalsIgnoreCase(readPreference))
options.readPreference(ReadPreference.nearest());
}
if (Configration.MONGODB_PROPS.containsKey("mongo.serverSelectionTimeout"))
options.serverSelectionTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.serverSelectionTimeout")));
if (Configration.MONGODB_PROPS.containsKey("mongo.socketTimeout"))
options.socketTimeout(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.socketTimeout")));
if (Configration.MONGODB_PROPS.containsKey("mongo.threadsAllowedToBlockForConnectionMultiplier"))
options.threadsAllowedToBlockForConnectionMultiplier(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier")));
if (Configration.MONGODB_PROPS.containsKey("mongo.writeConcern"))
options.writeConcern(new WriteConcern(Integer.parseInt(Configration.MONGODB_PROPS.getProperty("mongo.writeConcern"))));
if (Configration.MONGODB_PROPS.containsKey("mongo.socketKeepAlive"))
options.socketKeepAlive(Boolean.parseBoolean(Configration.MONGODB_PROPS.getProperty("mongo.socketKeepAlive")));
if (Configration.MONGODB_PROPS.containsKey("mongo.sslEnabled"))
options.sslEnabled(Boolean.parseBoolean(Configration.MONGODB_PROPS.getProperty("mongo.sslEnabled")));
if (Configration.MONGODB_PROPS.containsKey("mongo.sslInvalidHostNameAllowed"))
options.sslInvalidHostNameAllowed(Boolean.parseBoolean(Configration.MONGODB_PROPS.getProperty("mongo.sslInvalidHostNameAllowed")));
//initialize mongodb client
log.info("initializing mongodb client...");
if (mCreList.size() > 0)
InstanceHolder.mClient = new MongoClient(serverList, mCreList, options.build());
else
InstanceHolder.mClient = new MongoClient(serverList);
InstanceHolder.recordMdb = InstanceHolder.mClient.getDatabase(recordDbName);
return true;
} catch (Throwable t) {
log.error("initializing MongoClient failed", t);
return false;
}
}
/**
* 初始化breeze-consumer
*/
private static boolean initBreezeConsumer() {
InstanceHolder.timer = new Timer();
try {
log.debug("loading consumer.properties...");
//初始化阻塞队列
log.info("initializing blocking queue...");
String queueSize = Configration.CONSUMER_PROPS.getProperty("consumer.queueSize");
if ("".equals(queueSize) || queueSize == null) {
log.error("consumer.queueSize must not be null or empty!");
return false;
}
if ("0".equals(queueSize))
InstanceHolder.queue = new LinkedBlockingQueue<>();
else
InstanceHolder.queue = new LinkedBlockingQueue<>(Integer.parseInt(queueSize));
//初始化producer&consumer线程
log.info("initializing producer&consumer threads...");
//启动consumer线程
initConsumerThread();
//启动producer线程
initProducerThread();
//注册dameon线程,每5分钟执行一次
InstanceHolder.timer.schedule(new DaemonTask(), 10000, 5 * 60 * 1000);
return true;
} catch (Throwable t) {
log.error("initializing breeze-consumer failed", t);
//explicitly exit to trigger cleaning mechanism
System.exit(0);
return false;
}
}
private static void initProducerThread() {
//初始化producer线程(从kafka获取数据,作为生产者写入到消息队列)
int pCount = InstanceHolder.getProducerThreadCount();
log.info("the number of producer threads is " + pCount);
InstanceHolder.pThreads = new HashSet<>();
int i = 0;
while (InstanceHolder.pThreads.size() < pCount) {
ProducerThread pt = new ProducerThread();
pt.setName("Producer-" + i);
InstanceHolder.pThreads.add(pt);
i++;
}
InstanceHolder.producerNameCount = i;
//启动producer线程
log.info("launching producer threads...");
for (ProducerThread pt : InstanceHolder.pThreads) {
pt.start();
}
}
private static void initConsumerThread() {
int cCount = InstanceHolder.getConsumerThreadCount();
log.info("the number of consumer threads is " + cCount);
//初始化consumer线程(作为消费者来消费消息队列的数据,写入到mongodb)
InstanceHolder.cThreads = new HashSet<>();
int j = 0;
while (InstanceHolder.cThreads.size() < cCount) {
ConsumerThread ct = new ConsumerThread();
ct.setName("Consumer-" + j);
InstanceHolder.cThreads.add(ct);
j++;
}
InstanceHolder.consumerNameCount = j;
//启动consumer线程
log.info("launching consumer threads...");
for (ConsumerThread ct : InstanceHolder.cThreads) {
ct.start();
}
}
public static void main(String[] args) {
PropertyConfigurator.configure(ConsumerRunner.class.getClassLoader().getResource("log4j.properties"));
//注册进程退出hook,在进程退出时执行清理逻辑
Runtime.getRuntime().addShutdownHook(new CleanWorkThread());
// log.info("initializing mongo client...");
// if (ConsumerRunner.initMongo()) {
// log.info("initializing kafka client...");
// if (ConsumerRunner.initKafkaConsumer()) {
// log.info("initializing breeze-consumer...");
// if (ConsumerRunner.initBreezeConsumer()) {
// log.info("breeze-consumer started");
// return;
// }
// }
// }
log.info("initializing mongo client...");
if (ConsumerRunner.initMongo()) {
log.info("initializing breeze-consumer...");
if (ConsumerRunner.initBreezeConsumer()) {
log.info("breeze-consumer started");
return;
}
}
log.error("failed to start breeze-consumer");
System.exit(0);
}
}
| true
|
f0c05c42cfbd2de9113a3b55b2a7266e49a53e8b
|
Java
|
DarmokhvalViktor/Elective
|
/src/main/java/classes/idao/IArchivesDao.java
|
UTF-8
| 777
| 2.0625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classes.idao;
import classes.entity.Archives;
import java.util.Collection;
/**
*
* @author Андрей
*/
public interface IArchivesDao {
/**
*
* @return Collection<Archives> all records from archives;
*/
public Collection<Archives> findAllArchives() throws Exception;
/**
* @param Archives New Archives record, insert record into archive and set
* value in column users_isArchive true
*/
public void insertArchive(Archives archive) throws Exception;
public Archives findWhereCoursesIdEquals(Integer id) throws Exception;
}
| true
|
30a641017f349693c6e308df6aac72d7c76efba4
|
Java
|
bleujin/ISearcher
|
/src/net/ion/nsearcher/index/collect/DatabaseCollector.java
|
UTF-8
| 4,394
| 2.109375
| 2
|
[] |
no_license
|
package net.ion.nsearcher.index.collect;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import net.ion.framework.db.RowsUtils;
import net.ion.framework.db.bean.ResultSetHandler;
import net.ion.framework.db.procedure.Queryable;
import net.ion.framework.util.CaseInsensitiveHashMap;
import net.ion.framework.util.Debug;
import net.ion.nsearcher.common.HashFunction;
import net.ion.nsearcher.exception.ShutDownException;
import net.ion.nsearcher.index.event.DataRowEvent;
import net.ion.nsearcher.index.event.KeyValues;
import net.ion.nsearcher.index.handler.DataRowDocumentHandler;
import net.ion.nsearcher.index.handler.DocumentHandler;
import org.apache.commons.lang.ArrayUtils;
public class DatabaseCollector extends AbstractCollector {
private Queryable query;
private String[] keyColumns;
private String[] parentColumns;
private DocumentHandler handler;
public DatabaseCollector(Queryable query, String keyColumn) {
this(query, new String[] { keyColumn });
}
public DatabaseCollector(Queryable query, String[] keyColumns) {
this(query, keyColumns, keyColumns);
}
public DatabaseCollector(Queryable cmd, String[] keyColumns, String[] parentColumns) {
super(DEFAULT_NAME + "/" + cmd.getProcSQL());
this.query = cmd;
this.keyColumns = keyColumns;
this.parentColumns = parentColumns;
this.handler = new DataRowDocumentHandler();
}
public void collect() {
try {
fireStart();
DocumentMakerHandler handler = new DocumentMakerHandler(this);
query.execHandlerQuery(handler);
} catch (ShutDownException ignore) {
Debug.debug("SHUTDOWN......");
} catch (SQLException ignore) { // TODO when occured exception, what doing ?
ignore.printStackTrace();
} finally {
fireEnd();
}
}
public Queryable getQuery() {
return query;
}
public String[] getKeyColumns() {
return keyColumns;
}
private static class DocumentMakerHandler implements ResultSetHandler {
private static final long serialVersionUID = -4197073445282957962L;
private DatabaseCollector parent;
public DocumentMakerHandler(DatabaseCollector parent) {
this.parent = parent;
}
private Map<String, Object> currentRowToMap(ResultSetMetaData rsmd, ResultSet rs) throws SQLException {
Map<String, Object> result = new CaseInsensitiveHashMap<Object>();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; i++)
result.put(rsmd.getColumnName(i), getValue(rsmd, rs, i));
return result;
}
private static Object getValue(ResultSetMetaData meta, ResultSet rs, int i) throws SQLException {
// TODO BLOB..
if (meta.getColumnType(i) == 2005) // clob..
return RowsUtils.clobToString(rs.getClob(i));
else
return rs.getObject(i);
}
public Object handle(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
long beforeKey = 0L;
KeyValues keyValues = KeyValues.create();
while (rs.next()) {
if (parent.isShutDownState()) {
throw ShutDownException.throwIt(this.getClass());
}
long currKey = newKew(rs);
Map<String, Object> row = currentRowToMap(meta, rs);
if (isNewEvent(beforeKey, currKey)) {
if (beforeKey != 0L)
parent.fireCollectEvent(new DataRowEvent(parent, keyValues));
keyValues = KeyValues.create();
for (Entry<String, Object> entry : row.entrySet()) {
keyValues.add(entry.getKey(), entry.getValue());
}
beforeKey = currKey;
} else {
for (Entry<String, Object> entry : row.entrySet()) {
if (ArrayUtils.contains(parent.getKeyColumns(), entry.getKey()))
continue;
keyValues.add(entry.getKey(), entry.getValue());
}
}
}
parent.fireCollectEvent(new DataRowEvent(parent, keyValues));
return null;
}
private boolean isNewEvent(long beforeKey, long currKey) {
return beforeKey != currKey;
}
private long newKew(ResultSet rs) throws SQLException {
StringBuilder newKeyBuilder = new StringBuilder();
for (String key : parent.getKeyColumns()) {
newKeyBuilder.append(rs.getString(key) + " ");
}
long currKey = HashFunction.hashGeneral(newKeyBuilder.toString());
return currKey;
}
}
public DocumentHandler getDocumentHandler() {
return handler;
}
public void setDocumentHandler(DocumentHandler handler) {
this.handler = handler;
}
}
| true
|
d849dc39df81e3cf20937ac5f6b7ea5a59c3c6f0
|
Java
|
maojiaze/cold
|
/src/main/java/com/example/cold/Head_First_Design/v2_observer/exercise/Cs.java
|
UTF-8
| 273
| 2.1875
| 2
|
[] |
no_license
|
package com.example.cold.Head_First_Design.v2_observer.exercise;
public class Cs {
public static void main(String[] args) {
People people=new People();
Angel angel=new Angel(people);
Demon demon=new Demon(people);
people.say();
}
}
| true
|
11e95ea6ebcb709aa17a60eff32323d14918716c
|
Java
|
hummans/StrategyGame
|
/src/com/ligr/strategygame/Buttons/MessageCancelButton.java
|
UTF-8
| 911
| 2.21875
| 2
|
[] |
no_license
|
package com.ligr.strategygame.Buttons;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import com.ligr.strategygame.MainActivity;
public class MessageCancelButton extends Sprite {
private static String currentbuilding;
private MainActivity main;
public MessageCancelButton(float pX, float pY, ITextureRegion pTextureRegion,
VertexBufferObjectManager pVertexBufferObjectManager, MainActivity main) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.main = main;
}
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if(pSceneTouchEvent.isActionUp()){
Cancel();}
return true;
}
public void Cancel(){
main.removeMessage();
}
}
| true
|
9fcd3bbabce35b9156306913aabd967fbbbadd49
|
Java
|
Rishita-Nayak/Java-Fundamentals-Uncode
|
/Conditionals/checkdigit.java
|
UTF-8
| 515
| 3.328125
| 3
|
[] |
no_license
|
package Conditionals;
import java.util.Scanner;
public class checkdigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
if(a<10){
System.out.println("This is a single digit number");
return;
}
if(a>=10&&a<100){
System.out.println("This is a double digit number");
return;
}
System.out.println("This is a three digit number");
}
}
| true
|
dbf6becddc6f179189ddcc86db710ad39d8916ab
|
Java
|
ezhuun/javatest
|
/src/test/day07/OrderloadingTest.java
|
UHC
| 1,162
| 3.515625
| 4
|
[] |
no_license
|
package test.day07;
public class OrderloadingTest {
public static void main(String[] args) {
// =================
// εҵ ȣ
// =================
Test t1 = new Test();
t1.print(); // d : 0
t1.sum(); // true
t1.sum(1, 2); // 3
t1.sum(1, 2.5); // 3.5
// t1.sum(1); //error
// =================
// ڸҵ Ʈ
// =================
Test t2 = new Test(5);
t2.print(); // d : 5
}
}
class Test {
int d;
// =====================
// ҵ
// =====================
public Test() {
}
public Test(int d) {
this.d = d;
}
// =====================
// SET/ GET
// =====================
public void setD(int d) {
this.d = d;
}
public int getD() {
return this.d;
}
// =====================
// ε ҵ
// =====================
public boolean sum() {
return true;
}
public int sum(int a, int b) {
return (int) (a + b);
}
public double sum(double a, double b) {
return (double) (a + b);
}
// =====================
// ҵ
// =====================
public void print() {
System.out.println("d : " + this.d);
}
}
| true
|
dbfab0b5a20f2b79ede71833e5747a01d654444e
|
Java
|
bfortunato/applica-framework
|
/framework-data-security/src/main/java/applica/framework/data/security/OwnerProvider.java
|
UTF-8
| 147
| 1.632813
| 2
|
[
"CC-BY-4.0"
] |
permissive
|
package applica.framework.data.security;
/**
* Created by bimbobruno on 17/09/15.
*/
public interface OwnerProvider {
Object provide();
}
| true
|
8a736148ec7ee38be37be1cee45369574baa0253
|
Java
|
0jinxing/wechat-apk-source
|
/com/tencent/mm/plugin/sns/model/av.java
|
UTF-8
| 7,528
| 1.539063
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.platformtools.ae;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.sns.data.i;
import com.tencent.mm.protocal.protobuf.TimeLineObject;
import com.tencent.mm.protocal.protobuf.bau;
import com.tencent.mm.protocal.protobuf.uf;
import com.tencent.mm.sdk.platformtools.ab;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
public final class av
implements f
{
private static HashMap<String, av.b> qNg;
private static HashMap<String, WeakReference<av.b>> qNh;
static
{
AppMethodBeat.i(36681);
qNg = new HashMap();
qNh = new HashMap();
AppMethodBeat.o(36681);
}
public static void Yi(String paramString)
{
AppMethodBeat.i(36675);
if (ae.giZ)
ab.d("MicroMsg.TimelineSmallPicStat", "recordStartLoadSmallPic, mediaId:%s", new Object[] { paramString });
paramString = (WeakReference)qNh.get(paramString);
if (paramString != null)
{
paramString = (av.b)paramString.get();
if (paramString != null)
{
paramString.nnR = true;
AppMethodBeat.o(36675);
}
}
while (true)
{
return;
AppMethodBeat.o(36675);
}
}
public static void Yj(String paramString)
{
AppMethodBeat.i(36676);
if (ae.giZ)
ab.d("MicroMsg.TimelineSmallPicStat", "recordEndLoadSmallPic, mediaId:%s", new Object[] { paramString });
Object localObject = (WeakReference)qNh.get(paramString);
if (localObject != null)
{
localObject = (av.b)((WeakReference)localObject).get();
if (localObject != null)
{
if ((localObject != null) && (((av.b)localObject).qNi == -1L))
{
HashMap localHashMap = ((av.b)localObject).qNm;
if ((localHashMap != null) && (localHashMap.containsKey(paramString)))
{
paramString = (av.a)localHashMap.get(paramString);
if ((paramString != null) && (paramString.qNi == -1L))
{
paramString.qNi = 1L;
((av.b)localObject).qNl += 1;
}
}
}
AppMethodBeat.o(36676);
}
}
while (true)
{
return;
AppMethodBeat.o(36676);
}
}
public static void Yk(String paramString)
{
AppMethodBeat.i(36677);
ab.d("MicroMsg.TimelineSmallPicStat", "recordClickBigpic, localId:%s", new Object[] { paramString });
if (qNg.containsKey(paramString))
{
ab.d("MicroMsg.TimelineSmallPicStat", "recordClickBigPic, localId:%s, update map", new Object[] { paramString });
paramString = (av.b)qNg.get(paramString);
if ((paramString != null) && (paramString.qNi == -1L) && (paramString.startTime != -1L))
{
paramString.qNi = 1L;
paramString.qNl = paramString.fjN;
paramString.endTime = System.currentTimeMillis();
paramString.qNk = (paramString.endTime - paramString.startTime);
paramString = paramString.qNm.values().iterator();
while (paramString.hasNext())
((av.a)paramString.next()).qNi = 1L;
}
}
AppMethodBeat.o(36677);
}
public final void XJ(String paramString)
{
AppMethodBeat.i(36679);
if (qNg.containsKey(paramString))
{
if (ae.giZ)
ab.d("MicroMsg.TimelineSmallPicStat", "load finish localId:%s", new Object[] { paramString });
paramString = (av.b)qNg.get(paramString);
if ((paramString != null) && (paramString.startTime != -1L) && (paramString.qNi == -1L))
{
paramString.endTime = System.currentTimeMillis();
paramString.qNk = (paramString.endTime - paramString.startTime);
if (paramString.qNl == paramString.fjN)
{
paramString.qNi = 1L;
AppMethodBeat.o(36679);
}
}
}
while (true)
{
return;
paramString.qNi = 2L;
AppMethodBeat.o(36679);
}
}
public final void a(String paramString, TimeLineObject paramTimeLineObject)
{
AppMethodBeat.i(36678);
if (!qNg.containsKey(paramString))
{
if (ae.giZ)
ab.d("MicroMsg.TimelineSmallPicStat", "put localId:%s into reportData", new Object[] { paramString });
if ((paramTimeLineObject != null) && (paramTimeLineObject.xfI != null) && (paramTimeLineObject.xfI.wbJ == 1) && (paramTimeLineObject.xfI.wbK != null) && (paramTimeLineObject.xfI.wbK.size() > 0))
{
av.b localb = new av.b(this);
localb.fjN = paramTimeLineObject.xfI.wbK.size();
localb.qNl = 0;
localb.qNm = new HashMap();
paramTimeLineObject = paramTimeLineObject.xfI.wbK.iterator();
while (paramTimeLineObject.hasNext())
{
bau localbau = (bau)paramTimeLineObject.next();
av.a locala = new av.a(this);
locala.cHr = localbau.Id;
localb.qNm.put(localbau.Id, locala);
qNh.put(localbau.Id, new WeakReference(localb));
}
localb.startTime = System.currentTimeMillis();
qNg.put(paramString, localb);
AppMethodBeat.o(36678);
}
}
while (true)
{
return;
if (ae.giZ)
ab.d("MicroMsg.TimelineSmallPicStat", "onItemAdd error, timelineObject is nulli");
AppMethodBeat.o(36678);
}
}
public final void cmU()
{
AppMethodBeat.i(36680);
ab.d("MicroMsg.TimelineSmallPicStat", "reportAll, reportData.size:%d", new Object[] { Integer.valueOf(qNg.size()) });
int i = i.cms();
Iterator localIterator = qNg.keySet().iterator();
while (localIterator.hasNext())
{
Object localObject = (String)localIterator.next();
localObject = (av.b)qNg.get(localObject);
if ((localObject != null) && (((av.b)localObject).nnR))
if ((((av.b)localObject).qNk == -1L) || (((av.b)localObject).qNi == -1L) || (((av.b)localObject).startTime == -1L))
{
if (((av.b)localObject).startTime != -1L)
{
((av.b)localObject).endTime = System.currentTimeMillis();
((av.b)localObject).qNk = (((av.b)localObject).endTime - ((av.b)localObject).startTime);
if (((av.b)localObject).fjN != ((av.b)localObject).qNl);
}
}
else
for (((av.b)localObject).qNi = 1L; ; ((av.b)localObject).qNi = 2L)
{
ab.d("MicroMsg.TimelineSmallPicStat", "reportAll, picNum:%d, loadResult:%d, loadCostTime:%d, loadPicNum:%d, networkType:%d", new Object[] { Integer.valueOf(((av.b)localObject).fjN), Long.valueOf(((av.b)localObject).qNi), Long.valueOf(((av.b)localObject).qNk), Integer.valueOf(((av.b)localObject).qNl), Integer.valueOf(i) });
h.pYm.e(11600, new Object[] { Integer.valueOf(((av.b)localObject).fjN), Long.valueOf(((av.b)localObject).qNi), Long.valueOf(((av.b)localObject).qNk), Integer.valueOf(((av.b)localObject).qNl), Integer.valueOf(i) });
break;
}
}
qNg.clear();
qNh.clear();
AppMethodBeat.o(36680);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes2-dex2jar.jar
* Qualified Name: com.tencent.mm.plugin.sns.model.av
* JD-Core Version: 0.6.2
*/
| true
|
5a6facbabf9d1be34666b198f48ed3e2f6b6864c
|
Java
|
ligoj/plugin-id
|
/src/test/java/org/ligoj/app/plugin/id/resource/GroupResourceTest.java
|
UTF-8
| 14,512
| 1.625
| 2
|
[
"MIT"
] |
permissive
|
/*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.app.plugin.id.resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.ligoj.app.iam.CompanyOrg;
import org.ligoj.app.iam.ContainerOrg;
import org.ligoj.app.iam.GroupOrg;
import org.ligoj.app.iam.IamProvider;
import org.ligoj.app.iam.UserOrg;
import org.ligoj.app.model.ContainerType;
import org.ligoj.app.plugin.id.model.ContainerScope;
import org.ligoj.bootstrap.MatcherUtil;
import org.ligoj.bootstrap.core.json.TableItem;
import org.ligoj.bootstrap.core.json.datatable.DataTableAttributes;
import org.ligoj.bootstrap.core.validation.ValidationJsonException;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.springframework.data.domain.PageImpl;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/**
* Test class of {@link GroupResource}
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/application-context-test.xml")
@Rollback
@Transactional
class GroupResourceTest extends AbstractContainerResourceTest {
public static final String GROUP_FUNCTION = "Fonction";
private GroupResource resource;
@BeforeEach
void mock() {
resource = new GroupResource();
applicationContext.getAutowireCapableBeanFactory().autowireBean(resource);
resource.iamProvider = new IamProvider[] { iamProvider };
Mockito.when(groupRepository.getTypeName()).thenReturn("group");
}
@Test
void findAll() {
final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.singleton("user1"));
final GroupOrg groupOrg2 = new GroupOrg("cn=DIG RHA,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG RHA",
Collections.singleton("user2"));
groupOrg2.setLocked(true);
final Map<String, GroupOrg> groupsMap = new HashMap<>();
groupsMap.put("dig", groupOrg1);
groupsMap.put("dig rha", groupOrg2);
final Map<String, UserOrg> users = new HashMap<>();
final UserOrg user1 = new UserOrg();
user1.setCompany("france");
users.put("user1", user1);
final UserOrg user2 = new UserOrg();
user2.setCompany("france");
users.put("user2", user2);
user2.setCompany("ing-internal");
final CompanyOrg companyOrg1 = new CompanyOrg("ou=france,ou=people,dc=sample,dc=com", "france");
final CompanyOrg companyOrg2 = new CompanyOrg("ou=ing-internal,ou=ing,ou=external,ou=people,dc=sample,dc=com", "ing-internal");
final Map<String, CompanyOrg> companies = new HashMap<>();
companies.put("france", companyOrg1);
companies.put("ing-internal", companyOrg2);
Mockito.when(companyRepository.findAll()).thenReturn(companies);
Mockito.when(userRepository.findAll()).thenReturn(users);
Mockito.when(groupRepository.findAll()).thenReturn(groupsMap);
Mockito.when(
groupRepository.findAll(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
.thenReturn(new PageImpl<>(Arrays.asList(groupOrg1, groupOrg2)));
final TableItem<ContainerCountVo> groups = resource.findAll(newUriInfoAscSearch("name", "d"));
Assertions.assertEquals(2, groups.getRecordsTotal());
Assertions.assertEquals(2, groups.getRecordsFiltered());
Assertions.assertEquals(2, groups.getData().size());
final ContainerCountVo group0 = groups.getData().get(0);
Assertions.assertEquals("DIG", group0.getName());
Assertions.assertEquals(1, group0.getCount());
Assertions.assertEquals(0, group0.getCountVisible());
Assertions.assertTrue(group0.isCanAdmin());
Assertions.assertTrue(group0.isCanWrite());
Assertions.assertEquals(GROUP_FUNCTION, group0.getScope());
Assertions.assertEquals("dig", group0.getId());
Assertions.assertFalse(group0.isLocked());
final ContainerCountVo group10 = groups.getData().get(1);
Assertions.assertEquals("DIG RHA", group10.getName());
Assertions.assertEquals(1, group10.getCount());
Assertions.assertEquals(0, group10.getCountVisible());
Assertions.assertTrue(group10.isCanAdmin());
Assertions.assertTrue(group10.isCanWrite());
Assertions.assertEquals(GROUP_FUNCTION, group10.getScope());
Assertions.assertEquals(ContainerType.GROUP, group10.getContainerType());
Assertions.assertTrue(group10.isLocked());
}
@Test
void findByNameNoType() {
Mockito.when(groupRepository.findById(DEFAULT_USER, "business solution"))
.thenReturn(new GroupOrg("cn=Business Solution,ou=groups,dc=sample,dc=com", "Business Solution", null));
final ContainerWithScopeVo group = resource.findByName("business solution");
Assertions.assertEquals("Business Solution", group.getName());
Assertions.assertNull(group.getScope());
}
@Test
void findByNameNotExistingGroup() {
Assertions.assertNull(resource.findByName("any"));
}
@Test
void findByName() {
Mockito.when(groupRepository.findById(DEFAULT_USER, "dig as"))
.thenReturn(new GroupOrg("cn=DIG AS,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG AS", null));
final ContainerWithScopeVo group = resource.findByName("dig as");
Assertions.assertEquals("DIG AS", group.getName());
Assertions.assertEquals(GROUP_FUNCTION, group.getScope());
}
@Test
void findByIdNotExists() {
Assertions.assertNull(resource.findById("any"));
}
/**
* There is a delegate of "business solution" for this user, but the user
* does not exist anymore.
*/
@Test
void findByIdUserNoRight() {
initSpringSecurityContext("assist");
Assertions.assertNull(resource.findById("business solution"));
}
@Test
void exists() {
Mockito.when(groupRepository.findById(DEFAULT_USER, "dig as"))
.thenReturn(new GroupOrg("cn=DIG AS,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "dig as", null));
Assertions.assertTrue(resource.exists("dig as"));
}
@Test
void existsNot() {
Assertions.assertFalse(resource.exists("any"));
}
@Test
void createWithParent() {
final GroupEditionVo group = new GroupEditionVo();
group.setDepartments(Collections.singletonList("SOME"));
group.setOwners(Collections.singletonList("fdaugan"));
group.setAssistants(Collections.singletonList("wuser"));
group.setParent("DIG");
final UserOrg user = new UserOrg();
user.setCompany("ext");
user.setDn("uid=wuser");
final UserOrg user2 = new UserOrg();
user2.setCompany("internal");
user2.setDn("uid=fdaugan");
Mockito.when(userRepository.findByIdExpected("wuser")).thenReturn(user);
Mockito.when(userRepository.findByIdExpected("fdaugan")).thenReturn(user2);
Mockito.when(groupRepository.findByIdExpected(DEFAULT_USER, "dig"))
.thenReturn(new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", null));
createInternal(group, "cn=new-group,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com");
}
@Test
void create() {
createInternal(new GroupEditionVo(), "cn=new-group,ou=fonction,ou=groups,dc=sample,dc=com");
}
private void createInternal(final GroupEditionVo group, final String expected) {
final ContainerScope scope = containerScopeRepository.findByName(GROUP_FUNCTION);
group.setName("new-group");
group.setScope(scope.getId());
final GroupOrg groupOrg1 = new GroupOrg("cn=new-group", "new-group", null);
Mockito.when(groupRepository.create(expected, "new-group")).thenReturn(groupOrg1);
Assertions.assertEquals("new-group", resource.create(group));
}
@Test
void deleteNoRight() {
initSpringSecurityContext("mmartin");
Mockito.when(groupRepository.findByIdExpected("mmartin", "dig rha"))
.thenReturn(new GroupOrg("cn=DIG RHA,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "dig rha", null));
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.delete("dig rha");
}), "group", "unknown-id");
}
@Test
void empty() {
final GroupOrg groupOrg1 = new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", Collections.emptySet());
final GroupOrg groupOrg2 = new GroupOrg("cn=DIG RHA,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG RHA",
Collections.emptySet());
groupOrg2.setLocked(true);
final Map<String, GroupOrg> groupsMap = new HashMap<>();
groupsMap.put("dig", groupOrg1);
groupsMap.put("dig rha", groupOrg2);
Mockito.when(groupRepository.findAll()).thenReturn(groupsMap);
Mockito.when(groupRepository.findByIdExpected(DEFAULT_USER, "dig rha"))
.thenReturn(new GroupOrg("cn=DIG RHA,cn=DIG AS,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "dig rha", null));
resource.empty("dig rha");
}
@Test
void toDnParent() {
final ContainerScope scope = containerScopeRepository.findByName(GROUP_FUNCTION);
final GroupEditionVo group = new GroupEditionVo();
group.setName("new-group");
group.setParent(" DiG ");
Mockito.when(groupRepository.findByIdExpected(DEFAULT_USER, "dig"))
.thenReturn(new GroupOrg("cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", "DIG", null));
Assertions.assertEquals("cn=new-group,cn=DIG,ou=fonction,ou=groups,dc=sample,dc=com", resource.toDn(group, scope));
}
@Test
void toDnParentInvalid() {
final ContainerScope scope = containerScopeRepository.findByName(GROUP_FUNCTION);
final GroupEditionVo group = new GroupEditionVo();
group.setName("new-group");
group.setParent(" DiG ");
Mockito.when(groupRepository.findByIdExpected(DEFAULT_USER, "dig"))
.thenReturn(new GroupOrg("cn=ext,dc=sample,dc=com", "DIG", null));
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.toDn(group, scope);
}), "parent", "container-parent-type-match");
}
@Test
void toDn() {
final ContainerScope scope = containerScopeRepository.findByName(GROUP_FUNCTION);
final GroupEditionVo group = new GroupEditionVo();
group.setName("new-group");
Assertions.assertEquals("cn=new-group,ou=fonction,ou=groups,dc=sample,dc=com", resource.toDn(group, scope));
}
@Test
void emptyNoRight() {
initSpringSecurityContext("mmartin");
MatcherUtil.assertThrows(Assertions.assertThrows(ValidationJsonException.class, () -> {
resource.empty("dig rha");
}), "group", "unknown-id");
}
/**
* Check visible group is filtered against available groups for write.
*/
@Test
void getContainersForWrite() {
initSpringSecurityContext("mlavoine");
final TableItem<String> items = resource.getContainersForWrite(newUriInfo());
Assertions.assertEquals(0, items.getRecordsFiltered());
Assertions.assertEquals(0, items.getRecordsTotal());
Assertions.assertEquals(0, items.getData().size());
}
/**
* Check visible group is filtered against available groups for
* administration.
*/
@Test
void getContainersForAdmin() {
initSpringSecurityContext("mtuyer");
final TableItem<String> items = resource.getContainersForAdmin(newUriInfo());
// This user can see 4 groups from the direct admin delegates to him
Assertions.assertEquals(4, items.getRecordsFiltered());
Assertions.assertEquals(4, items.getRecordsTotal());
Assertions.assertEquals(4, items.getData().size());
}
/**
* Check visible group is filtered against available groups for
* administration.
*/
@Test
void getContainersForAdminNoRight() {
initSpringSecurityContext("mlavoine");
final TableItem<String> items = resource.getContainersForAdmin(newUriInfo());
Assertions.assertEquals(0, items.getRecordsFiltered());
Assertions.assertEquals(0, items.getRecordsTotal());
Assertions.assertEquals(0, items.getData().size());
}
@Test
void getContainersDelegateTreeExactParentDn() {
initSpringSecurityContext("mlavoine");
final TableItem<String> items = resource.getContainers(newUriInfo());
Assertions.assertEquals(4, items.getRecordsFiltered());
Assertions.assertEquals(4, items.getRecordsTotal());
Assertions.assertEquals(4, items.getData().size());
// Brought by a delegate of "cn=biz agency,ou=tools,dc=sample,dc=com" to
// company user "mlavoine"
Assertions.assertTrue(items.getData().contains("Biz Agency"));
Assertions.assertTrue(items.getData().contains("Biz Agency Manager"));
// Brought by a delegate of "Business Solution" to company "ing"
Assertions.assertTrue(items.getData().contains("Business Solution"));
Assertions.assertTrue(items.getData().contains("Sub Business Solution"));
}
@Test
void getContainersDelegateTreeSubParentDn() {
initSpringSecurityContext("mtuyer");
final UriInfo uriInfo = newUriInfo();
uriInfo.getQueryParameters().add(DataTableAttributes.PAGE_LENGTH, "100");
final TableItem<String> items = resource.getContainers(uriInfo);
Assertions.assertEquals(6, items.getRecordsFiltered());
Assertions.assertEquals(6, items.getRecordsTotal());
Assertions.assertEquals(6, items.getData().size());
// Brought by a delegate of "ou=fonction,ou=groups,dc=sample,dc=com" to
// company user "mtuyer"
Assertions.assertTrue(items.getData().contains("DIG AS"));
Assertions.assertTrue(items.getData().contains("DIG"));
// Brought by a delegate of "Business Solution" to company "ing"
Assertions.assertTrue(items.getData().contains("Business Solution"));
Assertions.assertTrue(items.getData().contains("Sub Business Solution"));
}
@Test
void getContainersNoDelegate() {
initSpringSecurityContext("any");
final TableItem<String> items = resource.getContainers(newUriInfo());
Assertions.assertEquals(0, items.getRecordsFiltered());
Assertions.assertEquals(0, items.getRecordsTotal());
Assertions.assertEquals(0, items.getData().size());
}
@Test
void getContainersDelegateGroup() {
initSpringSecurityContext("someone");
final TableItem<String> items = resource.getContainers(newUriInfo());
Assertions.assertEquals(1, items.getRecordsFiltered());
Assertions.assertEquals(1, items.getRecordsTotal());
Assertions.assertEquals(1, items.getData().size());
Assertions.assertTrue(items.getData().contains("DIG RHA"));
}
@Test
void newContainerCountVo() {
ContainerOrg rawContainer = new ContainerOrg("dn=no-scope", "name");
Assertions.assertNull(resource
.newContainerCountVo(rawContainer, Collections.emptySet(), Collections.emptySet(), Collections.emptyList()).getScope());
}
}
| true
|
60d1d6362fd565af5c2982a6e335edaccab2b75a
|
Java
|
BsharaSahoury/Ass3-ICM-
|
/ICM/src/Server/ServerTestFailedObserver.java
|
UTF-8
| 1,498
| 2.109375
| 2
|
[] |
no_license
|
package Server;
import java.sql.Connection;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Observable;
import java.util.Observer;
import DBconnection.mysqlConnection;
import Entity.Notification;
import ocsf.server.ConnectionToClient;
public class ServerTestFailedObserver implements Observer {
public ServerTestFailedObserver(Observable server) {
server.addObserver(this);
}
@Override
public void update(Observable arg0, Object arg1) {
if(arg1 instanceof Object[]) {
Object[] arg2=(Object[])arg1;
ConnectionToClient client=(ConnectionToClient)arg2[0];
if(arg2[1] instanceof Object[]) {
Object[] arg3=(Object[])arg2[1];
if(arg3[0] instanceof String) {
String keymessage=(String)arg3[0];
if(keymessage.equals("send Failure test result")) {
int requestId=(int)arg3[1];
String failureDetails=(String)arg3[2];
Connection con=mysqlConnection.makeAndReturnConnection();
mysqlConnection.updateDBdueToFailTest(con,requestId);
long millis=System.currentTimeMillis();
Notification n=new Notification("test for request#"+requestId+"failed, request returned to performance phase, please select a performer",new java.sql.Date(millis),"fail message sent to Inspector");
n=mysqlConnection.insertNotificationToDB(con, n);
mysqlConnection.insertNotificationDetailsToDB(con, n,failureDetails);
mysqlConnection.sendFailDetailsToInspector(con,n);
}
}
}
}
}
}
| true
|
261fdb1ff6492d65eea013959b20e84156e6f27c
|
Java
|
Haga14/JDBC-lite
|
/Comm.java
|
UTF-8
| 4,782
| 2.375
| 2
|
[] |
no_license
|
package libs;
import libs.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Comm {
private JDBCCreateDB Database;
private BasicQueries queries;
private Connection connect;
private CreateTable tableMaker;
private Runner run;
private BasicQueries Qs = new BasicQueries();
private String colNames[];
private String colTypes[];
private String data[];
private String tableName;
private InputGetter validator = new InputGetter();
public Comm() {
init();
}
public void init() {
Database = new JDBCCreateDB();
queries = new BasicQueries();
connect = Database.connectDBMS("test", "root", "root");
tableMaker = new CreateTable();
run = new Runner();
}
public void input(String inTableName, String inColNames[], String inColTypes[], String inData[]) {
colNames = inColNames;
colTypes = inColTypes;
data = inData;
tableName = inTableName;
}
public void input(String inData[]) {
data = inData;
}
public void input(String inData[], String inTable) {
data = inData;
tableName = inTable;
}
public void selectDB(String name)
{
run.Change(connect, queries.UseDB(name));
}
public void createDB(String name){
Database.createDB(connect, queries.CreateDB(name));
}
public void buildTable(String inTableName, String inColNames[], String inColTypes[]) {
colNames = inColNames;
colTypes = inColTypes;
tableName = inTableName;
String SQL = tableMaker.buildTable(tableName, colTypes, colNames);
System.out.println(SQL);
run.Change(connect, SQL);
}
public void buildTable() {
String SQL = tableMaker.buildTable(tableName, colTypes, colNames);
//System.out.println(SQL);
run.Change(connect, SQL);
}
public void appendToTable() {
ArrayList<String> aLdata = new ArrayList<String>();
Statement stmnt;
ResultSet resultset = null;
for(int i = 0; i < data.length; i++) aLdata.add(data[i]);
try {
stmnt = connect.createStatement();
resultset = stmnt.executeQuery(queries.getTable(tableName));
tableMaker.input(colTypes, colNames);
String SQL = tableMaker.insertRow(tableName, resultset.getMetaData(), aLdata);
System.out.println(SQL);
//System.out.println(SQL);
stmnt.executeUpdate(SQL);
}
catch(SQLException e) {
e.printStackTrace();
System.exit(0);
}
}
public String[] getUsers() {
run.Qrun(connect, queries.getUserNames("users"));
ArrayList<String> data = new ArrayList<String>();
int index = 1;
try {
while(run.rs.next())
{
try {
data.add(run.rs.getString("userName"));
index++;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String retString[] = new String[data.size()];
for(int i = 0; i < data.size(); i++)
{
retString[i] = data.get(i);
}
return retString;
}
public boolean findUser(String userName)
{
if(validator.isAlpha(userName))
{
run.Qrun(connect, Qs.getUserName("users", userName));
try {
if(run.rs.getString("userName") == userName)
{
run.rs = null;
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
run.rs = null;
e.printStackTrace();
return false;
}
}
///Set run.rs to null each time used.
run.rs = null;
return false;
}
public double getAmount(String uName){
double temp = -1;
run.Qrun(connect, queries.getAmountHeld("userData", uName));
if(run.sent)
{
try {
run.rs.next();
temp = Double.parseDouble(run.rs.getString("Dollar"));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
run.rs = null;
return temp;
}
public void changeValue(String table, String col, String value, String uName) {
//System.out.println(queries.setValue(table, col, value, uName));
run.Change(connect, queries.setValue(table, col, value, uName));
}
/*public void getUserValues() {
for(int i = 0; i < bank.size(); i++) {
bank.get(i).getValue();
}
}*/
public boolean loginUser(String uName, String uP)
{
if(validator.isAlpha(uName) && validator.isAlpha(uP))
{
run.Qrun(connect, Qs.verifyUserCreds("users", uName, uP));
run.rs = null;
return run.sent;
}
run.rs = null;
return false;
}
public void dropTable(String name)
{
run.Change(connect, queries.dropTables(name));
run.rs = null;
}
public void terminate() {
Database.closeConnections();
System.exit(0);
}
}
| true
|
f56c0ded34b29299bf004ff667d1a60c75cf4a73
|
Java
|
brasajava/playinjava
|
/spring-jsf/src/main/java/com/brasajava/services/UserServiceImpl.java
|
UTF-8
| 2,399
| 2.140625
| 2
|
[] |
no_license
|
package com.brasajava.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.brasajava.beans.User;
@Service
@Transactional
public class UserServiceImpl implements JpaService<User> {
@Autowired
private JpaRepository<User, Long> repository;
@Override
public Page<User> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
@Override
public long count() {
return repository.count();
}
@Override
public void delete(Long id) {
repository.delete(id);
}
@Override
public void delete(User user) {
repository.delete(user);
}
@Override
public void delete(Iterable<? extends User> iterable) {
repository.delete(iterable);
}
@Override
public void deleteAll() {
repository.deleteAll();
}
@Override
public boolean exists(Long id) {
return repository.exists(id);
}
@Override
public User findOne(Long id) {
return repository.findOne(id);
}
@Override
public <S extends User> S save(S user) {
return repository.save(user);
}
@Override
public void deleteAllInBatch() {
repository.deleteAllInBatch();
}
@Override
public void deleteInBatch(Iterable<User> iterable) {
repository.deleteInBatch(iterable);
}
@Override
public List<User> findAll() {
return repository.findAll();
}
@Override
public List<User> findAll(Sort sort) {
return repository.findAll(sort);
}
@Override
public List<User> findAll(Iterable<Long> iterable) {
return repository.findAll(iterable);
}
@Override
public void flush() {
repository.flush();
}
@Override
public User getOne(Long id) {
return repository.getOne(id);
}
@Override
public <S extends User> List<S> save(Iterable<S> iterable) {
return repository.save(iterable);
}
@Override
public <S extends User> S saveAndFlush(S user) {
return repository.saveAndFlush(user);
}
@Override
public void setRepository(JpaRepository<User, Long> repository) {
this.repository = repository;
}
}
| true
|
145adcb9d9d2342913810fe6958fdea42134213d
|
Java
|
Andreas-White/security
|
/src/main/java/com/peerlender/security/user/service/implementation/TokenAuthentication.java
|
UTF-8
| 1,461
| 2.21875
| 2
|
[] |
no_license
|
package com.peerlender.security.user.service.implementation;
import com.google.common.collect.ImmutableMap;
import com.peerlender.security.user.model.User;
import com.peerlender.security.user.repository.UserRepository;
import com.peerlender.security.user.service.TokenService;
import com.peerlender.security.user.service.UserAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Optional;
@Service
public class TokenAuthentication implements UserAuthenticationService {
private final TokenService tokenService;
private final UserRepository userRepository;
@Autowired
public TokenAuthentication(TokenService tokenService, UserRepository userRepository) {
this.tokenService = tokenService;
this.userRepository = userRepository;
}
@Override
public Optional<String> login(String username, String password) {
return Optional.ofNullable(userRepository
.findByUserDetails_Username(username))
.filter(user -> user.get().getUserDetails().getPassword().equals(password))
.map(user -> tokenService.expiring(ImmutableMap.of("username",username)));
}
@Override
public User findByToken(String token) {
Map<String,String> result = tokenService.verify(token);
return userRepository.findByUserDetails_Username(result.get("username")).get();
}
}
| true
|
3ee88dc66ed179e8639dd0af4a2fa2d089242a61
|
Java
|
tduyphuc/SWD391
|
/SpringWebService/src/main/java/service/room/IRoomInfo.java
|
UTF-8
| 338
| 1.96875
| 2
|
[] |
no_license
|
package service.room;
import java.util.Map;
public interface IRoomInfo {
public String getAllRoomType();
public Integer getAvailableRoom(Integer typeID);
public Double getTotalPrice(Map<Integer, Integer> details);
public String getAllService(String typeId);
public String getAllRooms();
public void updateAllRooms(String body);
}
| true
|
dd0a02f186caa18c1df5fc02d04e065383d18d6a
|
Java
|
dudwns9331/JavaStudy
|
/JavaStudy/Java2/src/Threads/GreetingThreadTester4.java
|
UTF-8
| 901
| 3.515625
| 4
|
[] |
no_license
|
package Threads;
import javax.swing.*;
public class GreetingThreadTester4 {
Thread t1;
Thread t2;
void startThreads() {
GreetingRunnable r1 = new GreetingRunnable("안녕?");
GreetingRunnable r2 = new GreetingRunnable("바이!");
t1 = new Thread(r1);
t2 = new Thread(r2);
t1.start();
t2.start();
}
void interruptThread() {
String input = JOptionPane.showInputDialog(
"어떤 인삿말을 하는 스레드를 끝낼까요?"
);
if(input.equals("안녕?"))
t1.interrupt();
else if (input.equals("바이!"))
t2.interrupt();
}
public static void main(String[] args) {
GreetingThreadTester4 tester4 = new GreetingThreadTester4();
tester4.startThreads();
tester4.interruptThread();
tester4.interruptThread();
}
}
| true
|
781b2cae0ec60d11cde7800355d5ba89d46a36e3
|
Java
|
daxingyou/yxj
|
/mmoarpg/mmoarpg-game/src/request/com/wanniu/game/request/team/CreateTeamHandler.java
|
UTF-8
| 1,498
| 2.078125
| 2
|
[] |
no_license
|
package com.wanniu.game.request.team;
import java.io.IOException;
import com.wanniu.core.game.LangService;
import com.wanniu.core.game.entity.GClientEvent;
import com.wanniu.core.game.protocol.PomeloResponse;
import com.wanniu.game.common.Const;
import com.wanniu.game.common.msg.ErrorResponse;
import com.wanniu.game.player.WNPlayer;
import com.wanniu.game.team.TeamUtil;
import pomelo.area.TeamHandler.CreateTeamResponse;
/**
* @author agui
*/
@GClientEvent("area.teamHandler.createTeamRequest")
public class CreateTeamHandler extends TeamRequestFilter {
@Override
public PomeloResponse request(WNPlayer player) throws Exception {
if (!TeamUtil.isValidOfMap(player.getSceneType())) {
return new ErrorResponse(LangService.getValue("TEAM_IN_RAID"));
}
if (player.getTeamManager().isInTeam()) {
return new ErrorResponse(LangService.getValue("TEAM_ALREADY_IN_TEAM"));
}
return new PomeloResponse() {
@Override
protected void write() throws IOException {
CreateTeamResponse.Builder res = CreateTeamResponse.newBuilder();
String result = null;
if (player.getSceneType() == Const.SCENE_TYPE.CROSS_SERVER.getValue()) {
result = TeamUtil.createAcrossTeam(player.getId(), null);
} else {
result = TeamUtil.createLocaleTeam(player.getId(), null);
}
if (result == null) {
res.setS2CCode(OK);
} else {
res.setS2CCode(FAIL);
res.setS2CMsg(result);
}
body.writeBytes(res.build().toByteArray());
}
};
}
}
| true
|
4e314bcfa3fc720530c285f72bffa94e2c39a68b
|
Java
|
kylecarter2020/Maven.FarmerFroilan
|
/src/main/java/com/zipcodewilmington/froilansfarm/animals/Horse.java
|
UTF-8
| 1,114
| 3.015625
| 3
|
[] |
no_license
|
package com.zipcodewilmington.froilansfarm.animals;
import com.zipcodewilmington.froilansfarm.interfaces.Animal;
import com.zipcodewilmington.froilansfarm.interfaces.Edible;
import com.zipcodewilmington.froilansfarm.interfaces.Ridable;
import com.zipcodewilmington.froilansfarm.produce.EarCorn;
public class Horse implements Animal, Ridable {
private Boolean isHorseRidden = false;
private Boolean isHorseFed = false;
private EarCorn horsefood;
public Horse() {
this.isHorseRidden = false;
this.horsefood = null;
this.isHorseFed = false;
}
public String makeNoise() {
return "neigh!";
}
public void eat(Edible food) {
this.horsefood = (EarCorn) food;
if (horsefood != null && horsefood instanceof EarCorn) {
this.isHorseFed = true;
}
}
public void ride() {
this.isHorseRidden = true;
}
public Boolean getHorseRidden() {
return this.isHorseRidden;
}
public Boolean getHorseFed() {
return this.isHorseFed;
}
@Override
public void work() {
}
}
| true
|
a7098c234f122d1fb0d4fe1003a8e4c64c5b537d
|
Java
|
anshujava/TestingSelenium
|
/Selenum_Project/src/TASK/Task1.java
|
UTF-8
| 974
| 4.125
| 4
|
[] |
no_license
|
package TASK;
/*1. Given two lists A and B. Find the sum of squares of elements in A and cubes of elements in B.
Example: A = [1,2,3] and B=[2,3]. The sum would be 1^2 + 2^2 + 3^2 + 2^3 + 3^3.
The challenge would be to accomplish this with the least lines of code possible. Best case is a single line solution.
*/
public class Task1 {
public static void main(String[] args) {
int [] A={1,2,3};
int [] B={2,3};
System.out.println("Total sum is = " + (SumOfA(A)+ SumOfB(B)));
}
public static int SumOfA(int[] A)
{
int square=1;
int sum=0;
int n=A.length;
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
public static int SumOfB(int[] B)
{
int cube=1;
int sum=0;
int n=B.length;
for(int i=0;i<n;i++)
{
cube=B[i]*B[i]*B[i];
sum+=cube;
}
return sum;
}
}
| true
|
b8f84abab35d3b7be3204aa569fec0159feccebc
|
Java
|
dangarfield/lkhelper
|
/src/main/java/com/dangarfield/lkhelper/controller/MapsController.java
|
UTF-8
| 6,454
| 2.046875
| 2
|
[] |
no_license
|
package com.dangarfield.lkhelper.controller;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dangarfield.lkhelper.constants.ControllerConstants;
import com.dangarfield.lkhelper.data.report.MapCompareRequest;
import com.dangarfield.lkhelper.service.ImageProcessingService;
import com.dangarfield.lkhelper.service.impl.ImageProcessingServiceImpl;
@Controller
public class MapsController {
@Autowired
private ImageProcessingService imageProcessingService;
@RequestMapping(value=ControllerConstants.URL.Maps.BaseMap, method = RequestMethod.GET)
public @ResponseBody byte[] baseServerMapImage(Model model, Principal principal,
@PathVariable(ControllerConstants.URL.PathVariable.ServerID) String serverId,
@RequestParam(value = "clear", required = false) boolean clear,
@RequestParam(value = "thickness", required = false) Integer thickness,
@RequestParam(value = "colour", required = false) String colour) throws IOException {
final int thicknessInt = ensureCorrectThickness(thickness, ImageProcessingServiceImpl.DEFAULT_THICKNESS_BASE);
final Color colorObj = ensureCorrectColour(colour, ImageProcessingServiceImpl.DEFAULT_COLOUR_BASE);
final File image = imageProcessingService.generateBaseMap(serverId, clear, thicknessInt, colorObj);
InputStream inputStream = new FileInputStream(image);
return IOUtils.toByteArray(inputStream);
}
@RequestMapping(value=ControllerConstants.URL.Maps.AllianceMap, method = RequestMethod.GET)
public @ResponseBody byte[] allianceMapImage(Model model, Principal principal,
@PathVariable(ControllerConstants.URL.PathVariable.ServerID) String serverId,
@PathVariable(ControllerConstants.URL.PathVariable.AllianceID) int allianceId,
@RequestParam(value = "clear", required = false) boolean clear,
@RequestParam(value = "thickness", required = false) Integer thickness,
@RequestParam(value = "base", required = false) boolean base,
@RequestParam(value = "colour", required = false) String colour) throws IOException {
final int thicknessInt = ensureCorrectThickness(thickness, ImageProcessingServiceImpl.DEFAULT_THICKNESS_ALLIANCE);
final Color colorObj = ensureCorrectColour(colour, ImageProcessingServiceImpl.DEFAULT_COLOUR_ALLIANCE);
final File image = imageProcessingService.generateAllianceMap(serverId, allianceId, clear, thicknessInt, base, colorObj);
InputStream inputStream = new FileInputStream(image);
return IOUtils.toByteArray(inputStream);
}
@RequestMapping(value=ControllerConstants.URL.Maps.PlayerMap, method = RequestMethod.GET)
public @ResponseBody byte[] playerMapImage(Model model, Principal principal,
@PathVariable(ControllerConstants.URL.PathVariable.ServerID) String serverId,
@PathVariable(ControllerConstants.URL.PathVariable.PlayerID) int playerId,
@RequestParam(value = "clear", required = false) boolean clear,
@RequestParam(value = "thickness", required = false) Integer thickness,
@RequestParam(value = "base", required = false) boolean base,
@RequestParam(value = "colour", required = false) String colour) throws IOException {
final int thicknessInt = ensureCorrectThickness(thickness, ImageProcessingServiceImpl.DEFAULT_THICKNESS_PLAYER);
final Color colorObj = ensureCorrectColour(colour, ImageProcessingServiceImpl.DEFAULT_COLOUR_PLAYER);
final File image = imageProcessingService.generatePlayerMap(serverId, playerId, clear, thicknessInt, base, colorObj);
InputStream inputStream = new FileInputStream(image);
return IOUtils.toByteArray(inputStream);
}
@RequestMapping(value=ControllerConstants.URL.Maps.CastleMap, method = RequestMethod.GET)
public @ResponseBody byte[] castleMapImage(Model model, Principal principal,
@PathVariable(ControllerConstants.URL.PathVariable.ServerID) String serverId,
@PathVariable(ControllerConstants.URL.PathVariable.CastleID) int castleId,
@RequestParam(value = "clear", required = false) boolean clear,
@RequestParam(value = "thickness", required = false) Integer thickness,
@RequestParam(value = "base", required = false) boolean base,
@RequestParam(value = "colour", required = false) String colour) throws IOException {
final int thicknessInt = ensureCorrectThickness(thickness, ImageProcessingServiceImpl.DEFAULT_THICKNESS_CASTLE);
final Color colorObj = ensureCorrectColour(colour, ImageProcessingServiceImpl.DEFAULT_COLOUR_CASTLE);
final File image = imageProcessingService.generateCastleMap(serverId, castleId, clear, thicknessInt, base, colorObj);
InputStream inputStream = new FileInputStream(image);
return IOUtils.toByteArray(inputStream);
}
@RequestMapping(value=ControllerConstants.URL.Maps.CompareMap, method = RequestMethod.GET)
public @ResponseBody byte[] compareMapImage(Model model, Principal principal,
@PathVariable(ControllerConstants.URL.PathVariable.ServerID) String serverId,
@PathVariable(ControllerConstants.URL.PathVariable.CompareMapString) String mapCompareRequestString,
@RequestParam(value = "clear", required = false) boolean clear) throws IOException {
final List<MapCompareRequest> mapCompareRequests = imageProcessingService.decodeMapCompareRequests(mapCompareRequestString);
final File image = imageProcessingService.generateCompareMap(serverId, mapCompareRequests, mapCompareRequestString, clear);
InputStream inputStream = new FileInputStream(image);
return IOUtils.toByteArray(inputStream);
}
private int ensureCorrectThickness(final Integer thickness, final int defaultThickness) {
return thickness!=null?thickness.intValue():defaultThickness;
}
private Color ensureCorrectColour(final String colour, final String defaultColour) {
final String correctColour = colour!=null?colour.toLowerCase():defaultColour;
return new Color(Integer.parseInt(correctColour,16));
}
}
| true
|
dec7a9896d0609230af1771bdb4283deef3b531a
|
Java
|
DCamma/IR-semesterProject
|
/DavideCammarata_IR_SemesterProject/IR-SpringBoot-Lucene/src/main/java/ch/IR/springLucene/response/ErrorResponse.java
|
UTF-8
| 585
| 2.28125
| 2
|
[] |
no_license
|
package ch.IR.springLucene.response;
public class ErrorResponse {
private boolean success;
private String errorMessage;
public ErrorResponse(String errorMessage) {
this.success = false;
this.errorMessage = errorMessage;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| true
|
a5c55ac395944ad5408eebb8b6becf22e24ed1a4
|
Java
|
Spikeify/aerospike-ql
|
/src/test/java/com/spikeify/aerospikeql/generate/functions/GroupReducerTest.java
|
UTF-8
| 3,818
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.spikeify.aerospikeql.generate.functions;
import com.spikeify.aerospikeql.parse.QueryFields;
import com.spikeify.aerospikeql.parse.fields.statements.AggregationStatement;
import com.spikeify.aerospikeql.parse.fields.statements.Statement;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GroupReducerTest {
@Test
public void testGroupBy() {
QueryFields queryFields = new QueryFields();
queryFields.getGroupList().add("timezone");
queryFields.getGroupList().add("timestamp");
GroupReducer groupReducer = GroupReducer.factory(queryFields);
String generatedCode = groupReducer.code;
String expectedCode = "\t\tfor k, v in map.pairs(val2) do\n" +
"\t\t\t-- reduce system diagnostics\n" +
"\t\t\tif k == \"sys_\" then\n" +
"\t\t\t\tif not val1[\"sys_\"] then\n" +
"\t\t\t\t\tval1[\"sys_\"] = map()\n" +
"\t\t\t\t\tval1[\"sys_\"][\"count\"] = 0\n" +
"\t\t\t\tend\n" +
"\t\t\t\tval1[\"sys_\"][\"count\"] = val1[\"sys_\"][\"count\"] + v[\"count\"]\n" +
"\n" +
"\t\t\telse\n" +
"\t\t\t\tval1[k] = v\n" +
"\t\t\tend\n" +
"\t\tend\n" +
"\t\treturn val1\n";
assertEquals(expectedCode, generatedCode);
}
@Test
public void testGroupByWithCounter() {
QueryFields queryFields = new QueryFields();
queryFields.getGroupList().add("timezone");
queryFields.getGroupList().add("timestamp");
queryFields.getSelectField().setAggregations(true);
Statement aggregationStatement = new AggregationStatement.AggregationFieldBuilder("counter", "COUNT").setField("*").createAggregationField();
queryFields.getSelectField().getStatements().add(aggregationStatement);
GroupReducer groupReducer = GroupReducer.factory(queryFields);
String generatedCode = groupReducer.code;
String expectedCode = "\t\tfor k, v in map.pairs(val2) do\n" +
"\t\t\t-- reduce system diagnostics\n" +
"\t\t\tif k == \"sys_\" then\n" +
"\t\t\t\tif not val1[\"sys_\"] then\n" +
"\t\t\t\t\tval1[\"sys_\"] = map()\n" +
"\t\t\t\t\tval1[\"sys_\"][\"count\"] = 0\n" +
"\t\t\t\tend\n" +
"\t\t\t\tval1[\"sys_\"][\"count\"] = val1[\"sys_\"][\"count\"] + v[\"count\"]\n" +
"\n" +
"\t\t\t-- reduce other fields\n" +
"\t\t\telseif val1[k] then\n" +
"\t\t\t\tval1[k][\"counter\"] = val1[k][\"counter\"] + v[\"counter\"]\n" +
"\t\t\telse\n" +
"\t\t\t\tval1[k] = map() \n" +
"\t\t\t\tval1[k][\"timezone\"] = v[\"timezone\"]\n" +
"\t\t\t\tval1[k][\"timestamp\"] = v[\"timestamp\"]\n" +
"\t\t\t\tval1[k][\"counter\"] = v[\"counter\"]\n" +
"\t\t\tend\n" +
"\t\tend\n" +
"\t\treturn val1\n";
assertEquals(expectedCode, generatedCode);
}
@Test
public void testCounter() {
QueryFields queryFields = new QueryFields();
queryFields.getSelectField().setAggregations(true);
Statement aggregationStatement = new AggregationStatement.AggregationFieldBuilder("counter", "COUNT").setField("*").createAggregationField();
queryFields.getSelectField().getStatements().add(aggregationStatement);
GroupReducer groupReducer = GroupReducer.factory(queryFields);
String expectedCode = "\t\tfor k, v in map.pairs(val2) do\n" +
"\t\t\t-- reduce system diagnostics\n" +
"\t\t\tif k == \"sys_\" then\n" +
"\t\t\t\tif not val1[\"sys_\"] then\n" +
"\t\t\t\t\tval1[\"sys_\"] = map()\n" +
"\t\t\t\t\tval1[\"sys_\"][\"count\"] = 0\n" +
"\t\t\t\tend\n" +
"\t\t\t\tval1[\"sys_\"][\"count\"] = val1[\"sys_\"][\"count\"] + v[\"count\"]\n" +
"\n" +
"\t\t\telseif k == \"counter\" then\n" +
"\t\t\t\tval1[k] = (val1[k] or 0) + v\n" +
"\t\t\tend\n" +
"\t\tend\n" +
"\t\treturn val1\n";
assertEquals(expectedCode, groupReducer.code);
}
}
| true
|
bf96c80c249cd303bae9fdf91001179c78701dee
|
Java
|
ctco/cukes
|
/cukes-samples/cukes-rest-sample/src/main/java/lv/ctco/cukes/rest/gadgets/GadgetResource.java
|
UTF-8
| 1,944
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package lv.ctco.cukes.rest.gadgets;
import com.google.inject.Inject;
import lv.ctco.cukes.rest.common.RestUtils;
import lv.ctco.cukes.rest.gadgets.dto.GadgetData;
import lv.ctco.cukes.rest.gadgets.dto.GadgetDto;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Collection;
@SuppressWarnings("SameReturnValue")
@Path(GadgetResource.API)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GadgetResource {
protected static final String API = "/gadgets";
@Inject
DummyGadgetService service;
@Inject
RestUtils rest;
@GET
public Response searchGadgets(@QueryParam("$top") Integer top, @QueryParam("$skip") Integer skip) {
Collection<GadgetDto> gadgets = service.searchGadgets(top, skip);
return rest.ok(new GadgetData(gadgets));
}
@GET
@Path("{id}")
public Response getGadget(@PathParam("id") Integer id) {
GadgetDto gadget = service.getGadget(id);
if (gadget == null) {
return rest.notFound();
}
return rest.ok(gadget);
}
@POST
public Response addGadget(GadgetDto gadget) {
Integer id = service.addGadget(gadget);
if (id == null) {
return rest.badRequest("Could not add new Gadget");
}
return rest.created(id, API);
}
@PUT
@Path("{id}")
public Response updateGadget(@PathParam("id") Integer id, GadgetDto gadget) {
boolean result = service.updateGadget(id, gadget);
if (!result) {
return rest.badRequest("Could not update Gadget with ID: " + id);
}
return rest.ok();
}
@DELETE
@Path("{id}")
public Response removeGadget(@PathParam("id") Integer id) {
boolean result = service.removeGadget(id);
if (!result) {
return rest.notFound();
}
return rest.ok();
}
}
| true
|
e7557b4d366ee375146bd7829dd6c953fcbab78e
|
Java
|
justidu/books_management
|
/src/com/Dao/Impl/AdminDaoImpl.java
|
UTF-8
| 545
| 2.390625
| 2
|
[] |
no_license
|
package com.Dao.Impl;
import java.util.ArrayList;
import java.util.List;
import com.Dao.AdminDao;
import com.Entity.Admin;
/**
* 管理员数据访问接口 实现类
* @author songdu
*
*/
public class AdminDaoImpl implements AdminDao {
List<Admin> adminList = new ArrayList<Admin>();
public void init() {
Admin adm1 = new Admin(1, "admin", "123456");
adminList.add(adm1);
}
@Override
public List<Admin> AdminList() {
return adminList;
}
@Override
public boolean insert(Admin admin) {
return adminList.add(admin);
}
}
| true
|
6666f19708b1fccbddbbf2ab239eb530c8bbd209
|
Java
|
waqarys/Java
|
/Java-Coding-Problems/src/arrays/sort/CountingSort.java
|
UTF-8
| 847
| 3.375
| 3
|
[] |
no_license
|
package arrays.sort;
//https://learning.oreilly.com/library/view/java-coding-problems/9781789801415/assets/570e8015-a037-48d9-b4f9-459a694b73ee.png
public class CountingSort {
public static void countingSort(int[] arr) {
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
} else if (arr[i] > max) {
max = arr[i];
}
}
int[] counts = new int[max - min + 1];
for (int i = 0; i < arr.length; i++) {
counts[arr[i] - min]++;
}
int sortedIndex = 0;
for (int i = 0; i < counts.length; i++) {
while (counts[i] > 0) {
arr[sortedIndex++] = i + min;
counts[i]--;
}
}
}
}
| true
|
49801c0ca55c5a59f15b8f97d1a149c55050b083
|
Java
|
learn2j-code/xupu-urm
|
/src/com/bjp/bam_menumanagement/vo/ResponseMenuEntity.java
|
UTF-8
| 538
| 1.695313
| 2
|
[] |
no_license
|
package com.bjp.bam_menumanagement.vo;
import java.util.List;
import com.bjp.bam_basemanagement.vo.ResponseEntity;
import com.bjp.constant.CommonConstant;
import com.bjp.pojo.RoleMenuRel;
import com.bjp.pojo.UserInfo;
public class ResponseMenuEntity extends ResponseEntity{
private List<RoleMenuRel> roleMenuRelList;
public List<RoleMenuRel> getRoleMenuRelList() {
return roleMenuRelList;
}
public void setRoleMenuRelList(List<RoleMenuRel> roleMenuRelList) {
this.roleMenuRelList = roleMenuRelList;
}
}
| true
|
cef391e3741e89f04d6c9fd8a8527fb955dc2ab3
|
Java
|
tlhhup/springboot-2.0.x
|
/chapter-9/src/main/java/org/tlh/rpc/core/EnableRpcClients.java
|
UTF-8
| 660
| 1.617188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.tlh.rpc.core;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by 离歌笑tlh/hu ping on 2019/2/11
* <p>
* Github: https://github.com/tlhhup
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(RpcClientRegistrar.class)
public @interface EnableRpcClients {
@AliasFor("basePackages")
String[] value() default {};
@AliasFor("value")
String[] basePackages() default {};
}
| true
|
8132fc20786f550785d4868bd8578b2c8d0a4e62
|
Java
|
GuoDongAp/Day01
|
/text1/src/main/java/com/example/text1/fragment/ClockFragment.java
|
UTF-8
| 3,108
| 2.078125
| 2
|
[] |
no_license
|
package com.example.text1.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.text1.R;
import com.example.text1.adapter.ClockAdapter;
import com.example.text1.bean.DbBean;
import com.example.text1.contract.ClockContract;
import com.example.text1.model.ClockModel;
import com.example.text1.presenter.ClockPresenter;
import java.util.ArrayList;
import java.util.List;
public class ClockFragment extends Fragment implements ClockContract.View {
private View view;
private RecyclerView mRlv;
private ClockPresenter mPresenter;
private List<DbBean> mList = new ArrayList<>();
private ClockAdapter mAdapter;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
initData();
}else {
mList.clear();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_clock, container, false);
mPresenter = new ClockPresenter(new ClockModel(), this);
initView(inflate);
return inflate;
}
private void initData() {
mPresenter.query();
}
private void initView(View inflate) {
mRlv = (RecyclerView) inflate.findViewById(R.id.rlv);
mRlv.setLayoutManager(new LinearLayoutManager(getContext()));
mAdapter = new ClockAdapter(getContext(), mList);
mRlv.setAdapter(mAdapter);
mAdapter.setOnClickListener(new ClockAdapter.onClickListener() {
@Override
public void onClick(DbBean bean, int position) {
mPresenter.delete(bean);
mAdapter.getList().remove(bean);
mAdapter.notifyDataSetChanged();
}
});
mAdapter.setOnLongClickListenr(new ClockAdapter.onLongClickListenr() {
@Override
public void onLongClick(DbBean bean, int position) {
bean.setDase("阿花");
mPresenter.update(bean);
mAdapter.getList().set(position,bean);
mAdapter.notifyDataSetChanged();
}
});
}
@Override
public void onQuerySuccess(List<DbBean> list) {
mList.addAll(list);
mAdapter.setList(mList);
mAdapter.notifyDataSetChanged();
}
@Override
public void onQueryFial(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onDelete(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onUpdate(String msg) {
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
}
}
| true
|
cdd9e44aa92fdd75081bd9bb53bb9cb94172ce3e
|
Java
|
maheswar333/vinay-app-telugu-full
|
/TestFirebase/app/src/main/java/main/com/dvb/SplashScreen.java
|
UTF-8
| 1,208
| 1.945313
| 2
|
[] |
no_license
|
package main.com.dvb;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
/**
* Created by AIA on 8/16/16.
*/
public class SplashScreen extends AppCompatActivity{
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "rs2jjzShvGV47MidZZVlNjzAO";
private static final String TWITTER_SECRET = "WUcR1u1AeLhC0KRAxf3Sc3jJoPSGAaUUTvfWPJQOgLY3t9YOCS";
private static int SPLASH_TIME_OUT = 4000;
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashScreen.this, Dashboard_main.class);
startActivity(intent);
finish();
}
};
handler.postDelayed(runnable, SPLASH_TIME_OUT);
}
@Override
public void onBackPressed() {
// super.onBackPressed();
}
}
| true
|
a52ef1cdd0e1fa12ed21a5e6dfe2c9641282ec96
|
Java
|
DanyloZasymenko/alloiz-server
|
/src/main/java/com/alloiz/alloizserver/dto/ImageDto.java
|
UTF-8
| 999
| 2.4375
| 2
|
[] |
no_license
|
package com.alloiz.alloizserver.dto;
import com.alloiz.alloizserver.dto.utils.annotations.Dto;
@Dto
public class ImageDto {
protected String path;
protected Long id;
protected String name;
protected Boolean available;
public String getPath() {
return path;
}
public ImageDto setPath(String path) {
this.path = path;
return this;
}
public Long getId() {
return id;
}
public ImageDto setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public ImageDto setName(String name) {
this.name = name;
return this;
}
public Boolean getAvailable() {
return available;
}
public ImageDto setAvailable(Boolean available) {
this.available = available;
return this;
}
@Override
public String toString() {
return "ImageDto{" +
"path='" + path + '\'' +
", id=" + id +
", name='" + name + '\'' +
", available=" + available +
'}';
}
}
| true
|
37efa1ed0e0e1e780fa119ff65c6127951566162
|
Java
|
wangread-git/web-study
|
/web-study-domain/src/main/java/com/wangread/webstudy/domain/redis/SentinelChannelEnum.java
|
UTF-8
| 665
| 2.5625
| 3
|
[] |
no_license
|
package com.wangread.webstudy.domain.redis;
/**
* Created by yfwangrui on 2015/8/13.
*
* sentinel channel enum
*/
public enum SentinelChannelEnum {
SWITCH_MASTER("+switch-master"),
ADD_SLAVE("+slave");
private String channel;
SentinelChannelEnum(String channel) {
this.channel = channel;
}
public String getChannel() {
return channel;
}
public static SentinelChannelEnum valueOfChannel(String channel) {
for (SentinelChannelEnum enm : SentinelChannelEnum.values()) {
if (enm.getChannel().equals(channel)) {
return enm;
}
}
return null;
}
}
| true
|
2051b32d63e917a87b9d3df67c7a55407e711971
|
Java
|
gomesgr/sp-boot
|
/src/main/java/com/example/demoproject/aprendendo/dao/UsuarioJPA.java
|
UTF-8
| 260
| 1.625
| 2
|
[] |
no_license
|
package com.example.demoproject.aprendendo.dao;
import com.example.demoproject.aprendendo.model.Usuario;
import org.springframework.data.repository.CrudRepository;
import java.util.UUID;
public interface UsuarioJPA extends CrudRepository<Usuario, UUID> {
}
| true
|
119cea6406dcb50fb7aa311a0c2d51c6ab7231e3
|
Java
|
distributedlife/sightings
|
/src/com/distributedlife/animalwiki/clickaction/SeenIt.java
|
UTF-8
| 844
| 2.859375
| 3
|
[] |
no_license
|
package com.distributedlife.animalwiki.clickaction;
import android.view.View;
import com.distributedlife.animalwiki.activities.AnimalDisplay;
import com.distributedlife.animalwiki.db.Sightings;
import com.distributedlife.animalwiki.model.Animal;
public class SeenIt implements View.OnClickListener {
private AnimalDisplay animalDisplay;
private Sightings sightings;
private Animal animal;
public SeenIt(AnimalDisplay animalDisplay, Sightings sightings, Animal animal) {
this.animalDisplay = animalDisplay;
this.sightings = sightings;
this.animal = animal;
}
@Override
public void onClick(View view) {
if (sightings.hasSighting(animal)) {
sightings.remove(animal);
} else {
sightings.add(animal);
}
animalDisplay.refresh();
}
}
| true
|
b3e0592f08fd32da79105449c0aadcc66b2483ad
|
Java
|
sunyaqin413/JCEX
|
/app/build/generated/source/apt/debug/cn/jcex/ui/fragment/mine/MyOrdersFragment_ViewBinder.java
|
UTF-8
| 503
| 1.8125
| 2
|
[] |
no_license
|
// Generated code from Butter Knife. Do not modify!
package cn.jcex.ui.fragment.mine;
import butterknife.Unbinder;
import butterknife.internal.Finder;
import butterknife.internal.ViewBinder;
import java.lang.Object;
import java.lang.Override;
public final class MyOrdersFragment_ViewBinder implements ViewBinder<MyOrdersFragment> {
@Override
public Unbinder bind(Finder finder, MyOrdersFragment target, Object source) {
return new MyOrdersFragment_ViewBinding<>(target, finder, source);
}
}
| true
|
73eb68b449e675ef814f9a23be0ef2c8a75ecc4e
|
Java
|
celineellenanna/QFS-App
|
/app/src/main/java/ch/hsr/qfs/domain/Answer.java
|
UTF-8
| 535
| 2.1875
| 2
|
[] |
no_license
|
package ch.hsr.qfs.domain;
public class Answer {
private String _id;
private String text;
private boolean correct;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public boolean isCorrect() {
return correct;
}
public void setCorrect(boolean correct) {
this.correct = correct;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| true
|
898eb7be8aa4f34cd60d06b26c1ee3d1a0e055bb
|
Java
|
dbcd/Java
|
/ProyectoNumeroMayor/src/edu/femxa/val/CalcularNumeroMayor.java
|
UTF-8
| 1,611
| 3.59375
| 4
|
[] |
no_license
|
package edu.femxa.val;
import java.util.Scanner;
public class CalcularNumeroMayor {
public static float pedirNumeroFloat(){
float num_leido=0;
Scanner scanner= new Scanner(System.in);//Declaro un objeto scanner para leer de teclado.(entrada estandar).
num_leido= scanner.nextFloat();//Leo del teclado y asigno el valor num_leido.
return num_leido;
}
public static void compararNumero (float a, float b ,float c){
if ((a > b)&&(a>c))
System.out.println("mayor es "+a);
else if ((b > a) && (b >c)) {
System.out.println("mayor "+b);
} else if ((c >a) && (c > b)) {
System.out.println("mayor "+c);
}
if((a < b)&&(a<c)){
System.out.println("menor es "+a);
}
else if ((b < a) && (b <c)) {
System.out.println("menor "+b);
} else if ((c <a) && (c < b)) {
System.out.println("menor "+c);
}else {
System.out.println("Son iguales");
}
}
public static void main(String[] args) {
/* float a=0;
float b=0;
float c=0;
a =pedirNumeroFloat();
b=pedirNumeroFloat();
c=pedirNumeroFloat();
compararNumero(a,b,c);
*/
float numero_leido=0;
float numero_mayor=0;
for(int i =0;i<10;i++){
//inicio
System.out.println("Introducir Numeros"+ (i+1));
numero_leido=pedirNumeroFloat();
if(numero_leido>numero_mayor){
numero_mayor=numero_leido;
}
}//
//System.out.println("Ha pedido todos ");
System.out.println("Numero Mayor "+numero_mayor);
}
}
| true
|
0826d0debc7a9241cbe13e157a7ae9ada9c08bca
|
Java
|
RehaniH/Group8A
|
/app/src/main/java/com/example/group8a/DisplayProductActivity.java
|
UTF-8
| 3,258
| 2.109375
| 2
|
[] |
no_license
|
package com.example.group8a;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
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.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
public class DisplayProductActivity extends AppCompatActivity {
TextView name, color, quantity;
ImageView imageView;
private DatabaseReference databaseReference;
private FirebaseStorage storage;
String imageUri;
private FirebaseDatabase database ;
private DatabaseReference mReference ;
private DatabaseReference childReference ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_product);
Intent intent = getIntent();
String key = intent.getStringExtra("Key");
name = findViewById(R.id.display_name);
color = findViewById(R.id.display_color);
quantity = findViewById(R.id.display_quantity);
imageView = findViewById(R.id.display_item);
final Context context = this;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Items").child(key);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
imageUri = dataSnapshot.child("mUri").getValue().toString();
name.setText(dataSnapshot.child("name").getValue().toString());
color.setText(dataSnapshot.child("color").getValue().toString());
quantity.setText(dataSnapshot.child("quantity").getValue().toString());
Picasso.with(context).load(imageUri).placeholder(R.drawable.ic_image_black_24dp).fit().centerCrop().into(imageView);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(DisplayProductActivity.this, "Cannot load product", Toast.LENGTH_SHORT).show();
}
});
//Glide.with(getApplicationContext()).load(imageUri).into(imageView);
//Picasso.with(this).load(imageUri).placeholder(R.mipmap.ic_launcher).fit().centerCrop().into(imageView);
/* Context context = this;
// place here
database = FirebaseDatabase.getInstance();
mReference = database.getReference("Items");
childReference = mReference.child(key);
*/
}//end of on create method
/*@Override
protected void onStart() {
super.onStart();
}*/
}
| true
|
7cd9f236fcc7351d8808ad6a08e2cbd8f402b5ae
|
Java
|
jcadler/GoingRogue
|
/src/edu/brown/cs32/bweedon/geometry/Hypersphere.java
|
UTF-8
| 4,748
| 3.40625
| 3
|
[] |
no_license
|
package edu.brown.cs32.bweedon.geometry;
import java.util.Objects;
/**
* a class representing an n-dimensional Hypersphere;
*
* @author Ben Weedon (bweedon)
*/
public class Hypersphere implements Hypershape {
private OrderedTuple center_;
private double radius_;
/**
* constructs a Hypersphere with the specified center and radius
*
* @param center an OrderedTuple representing the center of this Hypersphere
* @param radius the radius of this Hypersphere
*/
public Hypersphere(OrderedTuple center, double radius) {
center_ = center;
radius_ = radius;
}
/**
* determines if the specified OrderedTuple is inside this Hypersphere
*
* @param tuple an OrderedTuple
* @return true if the specified OrderedTuple is inside or exactly on the
* border of this Hypersphere, false if not
*/
@Override
public boolean tupleInShape(OrderedTuple tuple) {
if (center_.getDimensions() != tuple.getDimensions()) {
throw new Error("The number of dimensions in this OrderedTuple is not"
+ " equal to the number of dimensions in the Hypersphere.");
}
return (center_.distance(tuple) <= radius_);
}
/**
* determines if this Hypersphere intersects with the specified
* Hyperrectangle
*
* @param rec a Hyperrectangle of the same dimensions as this Hypersphere
* @return true if this Hypersphere crosses the borders of or touches the
* borders of the specified Hyperrectangle, false if not
*/
public boolean intersectsHyperrectangle(Hyperrectangle rec) {
if (center_.getDimensions() != rec.getDimensions()) {
throw new Error("The number of dimensions in this Hypersphere is not"
+ " equal to the number of dimensions in the given Hyperrectangle.");
}
OrderedTuple closestPoint = new ArrayOrderedTuple(new double[center_.getDimensions()]);
// determine each dimension of the closest point on the
// Hyperrectangle's edge to this Hypersphere
for (int i = 0; i < center_.getDimensions(); ++i) {
double cent = center_.getValue(i);
double recMin = rec.getMinPoint().getValue(i);
double recMax = rec.getMaxPoint().getValue(i);
if (cent <= recMin) {
closestPoint.setValue(i, recMin);
} else if ((cent > recMin) && (cent < recMax)) {
closestPoint.setValue(i, cent);
} else if (cent >= recMax) {
closestPoint.setValue(i, recMax);
}
}
// return whether this closest point is within the Hypersphere's radius
return (center_.distance(closestPoint) <= radius_);
}
/**
* gets the dimensions of this Hypersphere
*
* @return the number of dimensions in this Hypersphere
*/
@Override
public int getDimensions() {
return center_.getDimensions();
}
/**
* gets the center of this Hypersphere
*
* @return an OrderedTuple representing the center of this Hypersphere
*/
public OrderedTuple getCenter() {
return center_;
}
/**
* sets the center of this Hypersphere
*
* @param center an OrderedTuple which will become the new center of this
* Hypersphere
*/
public void setCenter(OrderedTuple center) {
center_ = center;
}
/**
* gets the radius of this Hypersphere
*
* @return the radius of this Hypersphere
*/
public double getRadius() {
return radius_;
}
/**
* sets the radius of this Hypersphere
*
* @param radius the new radius of this Hypersphere
*/
public void setRadius(double radius) {
radius_ = radius;
}
@Override
public String toString() {
return "Hypersphere{" + "center_=" + center_ + ", radius_=" + radius_ + '}';
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Hypersphere) {
return center_.equals(((Hypersphere) obj).getCenter())
&& (radius_ == ((Hypersphere) obj).getRadius());
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 43 * hash + Objects.hashCode(this.center_);
hash = 43 * hash + (int) (Double.doubleToLongBits(this.radius_) ^ (Double.doubleToLongBits(this.radius_) >>> 32));
return hash;
}
}
| true
|
aebe6cefef17b83778b3c39ffbf4f9057cd3b03a
|
Java
|
dragonwzj/hsweb-framework
|
/hsweb-system/hsweb-system-workflow/hsweb-system-workflow-flowable/src/test/java/org/hswebframework/web/workflow/flowable/test/ServiceTest.java
|
UTF-8
| 1,447
| 1.796875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.hswebframework.web.workflow.flowable.test;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.hswebframework.web.workflow.flowable.service.BpmActivityService;
import org.hswebframework.web.workflow.flowable.utils.FlowableAbstract;
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.util.List;
/**
* Created by zhouhao on 2017/7/20.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest extends FlowableAbstract {
@Autowired
BpmActivityService bpmActivityService;
@Test
public void getProcessDefinition(){
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("test").singleResult();
System.out.println(processDefinition);
}
@Test
public void getHiTask(){
//查出历史信息
HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId("5").taskAssignee("admin").singleResult();
Task task = taskService.createTaskQuery().taskId("123456").singleResult();
}
}
| true
|
1749bd9d1dea4c232c43c2be15ea7d95767eb153
|
Java
|
DanielParra05/ElectricToolsSpring
|
/src/main/java/com/spring/electric/tools/models/enums/OrderStatus.java
|
UTF-8
| 337
| 2.625
| 3
|
[] |
no_license
|
package com.spring.electric.tools.models.enums;
/**
* Clase para indicar el estado de una orden
*
* @author Jose Daniel Parra
*/
public enum OrderStatus {
EN_REPARACION("En reparación"), LISTO("Listo");
private String valor;
private OrderStatus(String valor) {
this.valor = valor;
}
public String getValor() {
return valor;
}
}
| true
|
8d8da1a99a94d001870b3a2b4c63f103fd0fc91c
|
Java
|
ChaozhiMobile/Chaozhi_Android
|
/app/src/main/java/com/czjy/chaozhi/presenter/main/contract/MineContract.java
|
UTF-8
| 607
| 2
| 2
|
[] |
no_license
|
package com.czjy.chaozhi.presenter.main.contract;
import com.czjy.chaozhi.base.IBaseView;
import com.czjy.chaozhi.base.IPresenter;
import com.czjy.chaozhi.model.bean.NotifyBean;
import com.czjy.chaozhi.model.bean.PurchaseBean;
import com.czjy.chaozhi.model.bean.UserBean;
/**
* Created by huyg on 2018/9/29.
*/
public interface MineContract {
interface View extends IBaseView{
void showUserInfo(UserBean userBean);
void showNotifyInfo(NotifyBean notifyBean);
}
interface Presenter extends IPresenter<View>{
void getUserInfo();
void getNotifyInfo();
}
}
| true
|
3c2357e70a97081fc85e427d68b191b20baa49f2
|
Java
|
jianglei260/TravelNote
|
/app/src/main/java/cn/edu/cuit/wsy/travelnote/login/LoginViewModel.java
|
UTF-8
| 3,185
| 2
| 2
|
[] |
no_license
|
package cn.edu.cuit.wsy.travelnote.login;
import android.content.Intent;
import android.databinding.ObservableField;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.avos.avoscloud.AVObject;
import cn.edu.cuit.wsy.travelnote.R;
import cn.edu.cuit.wsy.travelnote.base.DetailViewModel;
import cn.edu.cuit.wsy.travelnote.data.entity.User;
import cn.edu.cuit.wsy.travelnote.data.repository.UserRepository;
import cn.edu.cuit.wsy.travelnote.main.MainActivity;
import cn.edu.cuit.wsy.travelnote.utils.IOTask;
import cn.edu.cuit.wsy.travelnote.utils.RxUtil;
import cn.edu.cuit.wsy.travelnote.utils.UIAction;
/**
* Created by jianglei on 2017/4/16.
*/
public class LoginViewModel extends DetailViewModel {
private static final String TAG = "LoginViewModel";
public OnClickListener signClick = new OnClickListener() {
public void onClick(View var1) {
onSignClick();
}
};
public ObservableField<String> account = new ObservableField<String>();
public OnClickListener loginClick = new OnClickListener() {
public void onClick(View var1) {
onLoginClick();
}
};
public OnClickListener testClick = new OnClickListener() {
public void onClick(View var1) {
// onTestClick();
}
};
public ObservableField<String> password = new ObservableField<String>();
private UserLoginActivity userLoginActivity;
public LoginViewModel(UserLoginActivity userLoginActivity) {
this.userLoginActivity = userLoginActivity;
title.set("用户登录");
}
public void onLoginClick() {
if (TextUtils.isEmpty(account.get())) {
Toast.makeText(userLoginActivity, R.string.account_empty, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password.get())) {
Toast.makeText(userLoginActivity, R.string.password_empty, Toast.LENGTH_SHORT).show();
return;
}
loadding.set(true);
RxUtil.execute(new IOTask<User>() {
@Override
public User run() {
return UserRepository.getInstance().login(account.get(), password.get());
}
}, new UIAction<User>() {
@Override
public void onComplete(User user) {
loadding.set(false);
if (user!=null){
Intent intent=new Intent(userLoginActivity, MainActivity.class);
userLoginActivity.startActivity(intent);
userLoginActivity.publishEvent(MainActivity.ACTION_USER_LOGIN);
userLoginActivity.finish();
}else {
Toast.makeText(userLoginActivity, R.string.login_failed, Toast.LENGTH_SHORT).show();
}
}
});
}
public void gotoUserSignActivity() {
Intent intent = new Intent(userLoginActivity, UserSignActivity.class);
userLoginActivity.startActivity(intent);
}
public void onSignClick() {
gotoUserSignActivity();
}
}
| true
|
68b8047f32725f9927c82fad2b464fbacfb23e23
|
Java
|
weirdNox/sempreahoras
|
/app/app/src/main/java/com/sempreahoras/app/App.java
|
UTF-8
| 1,242
| 2.28125
| 2
|
[] |
no_license
|
package com.sempreahoras.app;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
public class App extends Application {
static final String CHANNEL1_ID = "sempreahoras_notifs!";
static final String CHANNEL2_ID = "sempreahoras_notifs2";
static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel1 = new NotificationChannel(CHANNEL1_ID, "Sempre a Horas", importance);
NotificationChannel channel2 = new NotificationChannel(CHANNEL2_ID, "Sempre a Horas", importance);
channel2.setVibrationPattern(new long[] {0,300,300,300,600,300,300,300,300,300,300,300,300,250,50,550,50,200});
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel1);
notificationManager.createNotificationChannel(channel2);
}
}
}
| true
|
b2606900b1c4cd7de601fedb2f8d220d2d465a54
|
Java
|
VasiliyZhigalov/otus_java_2019_12
|
/hw09-DiyORM/src/main/java/com/vasiliyzhigalov/core/service/DbServiceEntityImpl.java
|
UTF-8
| 2,212
| 2.34375
| 2
|
[] |
no_license
|
package com.vasiliyzhigalov.core.service;
import com.vasiliyzhigalov.core.model.User;
import com.vasiliyzhigalov.core.sessionmanager.SessionManager;
import com.vasiliyzhigalov.jdbc.dao.DAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
public class DbServiceEntityImpl<T> implements DBServiceEntity<T> {
private static Logger logger = LoggerFactory.getLogger(DbServiceEntityImpl.class);
private final DAO dao;
public DbServiceEntityImpl(DAO dao) {
this.dao = dao;
}
@Override
public void create(T objectData) {
try (SessionManager sessionManager = dao.getSessionManager()) {
sessionManager.beginSession();
try {
dao.create(objectData);
sessionManager.commitSession();
logger.info("created objectData: {}", objectData);
} catch (Exception e) {
logger.error(e.getMessage(), e);
sessionManager.rollbackSession();
throw new DbServiceException(e);
}
}
}
@Override
public void update(T objectData) {
try (SessionManager sessionManager = dao.getSessionManager()) {
sessionManager.beginSession();
try {
dao.update(objectData);
sessionManager.commitSession();
logger.info("update objectData: {}", objectData);
} catch (Exception e) {
logger.error(e.getMessage(), e);
sessionManager.rollbackSession();
throw new DbServiceException(e);
}
}
}
@Override
public Optional<T> load(long id, Class<T> clazz) {
try (SessionManager sessionManager = dao.getSessionManager()) {
sessionManager.beginSession();
try {
Optional<T> tOptional = (Optional<T>) dao.load(id, clazz);
logger.info("user: {}", tOptional);
return tOptional;
} catch (Exception e) {
logger.error(e.getMessage(), e);
sessionManager.rollbackSession();
}
return Optional.empty();
}
}
}
| true
|
9c6bc13c36de0dba5fe7bea2f247c7934c7bc9b7
|
Java
|
botondsulyok/projlab-2020-icefield
|
/src/hu/minesweepers/modell/command/commands/StormCommand.java
|
UTF-8
| 1,057
| 2.8125
| 3
|
[] |
no_license
|
package hu.minesweepers.modell.command.commands;
import hu.minesweepers.modell.character.Character;
import hu.minesweepers.modell.command.CommandUtils;
import hu.minesweepers.modell.tile.IceUnit;
/**
* A statikus osztálynak az egyetlen felelőssége kezelni a "storm" parancsot.
*/
public class StormCommand {
/**
* Ez a függvény oldja meg a "storm" parancsot. A paranccsal egy viharral rásújthatunk egy karakterre vagy egy jégtáblára.
* @param ID A karakter vagy a jégtábla azonosítója.
* @return Visszadja, hogy a parancs sikeresen lefutott vagy sem. Akkor nem sikeres, hogyha nem jó azonosítót adtunk meg a parancs argumentumában.
*/
public static boolean storm(String ID) {
Character c = CommandUtils.getCharacter(ID);
IceUnit iu = CommandUtils.getIceUnit(ID);
if (c != null) {
c.struckByDisaster();
}
else if (iu != null) {
iu.struckByDisaster();
}
else {
return false;
}
return true;
}
}
| true
|
8287dcf4581dcc111f6de2f57aec48408338b7b3
|
Java
|
Danielliudov/My-first-OOP-project
|
/src/Creatures/Race.java
|
UTF-8
| 84
| 1.789063
| 2
|
[] |
no_license
|
package Creatures;
public enum Race {
HUMAN, ORC, UNDEAD, ELF, DWARF, TROLL,
}
| true
|
57cb05810972b3d402df85bc33d7ada101d41d66
|
Java
|
zstu-xq/ly
|
/leyou-order/src/main/java/com/leyou/order/dto/AddressDTO.java
|
UTF-8
| 365
| 1.765625
| 2
|
[] |
no_license
|
package com.leyou.order.dto;
import lombok.Data;
@Data
public class AddressDTO {
Long id;
String name;
String phone;
private String state; //省份
private String city;
private String district; //区
private String address; //街道地址
private String zipCode; //邮编
private Boolean isDefault; //是否默认地址
}
| true
|
dcac13f3e57b3dbfc24ee38c7daa92f46d169468
|
Java
|
Sepehr79/Spring_REST
|
/src/main/java/com/luv2code/springdemo/controller/CustomerRestController.java
|
UTF-8
| 2,462
| 2.421875
| 2
|
[] |
no_license
|
package com.luv2code.springdemo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.luv2code.springdemo.controller.exception.CustomerNotFoundException;
import com.luv2code.springdemo.controller.pojo.CustomerRequest;
import com.luv2code.springdemo.entity.Customer;
import com.luv2code.springdemo.service.CustomerService;
@RestController
@RequestMapping("/api")
public class CustomerRestController {
@Autowired
private CustomerService service;
@GetMapping("/customers")
public List<Customer> getCustomers(){
return service.getCustomers();
}
@GetMapping("/customers/{customerId}")
public Customer getCustomer(@PathVariable int customerId) {
Customer customer;
try {
customer = service.getCustomer(customerId);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad input");
}
if (customer == null) {
throw new CustomerNotFoundException("Customer not found with the given id");
}
return customer;
}
@PostMapping("/customers")
public Customer saveCustomer(@RequestBody CustomerRequest customerRequest) {
Customer customer = new Customer(customerRequest.getFirstName(), customerRequest.getLastName(), customerRequest.getEmail());
service.saveCustomer(customer);
return customer;
}
@PutMapping("/customers")
public Customer updateCustomer(@RequestBody Customer customer) {
service.saveCustomer(customer);
return customer;
}
@DeleteMapping("/customers/{customerId}")
public String deleteCustomer(@PathVariable int customerId) {
Customer theCustomer;
try {
theCustomer = service.getCustomer(customerId);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad input");
}
if (theCustomer == null) {
throw new CustomerNotFoundException("Customer not found with the given id");
}
service.deleteCustomer(customerId);
return "Customer deleted with id: " + customerId;
}
}
| true
|
248cde74c2a3f00e80e119398fd12e3887843b73
|
Java
|
Pashkou/PayRoll
|
/PayRollSystem/src/main/java/usecases/operations/datastructures/PayEmployeeRequest.java
|
UTF-8
| 216
| 1.921875
| 2
|
[] |
no_license
|
package usecases.operations.datastructures;
import java.time.LocalDate;
public class PayEmployeeRequest extends Request {
private LocalDate date;
public LocalDate getDate() {
return date;
}
}
| true
|
44487a8887d2abacb3f9d8e19a19fee839b6c397
|
Java
|
gowthamkg11/Trailblaze
|
/app/src/main/java/com/ft08/trailblazelearn/adapters/PagerAdapter.java
|
UTF-8
| 951
| 2.4375
| 2
|
[] |
no_license
|
package com.ft08.trailblazelearn.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.ft08.trailblazelearn.fragments.StationFragment;
import com.ft08.trailblazelearn.fragments.LocationsFragment;
public class PagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
@Override public Fragment getItem(int position) {
switch (position) {
case 0:
StationFragment stationFragment = new StationFragment();
return stationFragment;
default:
LocationsFragment mapFragment = new LocationsFragment();
return mapFragment;
}
}
@Override public int getCount() {
return numOfTabs;
}
}
| true
|
02e870086af7274d0516d8e54d15af612f088715
|
Java
|
BluSunrize/ImmersiveEngineering
|
/src/main/java/blusunrize/immersiveengineering/common/util/commands/MineralArgument.java
|
UTF-8
| 2,341
| 2.3125
| 2
|
[
"CC-BY-4.0"
] |
permissive
|
package blusunrize.immersiveengineering.common.util.commands;
import blusunrize.immersiveengineering.ImmersiveEngineering;
import blusunrize.immersiveengineering.api.Lib;
import blusunrize.immersiveengineering.api.excavator.MineralMix;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.Level;
import net.minecraftforge.server.ServerLifecycleHooks;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
// TODO fix static level access hacks
public class MineralArgument implements ArgumentType<MineralMix>
{
public static final DynamicCommandExceptionType invalidVein = new DynamicCommandExceptionType(
(input) -> Component.translatable(Lib.CHAT_COMMAND+"mineral.invalid", input));
@Override
public MineralMix parse(StringReader reader) throws CommandSyntaxException
{
String name = reader.readQuotedString();//TODO does this work properly?
for(MineralMix mm : getStaticMinerals())
if(mm.getId().toString().equalsIgnoreCase(name))
return mm;
throw invalidVein.create(name);
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder)
{
return SharedSuggestionProvider.suggest(getStaticMinerals().stream().map(mix -> "\""+mix.getId()+"\""), builder);
}
@Override
public Collection<String> getExamples()
{
List<String> ret = new ArrayList<>();
for(MineralMix mix : getStaticMinerals())
{
ret.add("\""+mix.getId()+"\"");
if(ret.size() > 5)
break;
}
return ret;
}
private Collection<MineralMix> getStaticMinerals()
{
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
Level level = server==null?ImmersiveEngineering.proxy.getClientWorld(): server.overworld();
return MineralMix.RECIPES.getRecipes(level);
}
}
| true
|
3b6a52e3759e258c252a4ac45a76a36c5a9e40e8
|
Java
|
DeanHe/Practice
|
/LeetCodePractice/src/binarySearch/ClosestTargetValue.java
|
UTF-8
| 1,060
| 4.0625
| 4
|
[] |
no_license
|
package binarySearch;
import java.util.*;
/*
Given an array, find two numbers in the array and their sum is closest to the target value but does not exceed the target value, return their sum.
*/
public class ClosestTargetValue {
/**
* @param target: the target
* @param array: an array
* @return: the closest value
*/
public int closestTargetValue(int target, int[] array) {
// Write your code here
Arrays.sort(array);
int i = 0, j = array.length - 1;
int closest = Integer.MIN_VALUE;
while(i < j){
if(array[i] + array[j] < target){
closest = Math.max(closest, array[i] + array[j]);
i++;
} else if(array[i] + array[j] == target){
closest = array[i] + array[j];
return closest;
} else {
j--;
}
}
if(closest == Integer.MIN_VALUE){
return -1;
} else {
return closest;
}
}
}
| true
|
05e6288b60cbada5cfda914852747173f2045a5d
|
Java
|
jerrymousefxd/sys-parent
|
/sys-provider/src/main/java/com/eaju/appservice/ITbOrderService.java
|
UTF-8
| 448
| 1.804688
| 2
|
[] |
no_license
|
package com.eaju.appservice;
import java.util.List;
import com.eaju.entity.TbOrder;
public interface ITbOrderService {
/**
* 批量插入订单
* @param tbOrder
* @return
*/
int insertTbOrder(List<TbOrder> tbOrders);
List<TbOrder> findTbOrder(TbOrder tbOrder);
/**
* 老系统app中fbs单子写入8182定时器调用
* @return
*/
void insertOrderByFindFromAppFbs(String beginTime,String endTime);
}
| true
|
19b6cecac37a787c9eee0fb61950ecb2a6870753
|
Java
|
caf3sua/agency-service
|
/agency-src/com/baoviet/agency/web/rest/vm/PremiumSKTDVM.java
|
UTF-8
| 1,859
| 1.632813
| 2
|
[] |
no_license
|
package com.baoviet.agency.web.rest.vm;
import java.util.Date;
import com.baoviet.agency.utils.DateSerializer;
import com.baoviet.agency.utils.DoubleSerializer;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class PremiumSKTDVM {
private String chuongTrinh;
@JsonSerialize(using = DateSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date ngaysinh;
private Boolean ngoaitruChk;
@JsonSerialize(using = DoubleSerializer.class)
private Double ngoaitruPhi;
private Boolean tncnChk;
@JsonSerialize(using = DoubleSerializer.class)
private Double tncnSi;
@JsonSerialize(using = DoubleSerializer.class)
private Double tncnPhi;
private Boolean smcnChk;
@JsonSerialize(using = DoubleSerializer.class)
private Double smcnSi;
@JsonSerialize(using = DoubleSerializer.class)
private Double smcnPhi;
private Boolean nhakhoaChk;
@JsonSerialize(using = DoubleSerializer.class)
private Double nhakhoaPhi;
private Boolean thaisanChk;
@JsonSerialize(using = DoubleSerializer.class)
private Double thaisanPhi;
@JsonSerialize(using = DateSerializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
private Date thoihanbhTu;
// private String agencyrole ;
@JsonSerialize(using = DoubleSerializer.class)
private Double qlChinhPhi;
@JsonSerialize(using = DoubleSerializer.class)
private Double premiumnet;
@JsonSerialize(using = DoubleSerializer.class)
private Double premiumdiscount;
@JsonSerialize(using = DoubleSerializer.class)
private Double premiumdiscountsi;
@JsonSerialize(using = DoubleSerializer.class)
private Double premiumsktd;
}
| true
|
7d13c1e249cf52b649cba8399dccf96544d01d67
|
Java
|
java2e/SEMIRAMIS
|
/src/pelops/dao/HesapDAO.java
|
UTF-8
| 11,173
| 2.1875
| 2
|
[] |
no_license
|
package pelops.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import pelops.db.DBConnection;
import pelops.kasa.controller.KasaCtrl;
import pelops.model.Hesap;
public class HesapDAO extends DBConnection {
public Hesap Liste(int id) throws Exception {
DBConnection DB = new DBConnection();
DB.newConnectDB();
String SQL = "SELECT * FROM tbl_hesap where id=" + id;
Statement stmt;
ResultSet rs;
stmt = DB.conn.createStatement();
rs = stmt.executeQuery(SQL);
Hesap hesap = null;
while (rs.next()) {
hesap = new Hesap();
hesap.setIcra_dosyasi(rs.getInt("icra_dosyasi"));
hesap.setAsil_alacak(rs.getDouble("asil_alacak"));
hesap.setGecikme_faizi(rs.getDouble("gecikme_faizi"));
hesap.setTemerrut_faizi(rs.getDouble("temerrut_faizi"));
hesap.setFaiz_gider_vergisi(rs.getDouble("faiz_gider_vergisi"));
hesap.setNoter_masrafi(rs.getDouble("noter_masrafi"));
hesap.setTakip_alacagi(rs.getDouble("takip_alacagi"));
hesap.setVekalet_ucreti(rs.getDouble("vekalet_ucreti"));
hesap.setTakip_faizi(rs.getDouble("takip_faizi"));
hesap.setIndirim_faiz_orani(rs.getDouble("indirim_faiz_orani"));
hesap.setTakip_faiz_gider_vergi(rs.getDouble("takip_faiz_gider_vergi"));
hesap.setDiger_harclar(rs.getDouble("diger_harclar"));
hesap.setMasraf_tutari(rs.getDouble("masraf_tutari"));
hesap.setTahsil_harci(rs.getDouble("tahsil_harci"));
hesap.setToplam_alacak(rs.getDouble("toplam_alacak"));
hesap.setTahsilat_tutari(rs.getDouble("tahsilat_tutari"));
hesap.setIndirim_tutari(rs.getDouble("indirim_tutari"));
hesap.setKalan_alacak(rs.getDouble("kalan_alacak"));
hesap.setTemerrut_faiz_orani(rs.getDouble("temerrut_faiz_orani"));
hesap.setAkdi_faiz_orani(rs.getDouble("akdi_faiz_orani"));
hesap.setUrunAdi(rs.getString("urun_adi"));
hesap.setUrunNo(rs.getString("urun_no"));
}
DB.disconnectDB();
return hesap;
}
public int HesapIdGetir(int IcraDosyaNo) throws Exception {
newConnectDB();
String SQL = "SELECT * FROM tbl_hesap where icra_dosyasi=" + IcraDosyaNo;
Statement stmt;
ResultSet rs;
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
int id = 0;
while (rs.next()) {
id = rs.getInt("id");
}
disconnectDB();
return id;
}
public int Kaydet(Hesap hesap) throws Exception {
String SQL = "INSERT INTO tbl_hesap(icra_dosyasi, asil_alacak, gecikme_faizi, temerrut_faizi,"
+ " faiz_gider_vergisi, noter_masrafi, takip_alacagi, vekalet_ucreti,"
+ " takip_faizi, indirim_faiz_orani, takip_faiz_gider_vergi, diger_harclar,"
+ " masraf_tutari, tahsil_harci, toplam_alacak, tahsilat_tutari,"
+ " indirim_tutari, kalan_alacak, akdi_faiz_orani, temerrut_faiz_orani,"
+ " alacak_kalemi2_kalem_kod_turu, alacak_kalemi2_kalem_kod_aciklama, alacak_kalemi2_alacak_kalem_adi,"
+ " alacak_kalemi3_kalem_kod_turu, alacak_kalemi3_kalem_kod, alacak_kalemi3_kalem_kod_aciklama,"
+ " alacak_kalemi3_alacak_kalem_adi, alacak_kalemi4_kalem_kod_turu, alacak_kalemi4_kalem_kod_aciklama,"
+ " alacak_kalemi4_alacak_kalem_adi, alacak_kalemi4_kalem_kod, alacak_kalemi5_kalem_kod_turu,"
+ " alacak_kalemi5_kalem_kod_aciklama, alacak_kalemi5_alacak_kalem_adi, alacak_kalemi5_kalem_kod, urun_adi,urun_no"
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); ";
newConnectDB();
PreparedStatement pstmt = conn.prepareStatement(SQL.toString());
pstmt.setInt(1, hesap.getIcra_dosyasi());
pstmt.setDouble(2, hesap.getAsil_alacak());
pstmt.setDouble(3, hesap.getGecikme_faizi());
pstmt.setDouble(4, hesap.getTemerrut_faizi());
pstmt.setDouble(5, hesap.getFaiz_gider_vergisi());
pstmt.setDouble(6, hesap.getNoter_masrafi());
pstmt.setDouble(7, hesap.getTakip_alacagi());
pstmt.setDouble(8, hesap.getVekalet_ucreti());
pstmt.setDouble(9, hesap.getTakip_faizi());
pstmt.setDouble(10, hesap.getIndirim_faiz_orani());
pstmt.setDouble(11, hesap.getTakip_faiz_gider_vergi());
pstmt.setDouble(12, hesap.getDiger_harclar());
pstmt.setDouble(13, hesap.getMasraf_tutari());
pstmt.setDouble(14, hesap.getTahsil_harci());
pstmt.setDouble(15, hesap.getToplam_alacak());
pstmt.setDouble(16, hesap.getTahsilat_tutari());
pstmt.setDouble(17, hesap.getIndirim_tutari());
pstmt.setDouble(18, hesap.getKalan_alacak());
pstmt.setDouble(19, hesap.getAkdi_faiz_orani());
pstmt.setDouble(20, hesap.getTemerrut_faiz_orani());
pstmt.setString(21, hesap.getAlacak_kalemi2_kalem_kod_turu());
pstmt.setString(22, hesap.getAlacak_kalemi2_kalem_kod_aciklama());
pstmt.setString(23, hesap.getAlacak_kalemi2_alacak_kalem_adi());
pstmt.setString(24, hesap.getAlacak_kalemi3_kalem_kod_turu());
pstmt.setString(25, hesap.getAlacak_kalemi3_kalem_kod());
pstmt.setString(26, hesap.getAlacak_kalemi3_kalem_kod_aciklama());
pstmt.setString(27, hesap.getAlacak_kalemi3_alacak_kalem_adi());
pstmt.setString(28, hesap.getAlacak_kalemi4_kalem_kod_turu());
pstmt.setString(29, hesap.getAlacak_kalemi4_kalem_kod_aciklama());
pstmt.setString(30, hesap.getAlacak_kalemi4_alacak_kalem_adi());
pstmt.setString(31, hesap.getAlacak_kalemi4_kalem_kod());
pstmt.setString(32, hesap.getAlacak_kalemi5_kalem_kod_turu());
pstmt.setString(33, hesap.getAlacak_kalemi5_kalem_kod_aciklama());
pstmt.setString(34, hesap.getAlacak_kalemi5_alacak_kalem_adi());
pstmt.setString(35, hesap.getAlacak_kalemi5_kalem_kod());
pstmt.setString(36, hesap.getUrunAdi());
pstmt.setString(37, hesap.getUrunNo());
pstmt.executeUpdate();
disconnectDB();
return HesapIdGetir(hesap.getIcra_dosyasi());
}
public void Gucelle(Hesap hesap) throws Exception {
if (hesap.getId() == 99) {
} else {
String SQL = "UPDATE tbl_hesap" + " SET icra_dosyasi=?, asil_alacak=?, gecikme_faizi=?, temerrut_faizi=?,"
+ " faiz_gider_vergisi=?, noter_masrafi=?, takip_alacagi=?, vekalet_ucreti=?,"
+ " takip_faizi=?, indirim_faiz_orani=?, takip_faiz_gider_vergi=?,"
+ " diger_harclar=?, masraf_tutari=?, tahsil_harci=?, toplam_alacak=?,"
+ " tahsilat_tutari=?, indirim_tutari=?, kalan_alacak=? WHERE id=" + hesap.getId() + ";";
newConnectDB();
PreparedStatement pstmt = conn.prepareStatement(SQL.toString());
pstmt.setInt(1, hesap.getIcra_dosyasi());
pstmt.setDouble(2, hesap.getAsil_alacak());
pstmt.setDouble(3, hesap.getGecikme_faizi());
pstmt.setDouble(4, hesap.getTemerrut_faizi());
pstmt.setDouble(5, hesap.getFaiz_gider_vergisi());
pstmt.setDouble(6, hesap.getNoter_masrafi());
pstmt.setDouble(7, hesap.getTakip_alacagi());
pstmt.setDouble(8, hesap.getVekalet_ucreti());
pstmt.setDouble(9, hesap.getTakip_faizi());
pstmt.setDouble(10, hesap.getIndirim_faiz_orani());
pstmt.setDouble(11, hesap.getTakip_faiz_gider_vergi());
pstmt.setDouble(12, hesap.getDiger_harclar());
pstmt.setDouble(13, hesap.getMasraf_tutari());
pstmt.setDouble(14, hesap.getTahsil_harci());
pstmt.setDouble(15, hesap.getToplam_alacak());
pstmt.setDouble(16, hesap.getTahsilat_tutari());
pstmt.setDouble(17, hesap.getIndirim_tutari());
pstmt.setDouble(18, hesap.getKalan_alacak());
pstmt.executeUpdate();
disconnectDB();
}
}
public void GuncelleTahsilat(int id, double tahsilatTutari) throws Exception {
String SQL = "UPDATE tbl_hesap SET" + " tahsilat_tutari=?, kalan_alacak=? WHERE id=" + id + ";";
newConnectDB();
PreparedStatement pstmt = conn.prepareStatement(SQL.toString());
double tahsilkalan = Liste(id).getTahsilat_tutari() + tahsilatTutari;
pstmt.setDouble(1, tahsilkalan);
double kalan = Liste(id).getKalan_alacak() - tahsilatTutari;
pstmt.setDouble(2, kalan);
pstmt.executeUpdate();
disconnectDB();
}
public void GuncelleUrun(int id, String UrunAdi, String UrunNo) throws Exception {
String SQL = "UPDATE tbl_hesap SET" + " urun_adi=?, urun_no=? WHERE id=" + id + ";";
newConnectDB();
PreparedStatement pstmt = conn.prepareStatement(SQL.toString());
pstmt.setString(1, UrunAdi);
pstmt.setString(2, UrunNo);
pstmt.executeUpdate();
disconnectDB();
}
public void guncelleAlacak(int id, double alacaktutari) {
String SQL = "UPDATE tbl_hesap SET" + " kalan_alacak=?, toplam_alacak=? WHERE id=" + id + ";";
BaglantiDAO dao = new BaglantiDAO();
try {
Hesap hesap = Liste(dao.Listele(id).getHesaplamaID());
newConnectDB();
PreparedStatement pstm = conn.prepareStatement(SQL);
double kalan = hesap.getKalan_alacak() + alacaktutari;
pstm.setDouble(1, kalan);
double toplam = hesap.getToplam_alacak() + alacaktutari;
pstm.setDouble(2, toplam);
pstm.executeUpdate();
disconnectDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void guncelleHarc(int id, double harcTutari) {
String SQL = "UPDATE tbl_hesap SET" + " diger_harclar=?, kalan_alacak=?, toplam_alacak=? WHERE id=" + id + ";";
BaglantiDAO dao = new BaglantiDAO();
try {
Hesap hesap = Liste(dao.Listele(id).getHesaplamaID());
newConnectDB();
PreparedStatement pstm = conn.prepareStatement(SQL);
double newHarc = hesap.getDiger_harclar() + harcTutari;
pstm.setDouble(1, newHarc);
double kalan = hesap.getKalan_alacak() + harcTutari;
pstm.setDouble(2, kalan);
double toplam = hesap.getToplam_alacak() + harcTutari;
pstm.setDouble(3, toplam);
pstm.executeUpdate();
disconnectDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void guncelleMasraf(int id, double masrafTutari) {
String SQLupdate = "UPDATE tbl_hesap SET" + " masraf_tutari=?, kalan_alacak=?, toplam_alacak=? WHERE id=" + id
+ ";";
try {
Hesap hesap = Liste(id);
newConnectDB();
PreparedStatement pstmtMasraf = conn.prepareStatement(SQLupdate);
System.out.println(hesap.getKalan_alacak());
double masraf = hesap.getMasraf_tutari() + masrafTutari;
pstmtMasraf.setDouble(1, masraf);
double kalan = hesap.getKalan_alacak() + masrafTutari;
pstmtMasraf.setDouble(2, kalan);
double toplam = hesap.getToplam_alacak() + masrafTutari;
pstmtMasraf.setDouble(3, toplam);
pstmtMasraf.executeUpdate();
disconnectDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SilTahsilat(int id, double tahsilatTutari) throws Exception {
String SQL = "UPDATE tbl_hesap SET" + " tahsilat_tutari=?, kalan_alacak=? WHERE id=" + id + ";";
newConnectDB();
PreparedStatement pstmt = conn.prepareStatement(SQL.toString());
double tahsilkalan = Liste(id).getTahsilat_tutari() - tahsilatTutari;
pstmt.setDouble(1, tahsilkalan);
double kalan = Liste(id).getKalan_alacak() + tahsilatTutari;
pstmt.setDouble(2, kalan);
pstmt.executeUpdate();
disconnectDB();
}
public static void main(String[] args) {
HesapDAO dao = new HesapDAO();
try {
// System.out.println(dao.Liste(13044).getToplam_alacak());
KasaCtrl ctrl = new KasaCtrl();
ctrl.printTahsilatMakbuzu(10);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
3425ac8f5a5be94c2339a7a291cf6f4a0cad808d
|
Java
|
doudoutiao/Class
|
/Class/src/day006/四家店的最低手机价格.java
|
GB18030
| 933
| 4.1875
| 4
|
[] |
no_license
|
package day006;
import java.util.Scanner;
public class ļҵֻ۸ {
public static void main(String[] args) {
System.out.println("4ҵļ۸");
//ɨ
Scanner input = new Scanner(System.in);
//priceļ۸
int[] price = new int[4];
//ɨѭļ۸price
for (int i = 1; i <= 4; i++) {
System.out.println("" + i + "ļ۸");
price[i - 1] = input.nextInt();
}
//СֵminȰpriceĵһֵmin
int min = price[0];
//ѭжpriceǷСminֵmin
for (int i = 0; i < price.length; i++) {
if (price[i] < min) {
min = price[i];
}
}
System.out.println("͵ļ۸" + min);
input.close();
}
}
| true
|
0bb4018d7132f40ab1ef5071933f1fa0bc5b6627
|
Java
|
RainbowyDev/HawkClientSRC
|
/src/net/minecraft/entity/ai/EntityAIFollowOwner.java
|
UTF-8
| 4,530
| 2.125
| 2
|
[] |
no_license
|
package net.minecraft.entity.ai;
import net.minecraft.entity.passive.*;
import net.minecraft.pathfinding.*;
import net.minecraft.entity.*;
import net.minecraft.util.*;
import net.minecraft.world.*;
public class EntityAIFollowOwner extends EntityAIBase
{
/* synthetic */ World theWorld;
/* synthetic */ float maxDist;
/* synthetic */ float minDist;
private /* synthetic */ PathNavigate petPathfinder;
private /* synthetic */ double field_75336_f;
private /* synthetic */ boolean field_75344_i;
private /* synthetic */ int field_75343_h;
private /* synthetic */ EntityLivingBase theOwner;
private /* synthetic */ EntityTameable thePet;
@Override
public void startExecuting() {
this.field_75343_h = 0;
this.field_75344_i = ((PathNavigateGround)this.thePet.getNavigator()).func_179689_e();
((PathNavigateGround)this.thePet.getNavigator()).func_179690_a(false);
}
static {
__OBFID = "CL_00001585";
}
@Override
public boolean continueExecuting() {
return !this.petPathfinder.noPath() && this.thePet.getDistanceSqToEntity(this.theOwner) > this.maxDist * this.maxDist && !this.thePet.isSitting();
}
@Override
public void updateTask() {
this.thePet.getLookHelper().setLookPositionWithEntity(this.theOwner, 10.0f, (float)this.thePet.getVerticalFaceSpeed());
if (!this.thePet.isSitting() && --this.field_75343_h <= 0) {
this.field_75343_h = 10;
if (!this.petPathfinder.tryMoveToEntityLiving(this.theOwner, this.field_75336_f) && !this.thePet.getLeashed() && this.thePet.getDistanceSqToEntity(this.theOwner) >= 144.0) {
final int llIlIlIlIlIIIlI = MathHelper.floor_double(this.theOwner.posX) - 2;
final int llIlIlIlIlIIIIl = MathHelper.floor_double(this.theOwner.posZ) - 2;
final int llIlIlIlIlIIIII = MathHelper.floor_double(this.theOwner.getEntityBoundingBox().minY);
for (int llIlIlIlIIlllll = 0; llIlIlIlIIlllll <= 4; ++llIlIlIlIIlllll) {
for (int llIlIlIlIIllllI = 0; llIlIlIlIIllllI <= 4; ++llIlIlIlIIllllI) {
if ((llIlIlIlIIlllll < 1 || llIlIlIlIIllllI < 1 || llIlIlIlIIlllll > 3 || llIlIlIlIIllllI > 3) && World.doesBlockHaveSolidTopSurface(this.theWorld, new BlockPos(llIlIlIlIlIIIlI + llIlIlIlIIlllll, llIlIlIlIlIIIII - 1, llIlIlIlIlIIIIl + llIlIlIlIIllllI)) && !this.theWorld.getBlockState(new BlockPos(llIlIlIlIlIIIlI + llIlIlIlIIlllll, llIlIlIlIlIIIII, llIlIlIlIlIIIIl + llIlIlIlIIllllI)).getBlock().isFullCube() && !this.theWorld.getBlockState(new BlockPos(llIlIlIlIlIIIlI + llIlIlIlIIlllll, llIlIlIlIlIIIII + 1, llIlIlIlIlIIIIl + llIlIlIlIIllllI)).getBlock().isFullCube()) {
this.thePet.setLocationAndAngles(llIlIlIlIlIIIlI + llIlIlIlIIlllll + 0.5f, llIlIlIlIlIIIII, llIlIlIlIlIIIIl + llIlIlIlIIllllI + 0.5f, this.thePet.rotationYaw, this.thePet.rotationPitch);
this.petPathfinder.clearPathEntity();
return;
}
}
}
}
}
}
@Override
public void resetTask() {
this.theOwner = null;
this.petPathfinder.clearPathEntity();
((PathNavigateGround)this.thePet.getNavigator()).func_179690_a(true);
}
public EntityAIFollowOwner(final EntityTameable llIlIlIlIllllII, final double llIlIlIllIIIIII, final float llIlIlIlIllllll, final float llIlIlIlIlllllI) {
this.thePet = llIlIlIlIllllII;
this.theWorld = llIlIlIlIllllII.worldObj;
this.field_75336_f = llIlIlIllIIIIII;
this.petPathfinder = llIlIlIlIllllII.getNavigator();
this.minDist = llIlIlIlIllllll;
this.maxDist = llIlIlIlIlllllI;
this.setMutexBits(3);
if (!(llIlIlIlIllllII.getNavigator() instanceof PathNavigateGround)) {
throw new IllegalArgumentException("Unsupported mob type for FollowOwnerGoal");
}
}
@Override
public boolean shouldExecute() {
final EntityLivingBase llIlIlIlIllIlIl = this.thePet.func_180492_cm();
if (llIlIlIlIllIlIl == null) {
return false;
}
if (this.thePet.isSitting()) {
return false;
}
if (this.thePet.getDistanceSqToEntity(llIlIlIlIllIlIl) < this.minDist * this.minDist) {
return false;
}
this.theOwner = llIlIlIlIllIlIl;
return true;
}
}
| true
|
b74045a15c232844b3c705bdd1ace81220d10301
|
Java
|
chingchun0531/InClassExam2018
|
/src/com/exam/Order.java
|
UTF-8
| 141
| 1.601563
| 2
|
[] |
no_license
|
package com.exam;
import java.util.ArrayList;
public class Order {
ArrayList bag = new ArrayList();
public Order() {
}
}
| true
|
de37a2032c6006e2fac5f2f328645b0d44e9b909
|
Java
|
freeogo/yishimall
|
/src/main/java/cn/com/yishimall/dto/GoodsDTO.java
|
UTF-8
| 1,026
| 2.09375
| 2
|
[] |
no_license
|
package cn.com.yishimall.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
/**
* 商品表
* @author qinghua.zhang
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "商品表")
public class GoodsDTO {
@NotNull
@ApiModelProperty(value = "商品名称", required = true)
private String goodsName;
@NotNull
@ApiModelProperty(value = "商品标题", required = true)
private String goodsTitle;
@NotNull
@ApiModelProperty(value = "商品图片", required = true)
private String goodsImg;
@NotNull
@ApiModelProperty(value = "商品详情", required = true)
private String goodsDetail;
@NotNull
@ApiModelProperty(value = "商品价格", required = true)
private Double goodsPrice;
@NotNull
@ApiModelProperty(value = "商品库存", required = true)
private Integer goodsStock;
}
| true
|
bed2b18232e617bf0462a52c08ed59ee59b35862
|
Java
|
chensheng1/bigdata_communication
|
/src/main/java/hadoop/readfile.java
|
UTF-8
| 3,257
| 2.765625
| 3
|
[] |
no_license
|
package hadoop;
/**
* Created by asus on 2020/7/6.
* user:cs
* 描述:读取zip文件
*/
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class readfile {
/**
* 读取文件内容
*/
public static void cat(Configuration conf, String remoteFilePath) throws IOException {
String uri = remoteFilePath;
FileSystem fs = FileSystem.get(conf);
Path inputpath = new Path(uri);
FSDataInputStream in = fs.open(inputpath);
ZipInputStream d = new ZipInputStream(in);
ZipEntry entry;
while ((entry = d.getNextEntry()) != null) {
//获取当前解压的文件名
String entryName = entry.getName();
System.out.println("fileName:" + entryName);
String input= "/data/" + entryName;
//判断解压文件是否非文件夹
if (entry.isDirectory()) {
System.err.println("true if this is a directory entry. A directory entry is!");
} else {
if (entry.getName().endsWith(".gz")) {
if (entry.getName().contains("http.")) {
if (entry.getSize() == -1) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
int bytes = d.read();
if (bytes == -1) {
break;
}
baos.write(bytes);
}
baos.close();
System.out.println(String.format("Name:%s,Content:%s", entry.getName(), new String(baos.toByteArray())));
} else {
byte[] bytes = new byte[(int) entry.getSize()];
d.read(bytes, 0, (int) entry.getSize());
System.out.println(String.format("Name:%s,Content:%s", entry.getName(), new String(bytes)));
}
}
} else {
System.out.println("is file");
//在hdfs上创建指定文件
}
}
}
d.close();
in.close();
fs.close();
/**
*数据的解压执行过程
*/
}
/**
* 主函数
*/
public static void main(String[] args) {
System.setProperty("HADOOP_USER_NAME", "hadoop");
Configuration conf = new Configuration();
conf.set("fs.default.name", "hdfs://192.168.229.111:9000");
String remoteFilePath = "/data/20160620.zip"; // HDFS路径
try {
System.out.println("读取文件: " + remoteFilePath);
readfile.cat(conf, remoteFilePath);
System.out.println("\n读取完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
937650804face6714092ba57121d27f0511c1b86
|
Java
|
jano333/price-comparator
|
/src/main/java/sk/hudak/jef/ssl/JefSslContants.java
|
UTF-8
| 384
| 2.046875
| 2
|
[] |
no_license
|
package sk.hudak.jef.ssl;
import java.util.HashSet;
import java.util.Set;
public final class JefSslContants {
// obsahuje zoznam povenych hostov, pre ktore sa nevaliduje
public static final Set<String> ALLOWED_HOSTNAME = new HashSet<>(1);
static {
ALLOWED_HOSTNAME.add("hej.sk");
ALLOWED_HOSTNAME.add("esodrogeria.eu");
}
private JefSslContants() {
// no instance
}
}
| true
|
c0f59382e24b1079c94a62e99d3686d8611ec3f7
|
Java
|
hangxiang147/learngit
|
/study/src/com/zhizaolian/staff/utils/SafeFunction.java
|
UTF-8
| 425
| 3.03125
| 3
|
[] |
no_license
|
package com.zhizaolian.staff.utils;
import com.google.common.base.Function;
/**
* 在输入null值时直接返回null的Function
* @author zpp
*
*/
public abstract class SafeFunction<F, T> implements Function<F, T> {
@Override
public final T apply(F input) {
return input != null ? safeApply(input) : null;
}
/**
* @param input 不会为null
* @return
*/
protected abstract T safeApply(F input);
}
| true
|
19f2759718d66a8adae5a8b8c3318afe31b14f9b
|
Java
|
qiongcheng5/IDG_Models
|
/src/dto/json/RetrieveAPI.java
|
UTF-8
| 5,939
| 1.984375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dto.json;
//import static dto.json.DownloadFasta.accessionNumber;
//import static dto.json.DownloadFasta.fastaFileName;
import dto.GenePhenotypeRelInMonarch;
import dto.db.DBHandler4Monarch_DTO;
import dto.util.Common;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Vector;
import dto.wwwapi.GetURL;
import static dto.wwwapi.GetURL.createAFile;
import java.util.LinkedList;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* The class provides a general operation of retrieving data from API access
*
* @author Qiong Cheng
*/
public class RetrieveAPI {
/*
API example: https://monarchinitiative.org/gene/NCBIGene:2629
https://solr.monarchinitiative.org/solr/golr/select?defType=edismax&qt=standard&indent=on&wt=csv&rows=100000&start=0&fl=subject,subject_label,subject_taxon,subject_taxon_label,relation,relation_label,object,object_label,evidence,evidence_label,source,is_defined_by,qualifier&facet=true&facet.mincount=1&facet.sort=count&json.nl=arrarr&facet.limit=25&facet.method=enum&csv.encapsulator=&csv.separator=%09&csv.header=true&csv.mv.separator=%7C&fq=subject_closure:%22NCBIGene:2629%22&fq=object_category:%22phenotype%22&facet.field=subject_taxon_label&q=*:*
*/
/** Creates a new instance of DownloadFasta */
public RetrieveAPI() {
// Create a new trust manager that trust all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Activate the new trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
SecureRandom x = new java.security.SecureRandom();
sc.init(null, trustAllCerts, x);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}
public void getAllGenePhenotypeAssocitions(){
// database access
// Iteratively retrieving gene-phenotype associations
}
public void getAllGenePhenotypeAssocitionsOfDTOMonarchOverlap(DBHandler4Monarch_DTO dbhandler) throws IOException{
try{
// database access
LinkedList<Long> geneIDs = dbhandler.getCommonGeneIDsOfDTOMonarch();
// Iteratively retrieving gene-phenotype associations
int count = 0;
for (Long geneID : geneIDs){
System.out.println("[RetrieveAPI:getAllGenePhenotypeAssocitionsOfDTOMonarchOverlap] " + count + " : " + geneID.longValue());
retrieve(Common.Gene_Phenotype_Relationship, dbhandler, geneID.longValue());
count++;
}
} catch (Exception ex){
ex.printStackTrace();
}
}
/** This method does the actual GET */
public void retrieveRelationship(String theUrl, DBHandler4Monarch_DTO dbhandler, int relType) throws IOException
{
try {
URL gotoUrl = new URL(theUrl);
InputStreamReader isr = new InputStreamReader(gotoUrl.openStream());
BufferedReader in = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String inputLine;
boolean isFirst = true;
//grab the contents at the URL
while ((inputLine = in.readLine()) != null){
if (isFirst){
isFirst = false;
continue;
}
String items[] = inputLine.split("\t");
switch (relType){
case 1:
GenePhenotypeRelInMonarch relobj = new GenePhenotypeRelInMonarch(
items[0], items[1], items[2], items[3],
items[4], items[5], items[6], items[7],
items[8], items[9], items[10], items[11],
items[12]);
dbhandler.insertGenePhenotypeAssociation(relobj);
break;
case 2://other cases ......
default:
}
}
}
catch (MalformedURLException mue) {
mue.printStackTrace();
}
catch (IOException ioe) {
throw ioe;
}
}
public void retrieve(int relType, DBHandler4Monarch_DTO dbhandler, long geneID) throws Exception{
String URL="https://solr.monarchinitiative.org/solr/golr/select?defType=edismax&qt=standard&indent=on&wt=csv&rows=100000&start=0&fl=subject,subject_label,subject_taxon,subject_taxon_label,relation,relation_label,object,object_label,evidence,evidence_label,source,is_defined_by,qualifier&facet=true&facet.mincount=1&facet.sort=count&json.nl=arrarr&facet.limit=25&facet.method=enum&csv.encapsulator=&csv.separator=%09&csv.header=true&csv.mv.separator=%7C&fq=subject_closure:%22NCBIGene:" + geneID + "%22&fq=object_category:%22phenotype%22&facet.field=subject_taxon_label&q=*:*";
retrieveRelationship(URL, dbhandler , relType);
}
}
| true
|
e74ccbf8072fbbe0172147bd14b2db256716f1d5
|
Java
|
zealzhu/MyVideo
|
/app/src/main/java/com/zhu/learn/myvideo/bean/BibiliRecommendVideoInfo.java
|
UTF-8
| 5,440
| 2.015625
| 2
|
[] |
no_license
|
package com.zhu.learn.myvideo.bean;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* Created by zhu on 2017/3/25.
*/
public class BibiliRecommendVideoInfo {
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
private int code;
private String message;
private List<Data> data;
public class Data implements Serializable{
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public String getGo() {
return go;
}
public void setGo(String go) {
this.go = go;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPlay() {
return play;
}
public void setPlay(String play) {
this.play = play;
}
public String getIdx() {
return idx;
}
public void setIdx(String idx) {
this.idx = idx;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public Tag getTag() {
return tag;
}
public void setTag(Tag tag) {
this.tag = tag;
}
public List<DislikeReason> getDislike_reasons() {
return dislike_reasons;
}
public void setDislike_reasons(List<DislikeReason> dislike_reasons) {
this.dislike_reasons = dislike_reasons;
}
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getDanmaku() {
return danmaku;
}
public void setDanmaku(String danmaku) {
this.danmaku = danmaku;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
private String title;
private String cover;
private String uri;
private String param;
@SerializedName("goto")
private String go;
private String desc;
private String play;
private String idx;
private String tid;
private String tname;
private Tag tag;
private List<DislikeReason> dislike_reasons;
private String ctime;
private String danmaku;
private String duration;
private String mid;
private String name;
private String face;
public class Tag {
public String getTagId() {
return tagId;
}
public void setTagId(String tagId) {
this.tagId = tagId;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
@SerializedName("tag_id")
private String tagId;
@SerializedName("tag_name")
private String tagName;
}
public class DislikeReason implements Serializable{
public int getReasonId() {
return reasonId;
}
public void setReasonId(int reasonId) {
this.reasonId = reasonId;
}
public String getReasonName() {
return reasonName;
}
public void setReasonName(String reasonName) {
this.reasonName = reasonName;
}
@SerializedName("reason_id")
private int reasonId;
@SerializedName("reason_name")
private String reasonName;
}
}
}
| true
|
f5fd76629e52a413b00ba8c0b44097991e291a0e
|
Java
|
RyanDur/SML
|
/src/test/java/sml/AddInstructionTest.java
|
UTF-8
| 1,388
| 2.84375
| 3
|
[] |
no_license
|
package sml;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class AddInstructionTest {
private AddInstruction addInstruction;
private int result;
private int op1;
private int op2;
private String label;
@Before
public void setup() {
label = "label";
result = 0;
op1 = 3;
op2 = 5;
addInstruction = new AddInstruction(label, result, op1, op2);
}
@Test
public void shouldBeAbleToExecuteAnInstruction() {
int value = 4;
int value1 = 3;
Machine machine = mock(Machine.class);
Registers registers = mock(Registers.class);
when(machine.getRegisters()).thenReturn(registers);
when(registers.getRegister(op1)).thenReturn(value);
when(registers.getRegister(op2)).thenReturn(value1);
addInstruction.execute(machine);
verify(registers).setRegister(result, value + value1);
}
@Test
public void shouldBeAbleToPrintTheInstruction() {
assertThat(addInstruction.toString(), is(equalTo(label + ": add " + op1 + " + " + op2 + " to " + result)));
}
}
| true
|
a828e48034880c6f6dbbd6f502b5daa9a7074c65
|
Java
|
merlimat/lightproto
|
/code-generator/src/main/java/com/github/splunk/lightproto/generator/LightProtoField.java
|
UTF-8
| 5,216
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2020 Splunk Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.splunk.lightproto.generator;
import io.protostuff.parser.Field;
import io.protostuff.parser.MessageField;
import java.io.PrintWriter;
public abstract class LightProtoField<FieldType extends Field<?>> {
protected final FieldType field;
protected final int index;
protected final String ccName;
protected LightProtoField(FieldType field, int index) {
this.field = field;
this.index = index;
this.ccName = Util.camelCase(field.getName());
}
public static LightProtoField create(Field field, int index) {
if (field.isRepeated()) {
if (field.isMessageField()) {
return new LightProtoRepeatedMessageField((MessageField) field, index);
} else if (field.isStringField()) {
return new LightProtoRepeatedStringField((Field.String) field, index);
} else if (field.isEnumField()) {
return new LightProtoRepeatedEnumField(field, index);
} else if (field.isNumberField() || field.isBoolField()) {
return new LightProtoRepeatedNumberField(field, index);
} else if (field.isBytesField()) {
return new LightProtoRepeatedBytesField((Field.Bytes) field, index);
}
} else if (field.isMessageField()) {
return new LightProtoMessageField((MessageField) field, index);
} else if (field.isBytesField()) {
return new LightProtoBytesField((Field.Bytes) field, index);
} else if (field.isStringField()) {
return new LightProtoStringField((Field.String) field, index);
} else if (field.isEnumField()) {
return new LightProtoEnumField(field, index);
} else if (field.isNumberField()) {
return new LightProtoNumberField(field, index);
} else if (field.isBoolField()) {
return new LightProtoBooleanField(field, index);
}
throw new IllegalArgumentException("Unknown field: " + field);
}
public int index() {
return index;
}
public boolean isRepeated() {
return field.isRepeated();
}
public boolean isEnum() {
return field.isEnumField();
}
public boolean isRequired() {
return field.isRequired();
}
public void docs(PrintWriter w) {
field.getDocs().forEach(d -> w.format(" // %s\n", d));
}
abstract public void declaration(PrintWriter w);
public void tags(PrintWriter w) {
w.format(" private static final int %s = %d;\n", fieldNumber(), field.getNumber());
w.format(" private static final int %s = (%s << LightProtoCodec.TAG_TYPE_BITS) | %s;\n", tagName(), fieldNumber(), typeTag());
w.format(" private static final int %s_SIZE = LightProtoCodec.computeVarIntSize(%s);\n", tagName(), tagName());
if (!field.isRepeated()) {
w.format(" private static final int %s = 1 << (%d %% 32);\n", fieldMask(), index);
}
}
public void has(PrintWriter w) {
w.format(" public boolean %s() {\n", Util.camelCase("has", field.getName()));
w.format(" return (_bitField%d & %s) != 0;\n", bitFieldIndex(), fieldMask());
w.format(" }\n");
}
abstract public void clear(PrintWriter w);
public void fieldClear(PrintWriter w, String enclosingType) {
w.format(" public %s %s() {\n", enclosingType, Util.camelCase("clear", field.getName()));
w.format(" _bitField%d &= ~%s;\n", bitFieldIndex(), fieldMask());
clear(w);
w.format(" return this;\n");
w.format(" }\n");
}
abstract public void setter(PrintWriter w, String enclosingType);
abstract public void getter(PrintWriter w);
abstract public void serializedSize(PrintWriter w);
abstract public void serialize(PrintWriter w);
abstract public void parse(PrintWriter w);
abstract public void copy(PrintWriter w);
public boolean isPackable() {
return field.isRepeated() && field.isPackable();
}
public void parsePacked(PrintWriter w) {
}
abstract protected String typeTag();
protected String tagName() {
return "_" + Util.upperCase(field.getName(), "tag");
}
protected String fieldNumber() {
return "_" + Util.upperCase(field.getName(), "fieldNumber");
}
protected String fieldMask() {
return "_" + Util.upperCase(field.getName(), "mask");
}
protected int bitFieldIndex() {
return index / 32;
}
}
| true
|
7dfe68a37543077b5b4c7d67b94430a3dcdbb4f1
|
Java
|
alexandrofernando/java
|
/topcoder/TheEncryptionDivTwo.java
|
UTF-8
| 362
| 3.203125
| 3
|
[] |
no_license
|
public class TheEncryptionDivTwo {
public String encrypt(String message) {
char cipher[] = new char[26];
char sub = 'a';
String encoded = "";
for (int i = 0; i < message.length(); i++) {
int index = message.charAt(i) - 'a';
if (cipher[index] == 0) {
cipher[index] = sub;
sub++;
}
encoded += cipher[index];
}
return encoded;
}
}
| true
|
5a41579088a309570d16f32331b3bcb868108e88
|
Java
|
cckmit/gtc-cloud
|
/social_service/src/main/java/com/fmisser/gtc/social/domain/ConsumeBill.java
|
UTF-8
| 2,214
| 2.078125
| 2
|
[] |
no_license
|
package com.fmisser.gtc.social.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
// 用户购买消费品的账单
@Entity
@Table(name = "t_consume_bill",
indexes = {@Index(columnList = "userId")})
@Data
@EntityListeners(AuditingEntityListener.class)
@DynamicInsert
@DynamicUpdate
public class ConsumeBill {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 流水号
@Column(nullable = false, unique = true)
private String serialNumber;
@Column(nullable = false)
private Long userId;
// 购买的消费品id
@Column
private Long goodId;
// 商品具体充值币
@Column
private BigDecimal coin;
// 充值前币
@Column
private BigDecimal coinBefore;
// 充值后币
@Column
private BigDecimal coinAfter;
/**
* 购买状态
* 10: 购买成功
* 20:购买失败
*/
@Column
private int status;
@Column
private String remark;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column
private Date finishTime;
@CreatedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column
private Date creatTime;
@LastModifiedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Column
private Date modifyTime;
@CreatedBy
@Column
private String createBy;
@LastModifiedBy
@Column
private String modifyBy;
}
| true
|
2d7c1978959442f034dbae2c6b7dff2c6304c68f
|
Java
|
vinhthan/YouTube-Api-YouTubePlayerView
|
/app/src/main/java/com/example/youtubeapi/MainActivity.java
|
UTF-8
| 1,951
| 2.03125
| 2
|
[] |
no_license
|
package com.example.youtubeapi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
public static final String API_KEY_GOOGGLE_CLOUD_PLATFORM_PROJECT = "AIzaSyADXZVlMulcvbO7Y7k-DiBelLbkacuMnl0";
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
Button btnPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerView = findViewById(R.id.youtube_view);
btnPlay = findViewById(R.id.btn_play);
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("usA25ulAFXc"); //https://www.youtube.com/watch?v=usA25ulAFXc&ab_channel=M%C3%A1tPh%E1%BB%91EDM
Log.d("123123", "success");
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
btnPlay.setOnClickListener(v -> {
youTubePlayerView.initialize(API_KEY_GOOGGLE_CLOUD_PLATFORM_PROJECT, onInitializedListener);
});
}
}
//https://www.youtube.com/watch?v=usA25ulAFXc&ab_channel=M%C3%A1tPh%E1%BB%91EDM //usA25ulAFXc
//Error when rotate screen -> fix: file manifest
// android:name=".MainActivity"
//android:configChanges="orientation|screenSize"
| true
|
c37c9975e8b8fec98099b2214c549b37b7a6ac4a
|
Java
|
nithinn1999/manipalassignments-
|
/Day3_Assignment/Vehicle_car_assignment/src/pack1/car.java
|
UTF-8
| 511
| 3.09375
| 3
|
[] |
no_license
|
package pack1;
public class car extends Vehicle{
private int maxSpeed;
private String type;
public car(int regNo, String model, int currSpeed, int maxSpeed, String type) {
super(regNo, model, currSpeed);
this.maxSpeed = maxSpeed;
this.type = type;
}
@Override
public String increaseSpeed(int n) {
if ((currSpeed+n < maxSpeed))
{
return (Integer.toString(currSpeed+n));
}
else
return ("Car stopped(reached maximum speed)");
}
public int getMaxSpeed() {
return maxSpeed;
}
}
| true
|