hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
922ebdb5bab7c5c2d281648ee019e374858c8a2d | 1,232 | java | Java | SimulatorApp/src/main/java/com/aevi/sdk/dms/simulator/di/AppComponent.java | Aevi-UK/enabled-device-api | 47259d66cc982180a8ecdcfe20a4e5eb85c2fca6 | [
"Apache-2.0"
] | null | null | null | SimulatorApp/src/main/java/com/aevi/sdk/dms/simulator/di/AppComponent.java | Aevi-UK/enabled-device-api | 47259d66cc982180a8ecdcfe20a4e5eb85c2fca6 | [
"Apache-2.0"
] | 1 | 2018-11-16T12:09:29.000Z | 2018-11-16T12:18:02.000Z | SimulatorApp/src/main/java/com/aevi/sdk/dms/simulator/di/AppComponent.java | Aevi-UK/enabled-device-api | 47259d66cc982180a8ecdcfe20a4e5eb85c2fca6 | [
"Apache-2.0"
] | null | null | null | 30.04878 | 76 | 0.757305 | 994,847 | /*
* 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.aevi.sdk.dms.simulator.di;
import android.app.Application;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
@Singleton
@Component(modules = {
AndroidSupportInjectionModule.class,
ComponentBuilder.class,
AppModule.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}
|
922ebdcb41a7bc6569db867465323cb3d4dbb0fa | 2,819 | java | Java | platform/bb/RubyVM/src/com/rho/db/IDBResult.java | hanazuki/rhodes | eff0e410361dba791853a235d58471ba9e25e2fc | [
"MIT"
] | 1 | 2016-02-19T12:57:30.000Z | 2016-02-19T12:57:30.000Z | platform/bb/RubyVM/src/com/rho/db/IDBResult.java | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 2 | 2019-09-16T09:45:10.000Z | 2019-09-16T09:50:36.000Z | platform/bb/RubyVM/src/com/rho/db/IDBResult.java | sdwood/rhodes | 8228aa40708dcbcc1d3967a479d1d84364022255 | [
"MIT"
] | 1 | 2021-05-04T04:11:41.000Z | 2021-05-04T04:11:41.000Z | 40.271429 | 79 | 0.732529 | 994,848 | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
package com.rho.db;
import com.xruby.runtime.lang.RubyValue;
public interface IDBResult {
//public abstract int getCount();
public abstract int getColCount();
public abstract String getColName(int nCol);
public abstract String getOrigColName(int nCol);
/*
public abstract RubyValue getRubyValueByIdx(int nItem, int nCol);
public abstract long getLongByIdx(int nItem, int nCol);
public abstract int getIntByIdx(int nItem, int nCol);
public abstract String getStringByIdx(int nItem, int nCol);
public abstract RubyValue getRubyValue(int nItem, String colname);
public abstract long getLong(int nItem, String colname);
public abstract int getInt(int nItem, String colname);
public abstract String getString(int nItem, String colname);*/
//public abstract void close();//close cursor and release any locks
//New
public abstract boolean isEnd();
public abstract void next() throws DBException;
public abstract String getStringByIdx(int nCol);
public abstract int getIntByIdx(int nCol);
public abstract long getLongByIdx(int nCol);
public abstract String getUInt64ByIdx(int nCol);
public abstract RubyValue getRubyValueByIdx(int nCol);
public abstract boolean isNullByIdx(int nCol);
public abstract RubyValue getRubyValue(String colname);
public abstract int getInt(String colname);
public abstract String getString(String colname);
public abstract Object[] getCurData() throws DBException;
public abstract boolean isNonUnique();
public abstract void close();
}
|
922ebe13be2093dada622adb5c6e3fe626aaaa06 | 1,428 | java | Java | src/main/java/com/gmail/thelimeglass/Expressions/ExprSpreadSource.java | vjh0107/Skellett | 74dea2362676b909c36b35730ea4594fcbc2228d | [
"Apache-2.0"
] | 49 | 2016-06-22T20:19:13.000Z | 2022-02-02T17:49:00.000Z | src/main/java/com/gmail/thelimeglass/Expressions/ExprSpreadSource.java | vjh0107/Skellett | 74dea2362676b909c36b35730ea4594fcbc2228d | [
"Apache-2.0"
] | 179 | 2016-07-17T10:02:57.000Z | 2022-03-27T17:34:29.000Z | src/main/java/com/gmail/thelimeglass/Expressions/ExprSpreadSource.java | vjh0107/Skellett | 74dea2362676b909c36b35730ea4594fcbc2228d | [
"Apache-2.0"
] | 44 | 2016-07-18T01:21:41.000Z | 2022-01-27T20:26:28.000Z | 31.733333 | 100 | 0.77591 | 994,849 | package com.gmail.thelimeglass.Expressions;
import org.bukkit.block.Block;
import org.bukkit.event.Event;
import org.bukkit.event.block.BlockSpreadEvent;
import org.eclipse.jdt.annotation.Nullable;
import com.gmail.thelimeglass.Utils.Annotations.Config;
import com.gmail.thelimeglass.Utils.Annotations.PropertyType;
import com.gmail.thelimeglass.Utils.Annotations.Syntax;
import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
@Syntax("[spread] source block")
@Config("SpreadSource")
@PropertyType(ExpressionType.SIMPLE)
public class ExprSpreadSource extends SimpleExpression<Block> {
public Class<? extends Block> getReturnType() {
return Block.class;
}
public boolean isSingle() {
return true;
}
public boolean init(Expression<?>[] args, int arg1, Kleenean arg2, SkriptParser.ParseResult arg3) {
if (!ScriptLoader.isCurrentEvent(BlockSpreadEvent.class)) {
Skript.error("You can not use Source Block expression in any event but 'on spread:' event!");
return false;
}
return true;
}
public String toString(@Nullable Event arg0, boolean arg1) {
return "Source block spread";
}
@Nullable
protected Block[] get(Event e) {
return new Block[]{((BlockSpreadEvent)e).getSource()};
}
} |
922ebe3f123955b259ebb98253bfaa9cacb277c0 | 14,950 | java | Java | easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java | amilyaa/poi | b138d856dd3240414e925bdb824d8da4faad9f3c | [
"Apache-2.0"
] | 82 | 2017-01-15T08:57:42.000Z | 2022-03-24T07:47:54.000Z | easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java | amilyaa/poi | b138d856dd3240414e925bdb824d8da4faad9f3c | [
"Apache-2.0"
] | 11 | 2018-02-27T02:12:50.000Z | 2021-11-21T06:26:58.000Z | easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java | amilyaa/poi | b138d856dd3240414e925bdb824d8da4faad9f3c | [
"Apache-2.0"
] | 33 | 2017-06-01T16:16:56.000Z | 2021-12-30T08:37:44.000Z | 36.739558 | 119 | 0.545911 | 994,850 | /**
* Copyright 2013-2015 JueYue (envkt@example.com)
*
* 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 org.jeecgframework.poi.excel.export.base;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.entity.params.MergeEntity;
import org.jeecgframework.poi.excel.entity.vo.PoiBaseConstants;
import org.jeecgframework.poi.excel.export.styler.IExcelExportStyler;
import org.jeecgframework.poi.util.PoiMergeCellUtil;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 提供POI基础操作服务
*
* @author JueYue
* @date 2014年6月17日 下午6:15:13
*/
public abstract class ExcelExportBase extends ExportBase {
private static final Logger LOGGER = LoggerFactory
.getLogger(ExcelExportBase.class);
private int currentIndex = 0;
protected ExcelType type = ExcelType.HSSF;
private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
private IExcelExportStyler excelExportStyler;
/**
* 创建 最主要的 Cells
*
* @param styles
* @param rowHeight
* @throws Exception
*/
public int createCells(Drawing patriarch, int index, Object t,
List<ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook,
short rowHeight) throws Exception {
ExcelExportEntity entity;
Row row = sheet.createRow(index);
row.setHeight(rowHeight);
int maxHeight = 1, cellNum = 0;
int indexKey = createIndexCell(row, index, excelParams.get(0));
cellNum += indexKey;
for (int k = indexKey, paramSize = excelParams.size(); k < paramSize; k++) {
entity = excelParams.get(k);
if (entity.getList() != null) {
Collection<?> list = getListCellValue(entity, t);
int listC = 0;
for (Object obj : list) {
createListCells(patriarch, index + listC, cellNum, obj, entity.getList(),
sheet, workbook);
listC++;
}
cellNum += entity.getList().size();
if (list != null && list.size() > maxHeight) {
maxHeight = list.size();
}
} else {
Object value = getCellValue(entity, t);
if (entity.getType() == 1) {
createStringCell(row, cellNum++, value == null ? "" : value.toString(),
index % 2 == 0 ? getStyles(false, entity) : getStyles(true, entity), entity);
} else {
createImageCell(patriarch, entity, row, cellNum++,
value == null ? "" : value.toString(), t);
}
}
}
// 合并需要合并的单元格
cellNum = 0;
for (int k = indexKey, paramSize = excelParams.size(); k < paramSize; k++) {
entity = excelParams.get(k);
if (entity.getList() != null) {
cellNum += entity.getList().size();
} else if (entity.isNeedMerge()) {
for (int i = index + 1; i < index + maxHeight; i++) {
sheet.getRow(i).createCell(cellNum);
sheet.getRow(i).getCell(cellNum).setCellStyle(getStyles(false, entity));
}
sheet.addMergedRegion(new CellRangeAddress(index, index + maxHeight - 1, cellNum,
cellNum));
cellNum++;
}
}
return maxHeight;
}
/**
* 图片类型的Cell
*
* @param patriarch
* @param entity
* @param row
* @param i
* @param imagePath
* @param obj
* @throws Exception
*/
public void createImageCell(Drawing patriarch, ExcelExportEntity entity, Row row, int i,
String imagePath, Object obj) throws Exception {
row.setHeight((short) (50 * entity.getHeight()));
row.createCell(i);
ClientAnchor anchor;
if (type.equals(ExcelType.HSSF)) {
anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1),
row.getRowNum() + 1);
} else {
anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) i, row.getRowNum(), (short) (i + 1),
row.getRowNum() + 1);
}
if (StringUtils.isEmpty(imagePath)) {
return;
}
if (entity.getExportImageType() == 1) {
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
BufferedImage bufferImg;
try {
String path = PoiPublicUtil.getWebRootPath(imagePath);
path = path.replace("WEB-INF/classes/", "");
path = path.replace("file:/", "");
bufferImg = ImageIO.read(new File(path));
ImageIO.write(bufferImg,
imagePath.substring(imagePath.indexOf(".") + 1, imagePath.length()),
byteArrayOut);
byte[] value = byteArrayOut.toByteArray();
patriarch.createPicture(anchor,
row.getSheet().getWorkbook().addPicture(value, getImageType(value)));
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
} else {
byte[] value = (byte[]) (entity.getMethods() != null ? getFieldBySomeMethod(
entity.getMethods(), obj) : entity.getMethod().invoke(obj, new Object[] {}));
if (value != null) {
patriarch.createPicture(anchor,
row.getSheet().getWorkbook().addPicture(value, getImageType(value)));
}
}
}
private int createIndexCell(Row row, int index, ExcelExportEntity excelExportEntity) {
if (excelExportEntity.getName().equals("序号")
&& excelExportEntity.getFormat().equals(PoiBaseConstants.IS_ADD_INDEX)) {
createStringCell(row, 0, currentIndex + "", index % 2 == 0 ? getStyles(false, null)
: getStyles(true, null), null);
currentIndex = currentIndex + 1;
return 1;
}
return 0;
}
/**
* 创建List之后的各个Cells
*
* @param styles
*/
public void createListCells(Drawing patriarch, int index, int cellNum, Object obj,
List<ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook)
throws Exception {
ExcelExportEntity entity;
Row row;
if (sheet.getRow(index) == null) {
row = sheet.createRow(index);
row.setHeight(getRowHeight(excelParams));
} else {
row = sheet.getRow(index);
}
for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
entity = excelParams.get(k);
Object value = getCellValue(entity, obj);
if (entity.getType() == 1) {
createStringCell(row, cellNum++, value == null ? "" : value.toString(),
row.getRowNum() % 2 == 0 ? getStyles(false, entity) : getStyles(true, entity),
entity);
} else {
createImageCell(patriarch, entity, row, cellNum++,
value == null ? "" : value.toString(), obj);
}
}
}
/**
* 创建文本类型的Cell
*
* @param row
* @param index
* @param text
* @param style
* @param entity
*/
public void createStringCell(Row row, int index, String text, CellStyle style,
ExcelExportEntity entity) {
Cell cell = row.createCell(index);
if (style != null && style.getDataFormat() > 0 && style.getDataFormat() < 12) {
cell.setCellValue(Double.parseDouble(text));
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
} else {
RichTextString Rtext;
if (type.equals(ExcelType.HSSF)) {
Rtext = new HSSFRichTextString(text);
} else {
Rtext = new XSSFRichTextString(text);
}
cell.setCellValue(Rtext);
}
if (style != null) {
cell.setCellStyle(style);
}
addStatisticsData(index, text, entity);
}
/**
* 创建统计行
* @param styles
* @param sheet
*/
public void addStatisticsRow(CellStyle styles, Sheet sheet) {
if (statistics.size() > 0) {
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
Set<Integer> keys = statistics.keySet();
createStringCell(row, 0, "合计", styles, null);
for (Integer key : keys) {
createStringCell(row, key, DOUBLE_FORMAT.format(statistics.get(key)), styles, null);
}
statistics.clear();
}
}
/**
* 合计统计信息
* @param index
* @param text
* @param entity
*/
private void addStatisticsData(Integer index, String text, ExcelExportEntity entity) {
if (entity != null && entity.isStatistics()) {
Double temp = 0D;
if (!statistics.containsKey(index)) {
statistics.put(index, temp);
}
try {
temp = Double.valueOf(text);
} catch (NumberFormatException e) {
}
statistics.put(index, statistics.get(index) + temp);
}
}
/**
* 获取导出报表的字段总长度
*
* @param excelParams
* @return
*/
public int getFieldWidth(List<ExcelExportEntity> excelParams) {
int length = -1;// 从0开始计算单元格的
for (ExcelExportEntity entity : excelParams) {
length += entity.getList() != null ? entity.getList().size() : 1;
}
return length;
}
/**
* 获取图片类型,设置图片插入类型
*
* @param value
* @return
* @Author JueYue
* @date 2013年11月25日
*/
public int getImageType(byte[] value) {
String type = PoiPublicUtil.getFileExtendName(value);
if (type.equalsIgnoreCase("JPG")) {
return Workbook.PICTURE_TYPE_JPEG;
} else if (type.equalsIgnoreCase("PNG")) {
return Workbook.PICTURE_TYPE_PNG;
}
return Workbook.PICTURE_TYPE_JPEG;
}
private Map<Integer, int[]> getMergeDataMap(List<ExcelExportEntity> excelParams) {
Map<Integer, int[]> mergeMap = new HashMap<Integer, int[]>();
// 设置参数顺序,为之后合并单元格做准备
int i = 0;
for (ExcelExportEntity entity : excelParams) {
if (entity.isMergeVertical()) {
mergeMap.put(i, entity.getMergeRely());
}
if (entity.getList() != null) {
for (ExcelExportEntity inner : entity.getList()) {
if (inner.isMergeVertical()) {
mergeMap.put(i, inner.getMergeRely());
}
i++;
}
} else {
i++;
}
}
return mergeMap;
}
/**
* 获取样式
* @param entity
* @param needOne
* @return
*/
public CellStyle getStyles(boolean needOne, ExcelExportEntity entity) {
return excelExportStyler.getStyles(needOne, entity);
}
/**
* 合并单元格
*
* @param sheet
* @param excelParams
* @param styles
*/
public void mergeCells(Sheet sheet, List<ExcelExportEntity> excelParams, int titleHeight) {
Map<Integer, int[]> mergeMap = getMergeDataMap(excelParams);
PoiMergeCellUtil.mergeCells(sheet, mergeMap, titleHeight);
}
public void setCellWith(List<ExcelExportEntity> excelParams, Sheet sheet) {
int index = 0;
for (int i = 0; i < excelParams.size(); i++) {
if (excelParams.get(i).getList() != null) {
List<ExcelExportEntity> list = excelParams.get(i).getList();
for (int j = 0; j < list.size(); j++) {
sheet.setColumnWidth(index, (int) (256 * list.get(j).getWidth()));
index++;
}
} else {
sheet.setColumnWidth(index, (int) (256 * excelParams.get(i).getWidth()));
index++;
}
}
}
public void setCurrentIndex(int currentIndex) {
this.currentIndex = currentIndex;
}
public void setExcelExportStyler(IExcelExportStyler excelExportStyler) {
this.excelExportStyler = excelExportStyler;
}
public IExcelExportStyler getExcelExportStyler() {
return excelExportStyler;
}
}
|
922ebe99d6c1f77e94e0f5ce0d765ef66044e2e8 | 824 | java | Java | app/src/main/java/com/codemaroon/feedhub/ParseAPIBackend/FeedObject.java | toriawei/Feedhub | c1a01b0cc3787ac45e9fb71153f5ddcae5ad1c23 | [
"MIT"
] | null | null | null | app/src/main/java/com/codemaroon/feedhub/ParseAPIBackend/FeedObject.java | toriawei/Feedhub | c1a01b0cc3787ac45e9fb71153f5ddcae5ad1c23 | [
"MIT"
] | null | null | null | app/src/main/java/com/codemaroon/feedhub/ParseAPIBackend/FeedObject.java | toriawei/Feedhub | c1a01b0cc3787ac45e9fb71153f5ddcae5ad1c23 | [
"MIT"
] | null | null | null | 22.27027 | 47 | 0.632282 | 994,851 | package com.codemaroon.feedhub.ParseAPIBackend;
import com.parse.ParseObject;
import com.parse.ParseClassName;
import com.parse.ParseUser;
public class FeedObject extends ParseObject {
public FeedObject() {}
public String getTime(){
return getString("time");
}
public boolean isComplete(){
return getBoolean("complete");
}
public String getVenue(){
return getString("venue");
}
public String getUserId(){
return getString("userId");
}
public void setTime(String time) {
put("time", time);
}
public void setVenue(String venue){
put("venue", venue);
}
public void setUserId(String userId){
put("userId", userId);
}
public void setComplete(Boolean complete){
put("complete", complete);
}
}
|
922ec0dc44c6a60beb1e95c1a2d0780724ed4920 | 1,351 | java | Java | tomato-rpc-config/src/main/java/org/tomato/study/rpc/config/error/TomatoRpcConfigurationErrorEnum.java | CompassA/tomato-rpc | 24e393542860683dd93488fc3d49fb309c12ea0b | [
"Apache-2.0"
] | 4 | 2021-11-24T05:15:43.000Z | 2021-12-06T04:45:23.000Z | tomato-rpc-config/src/main/java/org/tomato/study/rpc/config/error/TomatoRpcConfigurationErrorEnum.java | CompassA/tomato-rpc | 24e393542860683dd93488fc3d49fb309c12ea0b | [
"Apache-2.0"
] | null | null | null | tomato-rpc-config/src/main/java/org/tomato/study/rpc/config/error/TomatoRpcConfigurationErrorEnum.java | CompassA/tomato-rpc | 24e393542860683dd93488fc3d49fb309c12ea0b | [
"Apache-2.0"
] | 1 | 2021-12-06T04:45:27.000Z | 2021-12-06T04:45:27.000Z | 30.704545 | 80 | 0.733531 | 994,852 | /*
* 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 org.tomato.study.rpc.config.error;
import lombok.AllArgsConstructor;
import org.tomato.study.rpc.core.error.TomatoRpcErrorInfo;
/**
* @author Tomato
* Created on 2021.11.18
*/
@AllArgsConstructor
public enum TomatoRpcConfigurationErrorEnum {
MICROSERVICE_ID_NOT_FOUND(-1, "missing micro-service-id"),
RPC_CORE_SERVICE_BEAN_START_ERROR(-2, "create rpc core service bean error"),
RPC_CORE_SERVICE_STOP_ERROR(-3, "stop rpc core service bean error"),
;
private int code;
private String message;
public TomatoRpcErrorInfo create() {
return new TomatoRpcErrorInfo(this.code, this.message);
}
public TomatoRpcErrorInfo create(String customMessage) {
return new TomatoRpcErrorInfo(this.code, customMessage);
}
}
|
922ec16ee9e7c93c181381bcbfd71cb8bc4fe6c4 | 890 | java | Java | StringSorter/src/com/github/psychotherapist/externalsorting/utils/UtilsTestWithNaturalOrder.java | PsychoTheRapist/ExternalSorting | b688dce985593d0b51a2b4917d47b710651d125f | [
"MIT"
] | null | null | null | StringSorter/src/com/github/psychotherapist/externalsorting/utils/UtilsTestWithNaturalOrder.java | PsychoTheRapist/ExternalSorting | b688dce985593d0b51a2b4917d47b710651d125f | [
"MIT"
] | null | null | null | StringSorter/src/com/github/psychotherapist/externalsorting/utils/UtilsTestWithNaturalOrder.java | PsychoTheRapist/ExternalSorting | b688dce985593d0b51a2b4917d47b710651d125f | [
"MIT"
] | null | null | null | 35.6 | 61 | 0.691011 | 994,853 | package com.github.psychotherapist.externalsorting.utils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UtilsTestWithNaturalOrder {
@Test
void testIsGrowingSequenceWithNull() {
assertTrue(Utils.isGrowingSequence(null, "test"));
assertTrue(Utils.isGrowingSequence(null, ""));
assertFalse(Utils.isGrowingSequence("test", null));
assertFalse(Utils.isGrowingSequence("", null));
assertFalse(Utils.isGrowingSequence(null, null));
}
@Test
void testIsGrowingSequenceWithoutNull() {
assertTrue(Utils.isGrowingSequence("test", "test"));
assertTrue(Utils.isGrowingSequence("Test", "test"));
assertTrue(Utils.isGrowingSequence("", "test"));
assertFalse(Utils.isGrowingSequence("test", "Test"));
assertFalse(Utils.isGrowingSequence("test", ""));
}
} |
922ec21734a676fdb76e5b237b9dcba7784375ef | 13,354 | java | Java | engine/src/test/java/io/camunda/zeebe/engine/processing/bpmn/gateway/ParallelGatewayTest.java | tommyfgj/zeebe | e55d38dd0dd1f57e547f0861b61f299d88a9afd2 | [
"Apache-2.0"
] | 1,830 | 2017-08-09T17:29:34.000Z | 2021-03-07T06:05:07.000Z | engine/src/test/java/io/camunda/zeebe/engine/processing/bpmn/gateway/ParallelGatewayTest.java | tommyfgj/zeebe | e55d38dd0dd1f57e547f0861b61f299d88a9afd2 | [
"Apache-2.0"
] | 6,103 | 2017-08-07T12:15:34.000Z | 2021-03-09T12:11:03.000Z | engine/src/test/java/io/camunda/zeebe/engine/processing/bpmn/gateway/ParallelGatewayTest.java | menski/zeebe | 742ad4fe3c7a796a78508780892c31be34d0478b | [
"Apache-2.0"
] | 337 | 2017-08-08T16:18:43.000Z | 2021-03-09T02:00:15.000Z | 37.301676 | 98 | 0.66744 | 994,854 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.engine.processing.bpmn.gateway;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import io.camunda.zeebe.engine.util.EngineRule;
import io.camunda.zeebe.model.bpmn.Bpmn;
import io.camunda.zeebe.model.bpmn.BpmnModelInstance;
import io.camunda.zeebe.model.bpmn.instance.ServiceTask;
import io.camunda.zeebe.protocol.record.Record;
import io.camunda.zeebe.protocol.record.intent.ProcessInstanceIntent;
import io.camunda.zeebe.protocol.record.value.BpmnElementType;
import io.camunda.zeebe.protocol.record.value.ProcessInstanceRecordValue;
import io.camunda.zeebe.test.util.record.RecordingExporter;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test;
public final class ParallelGatewayTest {
private static final String PROCESS_ID = "process";
private static final BpmnModelInstance FORK_PROCESS =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.parallelGateway("fork")
.serviceTask("task1", b -> b.zeebeJobType("type1"))
.endEvent("end1")
.moveToNode("fork")
.serviceTask("task2", b -> b.zeebeJobType("type2"))
.endEvent("end2")
.done();
private static final BpmnModelInstance FORK_JOIN_PROCESS =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.parallelGateway("fork")
.sequenceFlowId("flow1")
.parallelGateway("join")
.endEvent("end")
.moveToNode("fork")
.sequenceFlowId("flow2")
.connectTo("join")
.done();
@Rule public final EngineRule engine = EngineRule.singlePartition();
@Test
public void shouldActivateTasksOnParallelBranches() {
// given
engine.deployment().withXmlResource(FORK_PROCESS).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> taskEvents =
RecordingExporter.processInstanceRecords()
.withIntent(ProcessInstanceIntent.ELEMENT_ACTIVATED)
.filter(e -> isServiceTaskInProcess(e.getValue().getElementId(), FORK_PROCESS))
.limit(2)
.collect(Collectors.toList());
assertThat(taskEvents).hasSize(2);
assertThat(taskEvents)
.extracting(e -> e.getValue().getElementId())
.containsExactlyInAnyOrder("task1", "task2");
assertThat(taskEvents.get(0).getKey()).isNotEqualTo(taskEvents.get(1).getKey());
}
@Test
public void shouldCompleteScopeWhenAllPathsCompleted() {
// given
engine.deployment().withXmlResource(FORK_PROCESS).deploy();
final long processInstanceKey = engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
engine.job().ofInstance(processInstanceKey).withType("type1").complete();
// when
engine.job().ofInstance(processInstanceKey).withType("type2").complete();
// then
final List<Record<ProcessInstanceRecordValue>> completedEvents =
RecordingExporter.processInstanceRecords()
.withElementType(BpmnElementType.END_EVENT)
.withIntent(ProcessInstanceIntent.ELEMENT_COMPLETED)
.limit(2)
.collect(Collectors.toList());
assertThat(completedEvents)
.extracting(e -> e.getValue().getElementId())
.containsExactly("end1", "end2");
RecordingExporter.processInstanceRecords()
.withElementId(PROCESS_ID)
.withIntent(ProcessInstanceIntent.ELEMENT_COMPLETED)
.getFirst();
}
@Test
public void shouldCompleteScopeWithMultipleTokensOnSamePath() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent()
.parallelGateway("fork")
.exclusiveGateway("join")
.endEvent("end")
.moveToNode("fork")
.connectTo("join")
.done();
engine.deployment().withXmlResource(process).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> processInstanceEvents =
RecordingExporter.processInstanceRecords()
.limitToProcessInstanceCompleted()
.collect(Collectors.toList());
assertThat(processInstanceEvents)
.extracting(e -> e.getValue().getElementId(), Record::getIntent)
.containsSubsequence(
tuple("end", ProcessInstanceIntent.ELEMENT_COMPLETED),
tuple("end", ProcessInstanceIntent.ELEMENT_COMPLETED),
tuple(PROCESS_ID, ProcessInstanceIntent.ELEMENT_COMPLETED));
}
@Test
public void shouldPassThroughParallelGateway() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.sequenceFlowId("flow1")
.parallelGateway("fork")
.sequenceFlowId("flow2")
.endEvent("end")
.done();
engine.deployment().withXmlResource(process).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> processInstanceEvents =
RecordingExporter.processInstanceRecords()
.limitToProcessInstanceCompleted()
.collect(Collectors.toList());
assertThat(processInstanceEvents)
.extracting(e -> e.getValue().getElementId(), Record::getIntent)
.containsSequence(
tuple("fork", ProcessInstanceIntent.ELEMENT_ACTIVATING),
tuple("fork", ProcessInstanceIntent.ELEMENT_ACTIVATED),
tuple("fork", ProcessInstanceIntent.ELEMENT_COMPLETING),
tuple("fork", ProcessInstanceIntent.ELEMENT_COMPLETED),
tuple("flow2", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("end", ProcessInstanceIntent.ACTIVATE_ELEMENT),
tuple("end", ProcessInstanceIntent.ELEMENT_ACTIVATING),
tuple("end", ProcessInstanceIntent.ELEMENT_ACTIVATED),
tuple("end", ProcessInstanceIntent.ELEMENT_COMPLETING),
tuple("end", ProcessInstanceIntent.ELEMENT_COMPLETED),
tuple(PROCESS_ID, ProcessInstanceIntent.COMPLETE_ELEMENT),
tuple(PROCESS_ID, ProcessInstanceIntent.ELEMENT_COMPLETING),
tuple(PROCESS_ID, ProcessInstanceIntent.ELEMENT_COMPLETED));
}
@Test
public void shouldCompleteScopeOnParallelGateway() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.sequenceFlowId("flow1")
.parallelGateway("fork")
.done();
engine.deployment().withXmlResource(process).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> processInstanceEvents =
RecordingExporter.processInstanceRecords()
.limitToProcessInstanceCompleted()
.collect(Collectors.toList());
assertThat(processInstanceEvents)
.extracting(e -> e.getValue().getElementId(), Record::getIntent)
.containsSequence(
tuple("fork", ProcessInstanceIntent.ELEMENT_COMPLETED),
tuple(PROCESS_ID, ProcessInstanceIntent.COMPLETE_ELEMENT));
}
@Test
public void shouldMergeParallelBranches() {
// given
engine.deployment().withXmlResource(FORK_JOIN_PROCESS).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> events =
RecordingExporter.processInstanceRecords()
.limitToProcessInstanceCompleted()
.collect(Collectors.toList());
assertThat(events)
.extracting(e -> e.getValue().getElementId(), Record::getIntent)
.containsSubsequence(
tuple("flow1", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("join", ProcessInstanceIntent.ELEMENT_ACTIVATING))
.containsSubsequence(
tuple("flow2", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("join", ProcessInstanceIntent.ELEMENT_ACTIVATING))
.containsOnlyOnce(tuple("join", ProcessInstanceIntent.ELEMENT_ACTIVATING));
}
@Test
public void shouldOnlyTriggerGatewayWhenAllBranchesAreActivated() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent()
.parallelGateway("fork")
.exclusiveGateway("exclusiveJoin")
.moveToLastGateway()
.connectTo("exclusiveJoin")
.sequenceFlowId("joinFlow1")
.parallelGateway("join")
.moveToNode("fork")
.serviceTask("waitState", b -> b.zeebeJobType("type"))
.sequenceFlowId("joinFlow2")
.connectTo("join")
.endEvent()
.done();
engine.deployment().withXmlResource(process).deploy();
final long processInstanceKey = engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// waiting until we have signalled the first incoming sequence flow twice
// => this should not trigger the gateway yet
RecordingExporter.processInstanceRecords()
.limit(r -> "joinFlow1".equals(r.getValue().getElementId()))
.limit(2)
.skip(1)
.getFirst();
// when
// we complete the job
engine.job().ofInstance(processInstanceKey).withType("type").complete();
// then
final List<Record<ProcessInstanceRecordValue>> events =
RecordingExporter.processInstanceRecords()
.limit(
r ->
"join".equals(r.getValue().getElementId())
&& ProcessInstanceIntent.ELEMENT_COMPLETED == r.getIntent())
.collect(Collectors.toList());
assertThat(events)
.extracting(e -> e.getValue().getElementId(), Record::getIntent)
.containsSubsequence(
tuple("joinFlow1", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("joinFlow1", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("joinFlow2", ProcessInstanceIntent.SEQUENCE_FLOW_TAKEN),
tuple("join", ProcessInstanceIntent.ELEMENT_ACTIVATING));
}
@Test
public void shouldMergeAndSplitInOneGateway() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.parallelGateway("fork")
.parallelGateway("join-fork")
.moveToNode("fork")
.connectTo("join-fork")
.serviceTask("task1", b -> b.zeebeJobType("type1"))
.moveToLastGateway()
.serviceTask("task2", b -> b.zeebeJobType("type2"))
.done();
engine.deployment().withXmlResource(process).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> elementInstances =
RecordingExporter.processInstanceRecords()
.filter(
r ->
r.getIntent() == ProcessInstanceIntent.ELEMENT_ACTIVATED
&& r.getValue().getBpmnElementType() == BpmnElementType.SERVICE_TASK)
.limit(2)
.collect(Collectors.toList());
assertThat(elementInstances)
.extracting(e -> e.getValue().getElementId())
.contains("task1", "task2");
}
@Test
public void shouldSplitWithUncontrolledFlow() {
// given
final BpmnModelInstance process =
Bpmn.createExecutableProcess(PROCESS_ID)
.startEvent("start")
.serviceTask("task1", b -> b.zeebeJobType("type1"))
.moveToNode("start")
.serviceTask("task2", b -> b.zeebeJobType("type2"))
.done();
engine.deployment().withXmlResource(process).deploy();
// when
engine.processInstance().ofBpmnProcessId(PROCESS_ID).create();
// then
final List<Record<ProcessInstanceRecordValue>> taskEvents =
RecordingExporter.processInstanceRecords()
.withIntent(ProcessInstanceIntent.ELEMENT_ACTIVATED)
.filter(e -> isServiceTaskInProcess(e.getValue().getElementId(), process))
.limit(2)
.collect(Collectors.toList());
assertThat(taskEvents).hasSize(2);
assertThat(taskEvents)
.extracting(e -> e.getValue().getElementId())
.containsExactlyInAnyOrder("task1", "task2");
assertThat(taskEvents.get(0).getKey()).isNotEqualTo(taskEvents.get(1).getKey());
}
private static boolean isServiceTaskInProcess(
final String activityId, final BpmnModelInstance process) {
return process.getModelElementsByType(ServiceTask.class).stream()
.anyMatch(t -> t.getId().equals(activityId));
}
}
|
922ec2691c0a577362e043101a6835e853ca78f3 | 154 | java | Java | src/com/test/dip/DependancyInversionPrinciple.java | sopansagorkar/SolidPrinciples | 24c67ac49945d87454b1a408243f05dfe8b58a84 | [
"MIT"
] | null | null | null | src/com/test/dip/DependancyInversionPrinciple.java | sopansagorkar/SolidPrinciples | 24c67ac49945d87454b1a408243f05dfe8b58a84 | [
"MIT"
] | null | null | null | src/com/test/dip/DependancyInversionPrinciple.java | sopansagorkar/SolidPrinciples | 24c67ac49945d87454b1a408243f05dfe8b58a84 | [
"MIT"
] | null | null | null | 14 | 43 | 0.733766 | 994,855 | package com.test.dip;
public class DependancyInversionPrinciple {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
922ec269641b27e024ac507b75588babbbce8a72 | 3,177 | java | Java | resources/com/tactfactory/tracscan/entity/Zone.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | resources/com/tactfactory/tracscan/entity/Zone.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | resources/com/tactfactory/tracscan/entity/Zone.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | 19.85625 | 88 | 0.677683 | 994,856 | package com.tactfactory.tracscan.entity;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
import com.tactfactory.harmony.annotation.Column;
import com.tactfactory.harmony.annotation.Entity;
import com.tactfactory.harmony.annotation.Id;
import com.tactfactory.harmony.annotation.Column.Type;
@Entity
public class Zone implements Serializable , Parcelable {
/** Key Constant for parcelable/serialization. */
public static final String PARCEL =
"Zone";
/** Serial Version UID */
private static final long serialVersionUID = 7335864735424803701L;
@Id
@Column(type = Type.INTEGER, hidden = true)
protected int id;
@Column
protected String name;
@Column(type = Type.INTEGER, defaultValue="1")
protected int quantity;
/**
* Default constructor.
*/
public Zone() {
}
@Override
public String toString() {
return this.name;
}
/**
* @return the id
*/
public int getId() {
return this.id;
}
/**
* @param value the id to set
*/
public void setId(final int value) {
this.id = value;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* @param value the name to set
*/
public void setName(final String value) {
this.name = value;
}
/**
* @return the quantity
*/
public int getQuantity() {
return this.quantity;
}
/**
* @param value the quantity to set
*/
public void setQuantity(final int value) {
this.quantity = value;
}
/**
* This stub of code is regenerated. DO NOT MODIFY.
*
* @param dest Destination parcel
* @param flags flags
*/
public void writeToParcelRegen(Parcel dest, int flags) {
dest.writeInt(this.getId());
dest.writeString(this.getName());
dest.writeInt(this.getQuantity());
}
/**
* Regenerated Parcel Constructor.
*
* This stub of code is regenerated. DO NOT MODIFY THIS METHOD.
*
* @param parc The parcel to read from
*/
public void readFromParcel(Parcel parc) {
this.setId(parc.readInt());
this.setName(parc.readString());
this.setQuantity(parc.readInt());
}
/**
* Parcel Constructor.
*
* @param parc The parcel to read from
*/
public Zone(Parcel parc) {
// You can chose not to use harmony's generated parcel.
// To do this, remove this line.
this.readFromParcel(parc);
// You can implement your own parcel mechanics here.
}
/* This method is not regenerated. You can implement your own parcel mechanics here. */
@Override
public void writeToParcel(Parcel dest, int flags) {
// You can chose not to use harmony's generated parcel.
// To do this, remove this line.
this.writeToParcelRegen(dest, flags);
// You can implement your own parcel mechanics here.
}
@Override
public int describeContents() {
// This should return 0
// or CONTENTS_FILE_DESCRIPTOR if your entity is a FileDescriptor.
return 0;
}
/**
* Parcelable creator.
*/
public static final Parcelable.Creator<Zone> CREATOR
= new Parcelable.Creator<Zone>() {
public Zone createFromParcel(Parcel in) {
return new Zone(in);
}
public Zone[] newArray(int size) {
return new Zone[size];
}
};
}
|
922ec4b8bb310167c43acf5491a0ae23c74d9d9b | 13,694 | java | Java | app/src/main/java/com/afwsamples/testdpc/policy/OverrideApnFragment.java | sridharreddysuram123/android-testdpc | 3b64298489296d7b5cd52492dd7f52e04215a11a | [
"Apache-2.0"
] | 567 | 2015-05-22T15:06:28.000Z | 2022-03-22T07:53:28.000Z | app/src/main/java/com/afwsamples/testdpc/policy/OverrideApnFragment.java | sridharreddysuram123/android-testdpc | 3b64298489296d7b5cd52492dd7f52e04215a11a | [
"Apache-2.0"
] | 135 | 2015-11-18T12:11:47.000Z | 2022-03-29T14:52:51.000Z | app/src/main/java/com/afwsamples/testdpc/policy/OverrideApnFragment.java | sridharreddysuram123/android-testdpc | 3b64298489296d7b5cd52492dd7f52e04215a11a | [
"Apache-2.0"
] | 301 | 2015-06-06T22:26:51.000Z | 2022-03-14T17:55:13.000Z | 43.335443 | 99 | 0.635753 | 994,857 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* 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.afwsamples.testdpc.policy;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.Uri;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import androidx.preference.SwitchPreference;
import androidx.preference.Preference;
import android.telephony.data.ApnSetting;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.afwsamples.testdpc.DeviceAdminReceiver;
import com.afwsamples.testdpc.R;
import com.afwsamples.testdpc.common.BaseSearchablePolicyPreferenceFragment;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
@TargetApi(VERSION_CODES.P)
public class OverrideApnFragment extends BaseSearchablePolicyPreferenceFragment implements
Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
private static String LOG_TAG = "OverrideApnFragment";
private static final String INSERT_OVERRIDE_APN_KEY = "insert_override_apn";
private static final String REMOVE_OVERRIDE_APN_KEY = "remove_override_apn";
private static final String ENABLE_OVERRIDE_APN_KEY = "enable_override_apn";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mAdminComponentName;
private SwitchPreference mEnableOverrideApnPreference;
@Override
public void onCreate(Bundle savedInstanceState) {
mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
getActivity().getActionBar().setTitle(R.string.override_apn_title);
super.onCreate(savedInstanceState);
}
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.override_apn_preferences);
findPreference(INSERT_OVERRIDE_APN_KEY).setOnPreferenceClickListener(this);
findPreference(REMOVE_OVERRIDE_APN_KEY).setOnPreferenceClickListener(this);
mEnableOverrideApnPreference = (SwitchPreference) findPreference(ENABLE_OVERRIDE_APN_KEY);
mEnableOverrideApnPreference.setOnPreferenceChangeListener(this);
}
@Override
public boolean isAvailable(Context context) {
return true;
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
switch (key) {
case INSERT_OVERRIDE_APN_KEY:
showInsertOverrideApnDialog();
return true;
case REMOVE_OVERRIDE_APN_KEY:
onRemoveOverrideApn();
return true;
}
return false;
}
@Override
@SuppressLint("NewApi")
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
switch (key) {
case ENABLE_OVERRIDE_APN_KEY:
boolean enabled = (boolean) newValue;
mDevicePolicyManager.setOverrideApnsEnabled(mAdminComponentName, enabled);
reloadEnableOverrideApnUi();
return true;
}
return false;
}
void setUpSpinner(View dialogView, int viewId, int textArrayId) {
final Spinner spinner = (Spinner) dialogView.findViewById(viewId);
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity(), textArrayId, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
void setUpAllSpinners(View dialogView) {
// Set up spinner for auth type.
setUpSpinner(dialogView, R.id.apn_auth_type, R.array.apn_auth_type_choices);
// Set up spinner for protocol.
setUpSpinner(dialogView, R.id.apn_protocol, R.array.apn_protocol_choices);
// Set up spinner for roaming protocol.
setUpSpinner(dialogView, R.id.apn_roaming_protocol, R.array.apn_protocol_choices);
// Set up spinner for mvno type.
setUpSpinner(dialogView, R.id.apn_mvno_type, R.array.apn_mvno_type_choices);
// Set up spinner for carrier enabled.
setUpSpinner(dialogView, R.id.apn_carrier_enabled, R.array.apn_carrier_enabled_choices);
}
void showInsertOverrideApnDialog() {
if (getActivity() == null || getActivity().isFinishing()) {
return;
}
final View dialogView = getActivity().getLayoutInflater().inflate(
R.layout.insert_apn, null);
final EditText entryNameEditText = (EditText) dialogView.findViewById(
R.id.apn_entry_name);
final EditText apnNameEditText = (EditText) dialogView.findViewById(
R.id.apn_apn_name);
final EditText proxyEditText = (EditText) dialogView.findViewById(
R.id.apn_proxy);
final EditText portEditText = (EditText) dialogView.findViewById(
R.id.apn_port);
final EditText mmscEditText = (EditText) dialogView.findViewById(
R.id.apn_mmsc);
final EditText mmsProxyEditText = (EditText) dialogView.findViewById(
R.id.apn_mmsproxy);
final EditText mmsPortEditText = (EditText) dialogView.findViewById(
R.id.apn_mmsport);
final EditText userEditText = (EditText) dialogView.findViewById(
R.id.apn_user);
final EditText passwordEditText = (EditText) dialogView.findViewById(
R.id.apn_password);
final EditText typeEditText = (EditText) dialogView.findViewById(
R.id.apn_type);
final EditText numericEditText = (EditText) dialogView.findViewById(
R.id.apn_numeric);
final EditText networkBitmaskEditText = (EditText) dialogView.findViewById(
R.id.apn_network_bitmask);
setUpAllSpinners(dialogView);
entryNameEditText.setHint(R.string.apn_entry_name_cannot_be_empty);
apnNameEditText.setHint(R.string.apn_name_cannot_be_empty);
typeEditText.setHint(R.string.apn_type_cannot_be_zero);
numericEditText.setHint(R.string.apn_numeric_hint);
new AlertDialog.Builder(getActivity())
.setTitle(R.string.insert_override_apn)
.setView(dialogView)
.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> {
final String entryName = entryNameEditText.getText().toString();
if (entryName.isEmpty()) {
showToast(R.string.apn_entry_name_cannot_be_empty);
return;
}
final String apnName = apnNameEditText.getText().toString();
if (apnName.isEmpty()) {
showToast(R.string.apn_name_cannot_be_empty);
return;
}
final int apnTypeBitmask = parseInt(typeEditText.getText().toString(), 0);
if (apnTypeBitmask == 0) {
showToast(R.string.apn_type_cannot_be_zero);
return;
}
ApnSetting apn = makeApnSetting(
numericEditText.getText().toString(),
entryName,
apnName,
inetAddressFromString(proxyEditText.getText().toString()),
parseInt(portEditText.getText().toString(), -1),
UriFromString(mmscEditText.getText().toString()),
inetAddressFromString(mmsProxyEditText.getText().toString()),
parseInt(mmsPortEditText.getText().toString(), -1),
userEditText.getText().toString(),
passwordEditText.getText().toString(),
// -1 here as we have extra default choice "Not specified" in the
// spinner of auth type, protocol, roaming protocol and mvno type
// in case user doesn't want to specify these fields. And
// "Not Specified" should be transformed into "-1" in the builder
// of ApnSetting.
((Spinner)dialogView.findViewById(R.id.apn_auth_type))
.getSelectedItemPosition() - 1,
apnTypeBitmask,
((Spinner)dialogView.findViewById(R.id.apn_protocol))
.getSelectedItemPosition() - 1,
((Spinner)dialogView.findViewById(
R.id.apn_roaming_protocol)).getSelectedItemPosition() - 1,
((Spinner)dialogView.findViewById(
R.id.apn_carrier_enabled)).getSelectedItemPosition() == 1,
parseInt(networkBitmaskEditText.getText().toString(), 0),
((Spinner)dialogView.findViewById(R.id.apn_mvno_type))
.getSelectedItemPosition() - 1
);
int insertedId = mDevicePolicyManager.addOverrideApn(mAdminComponentName, apn);
if (insertedId == -1) {
showToast(R.string.insert_override_apn_error);
} else {
showToast("Inserted APN id: " + insertedId);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void onRemoveOverrideApn() {
List<ApnSetting> apnSettings =
mDevicePolicyManager.getOverrideApns(mAdminComponentName);
for (ApnSetting apn : apnSettings) {
mDevicePolicyManager.removeOverrideApn(mAdminComponentName, apn.getId());
}
}
private int parseInt(String str, int defaultValue) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
private ApnSetting makeApnSetting(String operatorNumeric, String entryName, String apnName,
InetAddress proxyAddress, int proxyPort, Uri mmsc, InetAddress mmsProxyAddress,
int mmsProxyPort, String user, String password, int authType, int apnTypeBitmask,
int protocol, int roamingProtocol, boolean carrierEnabled, int networkTypeBitmask,
int mvnoType) {
return new ApnSetting.Builder()
.setOperatorNumeric(operatorNumeric)
.setEntryName(entryName)
.setApnName(apnName)
.setProxyAddress(proxyAddress)
.setProxyPort(proxyPort)
.setMmsc(mmsc)
.setMmsProxyAddress(mmsProxyAddress)
.setMmsProxyPort(mmsProxyPort)
.setUser(user)
.setPassword(password)
.setAuthType(authType)
.setApnTypeBitmask(apnTypeBitmask)
.setProtocol(protocol)
.setRoamingProtocol(roamingProtocol)
.setCarrierEnabled(carrierEnabled)
.setMvnoType(mvnoType)
.setNetworkTypeBitmask(networkTypeBitmask)
.build();
}
private Uri UriFromString(String uri) {
return TextUtils.isEmpty(uri) ? null : Uri.parse(uri);
}
private InetAddress inetAddressFromString(String inetAddress) {
if (TextUtils.isEmpty(inetAddress)) {
return null;
}
try {
return InetAddress.getByName(inetAddress);
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Can't parse InetAddress from string: unknown host.");
showToast(R.string.apn_wrong_inetaddress);
return null;
}
}
private void reloadEnableOverrideApnUi() {
boolean enabled = mDevicePolicyManager.isOverrideApnEnabled(mAdminComponentName);
if (mEnableOverrideApnPreference.isEnabled()) {
mEnableOverrideApnPreference.setChecked(enabled);
}
}
private void showToast(int msgId, Object... args) {
showToast(getString(msgId, args), Toast.LENGTH_SHORT);
}
private void showToast(String msg) {
showToast(msg, Toast.LENGTH_SHORT);
}
private void showToast(String msg, int duration) {
Activity activity = getActivity();
if (activity == null || activity.isFinishing()) {
return;
}
Toast.makeText(activity, msg, duration).show();
}
}
|
922ec4fb59f53c70dfea2cc202eb5b86e9d27bc9 | 508 | java | Java | src/test/java/org/humingk/movie/baseTest.java | Hardlipa/douban_movie | f4642116d2507dffbab99d998fb3fc87c12dbf88 | [
"MIT"
] | null | null | null | src/test/java/org/humingk/movie/baseTest.java | Hardlipa/douban_movie | f4642116d2507dffbab99d998fb3fc87c12dbf88 | [
"MIT"
] | null | null | null | src/test/java/org/humingk/movie/baseTest.java | Hardlipa/douban_movie | f4642116d2507dffbab99d998fb3fc87c12dbf88 | [
"MIT"
] | null | null | null | 26.736842 | 71 | 0.785433 | 994,858 | package org.humingk.movie;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* junit启动的时候自动加载springIOC容器
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
"classpath:spring/spring-*.xml",
"classpath:mybatis/mybatis-config.xml"})
@WebAppConfiguration
public class baseTest {
}
|
922ec56a2e9075744c296ca5a3cba52ef0958fd7 | 311 | java | Java | design/src/test/java/com/huifer/design/singleton/nw/SimpleSingletonTest.java | wt1187982580/javaBook-src | 0e920055f40b8fa7e1149974a4dcd4b550c669df | [
"Apache-2.0"
] | 39 | 2019-06-18T07:37:18.000Z | 2022-03-04T01:36:43.000Z | design/src/test/java/com/huifer/design/singleton/nw/SimpleSingletonTest.java | wt1187982580/javaBook-src | 0e920055f40b8fa7e1149974a4dcd4b550c669df | [
"Apache-2.0"
] | 38 | 2019-09-25T06:39:57.000Z | 2022-01-28T00:54:33.000Z | design/src/test/java/com/huifer/design/singleton/nw/SimpleSingletonTest.java | wt1187982580/javaBook-src | 0e920055f40b8fa7e1149974a4dcd4b550c669df | [
"Apache-2.0"
] | 15 | 2019-10-31T10:28:24.000Z | 2021-09-16T06:10:10.000Z | 25.916667 | 53 | 0.620579 | 994,859 | package com.huifer.design.singleton.nw;
public class SimpleSingletonTest {
public static void main(String[] args) {
Thread t1 = new Thread(new ExecutorThread());
Thread t2 = new Thread(new ExecutorThread());
t1.start();
t2.start();
System.out.println("结束");
}
} |
922ec6467a90deaa248f69f579b0282f4b2468ba | 20,892 | java | Java | nutz-plugins-ngrok/src/main/java/org/nutz/plugins/ngrok/server/NgrokServer.java | lihongwu19921215/nutzmore | 798fc634128c8bb4239e3b76a233b87c7a2932cc | [
"Apache-2.0"
] | null | null | null | nutz-plugins-ngrok/src/main/java/org/nutz/plugins/ngrok/server/NgrokServer.java | lihongwu19921215/nutzmore | 798fc634128c8bb4239e3b76a233b87c7a2932cc | [
"Apache-2.0"
] | null | null | null | nutz-plugins-ngrok/src/main/java/org/nutz/plugins/ngrok/server/NgrokServer.java | lihongwu19921215/nutzmore | 798fc634128c8bb4239e3b76a233b87c7a2932cc | [
"Apache-2.0"
] | null | null | null | 43.798742 | 163 | 0.461181 | 994,860 | package org.nutz.plugins.ngrok.server;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.nutz.lang.Stopwatch;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.plugins.ngrok.common.NgrokAgent;
import org.nutz.plugins.ngrok.common.NgrokMsg;
import org.nutz.plugins.ngrok.common.PipedStreamThread;
import org.nutz.plugins.ngrok.common.StatusProvider;
import org.nutz.plugins.ngrok.server.NgrokServer.NgrokServerClient.ProxySocket;
import org.nutz.plugins.ngrok.server.auth.DefaultNgrokAuthProvider;
import org.nutz.plugins.ngrok.server.auth.NgrokAuthProvider;
import org.nutz.plugins.ngrok.server.auth.SimpleRedisAuthProvider;
public class NgrokServer implements Callable<Object>, StatusProvider<Integer> {
private static final Log log = Logs.get();
public transient SSLServerSocket mainCtlSS;
public transient ServerSocket httpSS;
public transient SSLServerSocketFactory sslServerSocketFactory;
public String ssl_jks_password = "123456";
public byte[] ssl_jks;
public String ssl_jks_path;
public int srv_port = 4443;
public int http_port = 9080;
public ExecutorService executorService;
public int status;
public Map<String, NgrokServerClient> clients = new ConcurrentHashMap<String, NgrokServerClient>();
public NgrokAuthProvider auth;
public String srv_host = "wendal.cn";
public int client_proxy_init_size = 1;
public int client_proxy_wait_timeout = 30 * 1000;
public Map<String, String> hostmap = new ConcurrentHashMap<String, String>();
public Map<String, String> reqIdMap = new ConcurrentHashMap<String, String>();
public int bufSize = 8192;
public boolean redis;
public String redis_host= "127.0.0.1";
public int redis_port = 6379;
public String redis_key = "ngrok";
public String redis_rkey;
public void start() throws Exception {
log.debug("NgrokServer start ...");
if (sslServerSocketFactory == null)
sslServerSocketFactory = buildSSL();
if (executorService == null) {
log.debug("using default CachedThreadPool");
executorService = Executors.newCachedThreadPool();
}
if (auth == null) {
if (redis) {
log.debug("using redis auth provider");
auth = new SimpleRedisAuthProvider(redis_host, redis_port, redis_key);
} else {
log.debug("using default ngrok auth provider");
auth = new DefaultNgrokAuthProvider();
}
} else {
log.debug("using custom auth provider class=" + auth.getClass().getName());
}
status = 1;
// 先创建监听,然后再启动哦,
log.debug("start listen srv_port=" + srv_port);
mainCtlSS = (SSLServerSocket) sslServerSocketFactory.createServerSocket(srv_port);
log.debug("start listen http_port=" + http_port);
httpSS = new ServerSocket(http_port);
log.debug("start Contrl Thread...");
executorService.submit(this);
log.debug("start Http Thread...");
executorService.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
while (status == 1) {
Socket socket = httpSS.accept();
executorService.submit(new HttpThread(socket));
}
return null;
}
});
}
public void stop() {
status = 3;
executorService.shutdown();
}
@Override
public Object call() throws Exception {
while (status == 1) {
Socket socket = mainCtlSS.accept();
executorService.submit(new NgrokServerClient(socket));
}
return null;
}
public SSLServerSocketFactory buildSSL() throws Exception {
log.debug("try to load Java KeyStore File ...");
KeyStore ks = KeyStore.getInstance("JKS");
if (ssl_jks != null)
ks.load(new ByteArrayInputStream(ssl_jks), ssl_jks_password.toCharArray());
else if (ssl_jks_path != null) {
log.debug("load jks from " + this.ssl_jks_path);
ks.load(new FileInputStream(this.ssl_jks_path), ssl_jks_password.toCharArray());
}
else if (new File(srv_host + ".jks").exists()) {
log.debug("load jks from " + srv_host + ".jks");
ks.load(new FileInputStream(srv_host + ".jks"), ssl_jks_password.toCharArray());
}
else
throw new RuntimeException("must set ssl_jks_path or ssl_jks");
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(ks);
TrustManager[] tms = tmfactory.getTrustManagers();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, ssl_jks_password.toCharArray());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(kmf.getKeyManagers(), tms, new SecureRandom());
return sc.getServerSocketFactory();
}
public class NgrokServerClient implements Callable<Object> {
protected Socket socket;
protected InputStream ins;
protected OutputStream out;
protected boolean proxyMode;
protected boolean authed;
public String id;
public ArrayBlockingQueue<ProxySocket> idleProxys = new ArrayBlockingQueue<NgrokServer.NgrokServerClient.ProxySocket>(128);
public NgrokMsg authMsg;
public long lastPing;
public boolean gzip_proxy;
public NgrokServerClient(Socket socket) {
this.socket = socket;
}
public Object call() throws Exception {
try {
this.ins = socket.getInputStream();
this.out = socket.getOutputStream();
while (true) {
NgrokMsg msg = NgrokAgent.readMsg(ins);
String type = msg.getType();
if ("Auth".equals(type)) {
if (authed) {
NgrokMsg.authResp("", "Auth Again?!!").write(out);
break;
}
if (!auth.check(NgrokServer.this, msg)) {
NgrokMsg.authResp("", "AuthError").write(out);
break;
}
id = msg.getString("ClientId");
if (Strings.isBlank(id))
id = R.UU32();
gzip_proxy = msg.getBoolean("GzipProxy", false);
if (log.isDebugEnabled())
log.debugf("New Client >> id=%s gzip_proxy=%s", id, gzip_proxy);
NgrokMsg.authResp(id, "").write(out);
msg.put("ClientId", id);
authMsg = msg;
authed = true;
lastPing = System.currentTimeMillis();
clients.put(id, this);
} else if ("ReqTunnel".equals(type)) {
if (!authed) {
NgrokMsg.newTunnel("", "", "", "Not Auth Yet").write(out);
break;
}
String[] mapping = auth.mapping(NgrokServer.this, NgrokServerClient.this, msg);
if (mapping == null || mapping.length == 0) {
NgrokMsg.newTunnel("",
"",
"",
"pls check your token").write(out);
break;
}
for (String host : mapping) {
String prevClientId = hostmap.get(host);
if (prevClientId != null) {
NgrokServerClient prevClient = clients.get(prevClientId);
if (prevClient != null) {
if (prevClient.socket.isConnected()) {
log.debug("dup connect!!! host=" + host);
NgrokMsg.newTunnel("",
"",
"",
"host="+host+" is used by another client!!!").write(out);
break;
} else {
prevClient.clean();
}
}
}
}
String reqId = msg.getString("ReqId");
for (String host : mapping) {
NgrokMsg.newTunnel(reqId,
"http://" + host,
"http",
"").write(out);
hostmap.put(host, id); // 冲突了怎么办?
reqIdMap.put(host, reqId);
reqProxy(host);
}
} else if ("Ping".equals(type)) {
NgrokMsg.pong().write(out);
} else if ("Pong".equals(type)) {
lastPing = System.currentTimeMillis();
} else if ("RegProxy".equals(type)) {
String clientId = msg.getString("ClientId");
NgrokServerClient client = clients.get(clientId);
if (client == null) {
log.debug("not such client id=" + clientId);
break;
}
proxyMode = true;
ProxySocket proxySocket = new ProxySocket(socket);
client.idleProxys.add(proxySocket);
break;
} else {
log.info("Bad Type=" + type);
break;
}
}
}
finally {
if (!proxyMode) {
Streams.safeClose(socket);
clean();
}
}
return null;
}
public boolean reqProxy(String host) throws IOException {
String reqId = reqIdMap.get(host);
if (reqId == null)
return false;
for (int i = 0; i < 5; i++) {
NgrokAgent.writeMsg(out, NgrokMsg.reqProxy(reqId, "http://" + host, "http", ""));
}
return true;
}
public class ProxySocket {
public Socket socket;
public ProxySocket(Socket socket) {
this.socket = socket;
}
}
public ProxySocket getProxy(String host) throws Exception {
ProxySocket ps = null;
while (true) {
ps = idleProxys.poll();
if (ps == null)
break;
if (!ps.socket.isClosed())
return ps;
}
if (ps == null) {
if (log.isDebugEnabled())
log.debugf("req proxy conn for host[%s]", host);
if (reqProxy(host))
ps = idleProxys.poll(client_proxy_wait_timeout, TimeUnit.MILLISECONDS);
}
return ps;
}
public void clean() {
clients.remove(id);
while (true) {
ProxySocket proxySocket = idleProxys.poll();
if (proxySocket != null)
Streams.safeClose(proxySocket.socket);
else
break;
}
}
public boolean isRunning() {
return socket != null && socket.isConnected();
}
}
public class HttpThread implements Callable<Object> {
public Socket socket;
public HttpThread(Socket socket) {
super();
this.socket = socket;
}
public Object call() throws Exception {
//if (log.isDebugEnabled())
// log.debug("NEW Http Request ...");
Stopwatch sw = Stopwatch.begin();
InputStream _ins = socket.getInputStream();
OutputStream _out = socket.getOutputStream();
ByteArrayOutputStream bao = new ByteArrayOutputStream(8192);
ByteArrayOutputStream line_buffer_bao = new ByteArrayOutputStream();
int line_len = 0;
int count = 0;
byte[] buf = new byte[1];
String firstLine = null;
while (true) {
int len = _ins.read(buf);
if (len == -1)
break;
else if (len == 0)
continue;
count++;
if (count > 8192) {
NgrokAgent.httpResp(_out, 400, "无法读取合法的Host,拒绝访问.不允许ip直接访问,同时Host必须存在于请求的前8192个字节!");
socket.close();
return null;
}
bao.write(buf);
if (buf[0] == '\n') {
if (line_len == 0) {
break;
} else {
// 读取了有效的一行,那么, 解析一下吧
if (line_len > 8) { // Host: wendal.cn 域名起码3位吧?
byte[] line_buf = line_buffer_bao.toByteArray();
String line = new String(line_buf).trim().toLowerCase();
if (firstLine == null) {
firstLine = line;
}
//log.debug("Header Line --> " + line);
// 看看是不是Host
// 有可能是Host或者host哦
else if (line.startsWith("host") && line.contains(":")) {
String host = line.split("[\\:]")[1].trim();
sw.tag("Read Host");
if (log.isDebugEnabled())
log.debugf("Host[%s] >> %s", host, firstLine);
String clientId = hostmap.get(host);
if (clientId == null) {
NgrokAgent.httpResp(_out, 404, "Tunnel " + host + " not found");
socket.close();
return null;
}
NgrokServerClient client = clients.get(clientId);
if (client == null) {
NgrokAgent.httpResp(_out, 404, "Tunnel " + host + " is Closed");
socket.close();
return null;
}
ProxySocket proxySocket;
try {
proxySocket = client.getProxy(host);
}
catch (Exception e) {
log.debug("Get ProxySocket FAIL host=" + host);
NgrokAgent.httpResp(_out, 500, "Tunnel "
+ host
+ "did't has any proxy conntion yet!!");
socket.close();
return null;
}
sw.tag("After Get ProxySocket");
PipedStreamThread srv2loc = null;
PipedStreamThread loc2srv = null;
try {
NgrokAgent.writeMsg(proxySocket.socket.getOutputStream(),
NgrokMsg.startProxy("http://" + host, ""));
sw.tag("After Send Start Proxy");
proxySocket.socket.getOutputStream().write(bao.toByteArray());
// 服务器-->本地
srv2loc = new PipedStreamThread("http2proxy",
_ins,
NgrokAgent.gzip_out(client.gzip_proxy, proxySocket.socket.getOutputStream()),
bufSize);
// 本地-->服务器
loc2srv = new PipedStreamThread("proxy2http",
NgrokAgent.gzip_in(client.gzip_proxy, proxySocket.socket.getInputStream()),
_out,
bufSize);
sw.tag("After PipedStream Make");
sw.stop();
log.debug("ProxyConn Timeline = " + sw.toString());
// 等待其中任意一个管道的关闭
String exitFirst = executorService.invokeAny(Arrays.asList(srv2loc,
loc2srv));
if (log.isDebugEnabled())
log.debug("proxy conn exit first at " + exitFirst);
}
catch (Exception e) {
log.debug("done?", e);
}
finally {
Streams.safeClose(proxySocket.socket);
Streams.safeClose(socket);
if (srv2loc != null && loc2srv != null)
auth.record(host, srv2loc.getCount(), loc2srv.getCount());
}
return null;
}
}
line_buffer_bao.reset();
line_len = 0;
}
}
line_buffer_bao.write(buf, 0, 1);
line_len++;
}
socket.close();
return null;
}
}
@Override
public Integer getStatus() {
return status;
}
public static void main(String[] args) throws Exception {
// System.setProperty("javax.net.debug","all");
NgrokServer server = new NgrokServer();
if (!NgrokAgent.fixFromArgs(server, args)) {
log.debug("usage : -srv_host=wendal.cn -srv_port=4443 -http_port=9080 -ssl_jks=wendal.cn.jks -ssl_jks_password=123456 -conf_file=xxx.properties");
}
server.start();
}
// 使用 crt和key文件, 也就是nginx使用的证书,生成jks的步骤
// 首先, 使用openssl生成p12文件,必须输入密码
// openssl pkcs12 -export -in 1_wendal.cn_bundle.crt -inkey 2_wendal.cn.key
// -out wendal.cn.p12
// 然后, 使用keytool 生成jks
// keytool -importkeystore -destkeystore wendal.cn.jks -srckeystore
// wendal.cn.p12 -srcstoretype pkcs12 -alias 1
}
|
922ec6d2594f0297d468c2b1ff3fd323fb83fb30 | 771 | java | Java | plugin-api/src/main/java/com/megaease/easeagent/plugin/matcher/operator/Operator.java | LodgeGong/easeagent | b86a6f6dcdecf91b4d5c14ea8d7d5edf124664de | [
"Apache-2.0"
] | 403 | 2021-01-15T08:40:18.000Z | 2022-03-31T13:08:01.000Z | plugin-api/src/main/java/com/megaease/easeagent/plugin/matcher/operator/Operator.java | LodgeGong/easeagent | b86a6f6dcdecf91b4d5c14ea8d7d5edf124664de | [
"Apache-2.0"
] | 78 | 2021-01-18T04:22:40.000Z | 2022-03-25T23:57:44.000Z | plugin-api/src/main/java/com/megaease/easeagent/plugin/matcher/operator/Operator.java | LodgeGong/easeagent | b86a6f6dcdecf91b4d5c14ea8d7d5edf124664de | [
"Apache-2.0"
] | 77 | 2021-01-15T10:19:25.000Z | 2022-03-22T14:39:20.000Z | 30.84 | 75 | 0.722438 | 994,861 | /*
* Copyright (c) 2021, MegaEase
* 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.
* 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.megaease.easeagent.plugin.matcher.operator;
public interface Operator<S> {
S and(S matcher);
S or(S matcher);
S negate();
}
|
922ec6f0a5635eddd474cc65b986645d1cfd5f32 | 10,273 | java | Java | kubernetes-model-generator/kubernetes-model-node/src/generated/java/io/fabric8/kubernetes/api/model/KubeSchema.java | OneCricketeer/kubernetes-client | 15ba0dd6c7e452c8f53905f23e3c22d35e9b1d9b | [
"Apache-2.0"
] | 2,460 | 2015-08-26T08:44:49.000Z | 2022-03-31T09:52:23.000Z | kubernetes-model-generator/kubernetes-model-node/src/generated/java/io/fabric8/kubernetes/api/model/KubeSchema.java | OneCricketeer/kubernetes-client | 15ba0dd6c7e452c8f53905f23e3c22d35e9b1d9b | [
"Apache-2.0"
] | 3,934 | 2015-07-16T14:51:50.000Z | 2022-03-31T20:14:44.000Z | kubernetes-model-generator/kubernetes-model-node/src/generated/java/io/fabric8/kubernetes/api/model/KubeSchema.java | OneCricketeer/kubernetes-client | 15ba0dd6c7e452c8f53905f23e3c22d35e9b1d9b | [
"Apache-2.0"
] | 1,259 | 2015-07-16T14:36:46.000Z | 2022-03-31T09:52:26.000Z | 36.953237 | 728 | 0.749246 | 994,862 |
package io.fabric8.kubernetes.api.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.version.Info;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"apiVersion",
"kind",
"metadata",
"BaseKubernetesList",
"Info",
"ObjectMeta",
"ObjectReference",
"Quantity",
"Status",
"TypeMeta",
"V1RuntimeClass",
"V1RuntimeClassList",
"V1alpha1RuntimeClass",
"V1alpha1RuntimeClassList",
"V1beta1RuntimeClass",
"V1beta1RuntimeClassList"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
"_",
""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
@BuildableReference(io.fabric8.kubernetes.api.model.ObjectMeta.class),
@BuildableReference(LabelSelector.class),
@BuildableReference(Container.class),
@BuildableReference(PodTemplateSpec.class),
@BuildableReference(ResourceRequirements.class),
@BuildableReference(IntOrString.class),
@BuildableReference(io.fabric8.kubernetes.api.model.ObjectReference.class),
@BuildableReference(LocalObjectReference.class),
@BuildableReference(PersistentVolumeClaim.class)
})
public class KubeSchema {
@JsonProperty("BaseKubernetesList")
private BaseKubernetesList baseKubernetesList;
@JsonProperty("Info")
private Info info;
@JsonProperty("ObjectMeta")
private io.fabric8.kubernetes.api.model.ObjectMeta objectMeta;
@JsonProperty("ObjectReference")
private io.fabric8.kubernetes.api.model.ObjectReference objectReference;
@JsonProperty("Quantity")
private Quantity quantity;
@JsonProperty("Status")
private Status status;
@JsonProperty("TypeMeta")
private TypeMeta typeMeta;
@JsonProperty("V1RuntimeClass")
private io.fabric8.kubernetes.api.model.node.v1.RuntimeClass v1RuntimeClass;
@JsonProperty("V1RuntimeClassList")
private io.fabric8.kubernetes.api.model.node.v1.RuntimeClassList v1RuntimeClassList;
@JsonProperty("V1alpha1RuntimeClass")
private io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClass v1alpha1RuntimeClass;
@JsonProperty("V1alpha1RuntimeClassList")
private io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClassList v1alpha1RuntimeClassList;
@JsonProperty("V1beta1RuntimeClass")
private io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClass v1beta1RuntimeClass;
@JsonProperty("V1beta1RuntimeClassList")
private io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClassList v1beta1RuntimeClassList;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public KubeSchema() {
}
/**
*
* @param quantity
* @param v1RuntimeClassList
* @param baseKubernetesList
* @param v1beta1RuntimeClass
* @param objectReference
* @param v1RuntimeClass
* @param typeMeta
* @param objectMeta
* @param v1alpha1RuntimeClass
* @param v1alpha1RuntimeClassList
* @param v1beta1RuntimeClassList
* @param info
* @param status
*/
public KubeSchema(BaseKubernetesList baseKubernetesList, Info info, io.fabric8.kubernetes.api.model.ObjectMeta objectMeta, io.fabric8.kubernetes.api.model.ObjectReference objectReference, Quantity quantity, Status status, TypeMeta typeMeta, io.fabric8.kubernetes.api.model.node.v1.RuntimeClass v1RuntimeClass, io.fabric8.kubernetes.api.model.node.v1.RuntimeClassList v1RuntimeClassList, io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClass v1alpha1RuntimeClass, io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClassList v1alpha1RuntimeClassList, io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClass v1beta1RuntimeClass, io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClassList v1beta1RuntimeClassList) {
super();
this.baseKubernetesList = baseKubernetesList;
this.info = info;
this.objectMeta = objectMeta;
this.objectReference = objectReference;
this.quantity = quantity;
this.status = status;
this.typeMeta = typeMeta;
this.v1RuntimeClass = v1RuntimeClass;
this.v1RuntimeClassList = v1RuntimeClassList;
this.v1alpha1RuntimeClass = v1alpha1RuntimeClass;
this.v1alpha1RuntimeClassList = v1alpha1RuntimeClassList;
this.v1beta1RuntimeClass = v1beta1RuntimeClass;
this.v1beta1RuntimeClassList = v1beta1RuntimeClassList;
}
@JsonProperty("BaseKubernetesList")
public BaseKubernetesList getBaseKubernetesList() {
return baseKubernetesList;
}
@JsonProperty("BaseKubernetesList")
public void setBaseKubernetesList(BaseKubernetesList baseKubernetesList) {
this.baseKubernetesList = baseKubernetesList;
}
@JsonProperty("Info")
public Info getInfo() {
return info;
}
@JsonProperty("Info")
public void setInfo(Info info) {
this.info = info;
}
@JsonProperty("ObjectMeta")
public io.fabric8.kubernetes.api.model.ObjectMeta getObjectMeta() {
return objectMeta;
}
@JsonProperty("ObjectMeta")
public void setObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta objectMeta) {
this.objectMeta = objectMeta;
}
@JsonProperty("ObjectReference")
public io.fabric8.kubernetes.api.model.ObjectReference getObjectReference() {
return objectReference;
}
@JsonProperty("ObjectReference")
public void setObjectReference(io.fabric8.kubernetes.api.model.ObjectReference objectReference) {
this.objectReference = objectReference;
}
@JsonProperty("Quantity")
public Quantity getQuantity() {
return quantity;
}
@JsonProperty("Quantity")
public void setQuantity(Quantity quantity) {
this.quantity = quantity;
}
@JsonProperty("Status")
public Status getStatus() {
return status;
}
@JsonProperty("Status")
public void setStatus(Status status) {
this.status = status;
}
@JsonProperty("TypeMeta")
public TypeMeta getTypeMeta() {
return typeMeta;
}
@JsonProperty("TypeMeta")
public void setTypeMeta(TypeMeta typeMeta) {
this.typeMeta = typeMeta;
}
@JsonProperty("V1RuntimeClass")
public io.fabric8.kubernetes.api.model.node.v1.RuntimeClass getV1RuntimeClass() {
return v1RuntimeClass;
}
@JsonProperty("V1RuntimeClass")
public void setV1RuntimeClass(io.fabric8.kubernetes.api.model.node.v1.RuntimeClass v1RuntimeClass) {
this.v1RuntimeClass = v1RuntimeClass;
}
@JsonProperty("V1RuntimeClassList")
public io.fabric8.kubernetes.api.model.node.v1.RuntimeClassList getV1RuntimeClassList() {
return v1RuntimeClassList;
}
@JsonProperty("V1RuntimeClassList")
public void setV1RuntimeClassList(io.fabric8.kubernetes.api.model.node.v1.RuntimeClassList v1RuntimeClassList) {
this.v1RuntimeClassList = v1RuntimeClassList;
}
@JsonProperty("V1alpha1RuntimeClass")
public io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClass getV1alpha1RuntimeClass() {
return v1alpha1RuntimeClass;
}
@JsonProperty("V1alpha1RuntimeClass")
public void setV1alpha1RuntimeClass(io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClass v1alpha1RuntimeClass) {
this.v1alpha1RuntimeClass = v1alpha1RuntimeClass;
}
@JsonProperty("V1alpha1RuntimeClassList")
public io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClassList getV1alpha1RuntimeClassList() {
return v1alpha1RuntimeClassList;
}
@JsonProperty("V1alpha1RuntimeClassList")
public void setV1alpha1RuntimeClassList(io.fabric8.kubernetes.api.model.node.v1alpha1.RuntimeClassList v1alpha1RuntimeClassList) {
this.v1alpha1RuntimeClassList = v1alpha1RuntimeClassList;
}
@JsonProperty("V1beta1RuntimeClass")
public io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClass getV1beta1RuntimeClass() {
return v1beta1RuntimeClass;
}
@JsonProperty("V1beta1RuntimeClass")
public void setV1beta1RuntimeClass(io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClass v1beta1RuntimeClass) {
this.v1beta1RuntimeClass = v1beta1RuntimeClass;
}
@JsonProperty("V1beta1RuntimeClassList")
public io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClassList getV1beta1RuntimeClassList() {
return v1beta1RuntimeClassList;
}
@JsonProperty("V1beta1RuntimeClassList")
public void setV1beta1RuntimeClassList(io.fabric8.kubernetes.api.model.node.v1beta1.RuntimeClassList v1beta1RuntimeClassList) {
this.v1beta1RuntimeClassList = v1beta1RuntimeClassList;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
922ec770358e08949b8d873a46f54f9b630700fa | 1,405 | java | Java | java2typescript-jackson/src/test/java/java2typescript/jackson/module/TypeRenamingWithEnclosingClassTest.java | JLLeitschuh/java2typescript | 5e3921b674bfb03ba9ac042238a8db0b9b17ca3a | [
"Apache-2.0"
] | 132 | 2015-01-21T15:09:59.000Z | 2022-03-26T23:53:38.000Z | java2typescript-jackson/src/test/java/java2typescript/jackson/module/TypeRenamingWithEnclosingClassTest.java | atsu85/java2typescript | cf01e5e84f16a3b8ba60c18a88a201453698d175 | [
"Apache-2.0"
] | 49 | 2015-12-28T11:13:58.000Z | 2021-11-09T19:14:11.000Z | java2typescript-jackson/src/test/java/java2typescript/jackson/module/TypeRenamingWithEnclosingClassTest.java | atsu85/java2typescript | cf01e5e84f16a3b8ba60c18a88a201453698d175 | [
"Apache-2.0"
] | 48 | 2015-02-13T14:12:12.000Z | 2022-02-14T10:27:03.000Z | 27.019231 | 91 | 0.8121 | 994,863 | package java2typescript.jackson.module;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java2typescript.jackson.module.conf.typename.WithEnclosingClassTSTypeNamingStrategy;
import java2typescript.jackson.module.grammar.Module;
import java2typescript.jackson.module.util.ExpectedOutputChecker;
import java2typescript.jackson.module.util.TestUtil;
import java2typescript.jackson.module.writer.ExternalModuleFormatWriter;
public class TypeRenamingWithEnclosingClassTest {
static class TestClass {
public String fieldOfInnerClass;
public java2typescript.jackson.module.TestClass other;
public ClassToRename renamedWithAnnotation;
}
@JsonTypeName("ClassNameChangedWithAnnotation")
static class ClassToRename {
public String field;
}
@Test
public void twoClassesWithSameName() throws IOException {
// Arrange
Configuration conf = new Configuration();
conf.setNamingStrategy(new WithEnclosingClassTSTypeNamingStrategy());
Module module = TestUtil.createTestModule(conf, TestClass.class);
Writer out = new StringWriter();
// Act
new ExternalModuleFormatWriter().write(module, out);
out.close();
System.out.println(out);
// Assert
ExpectedOutputChecker.checkOutputFromFile(out);
}
}
class TestClass {
public String fieldOfPackageProtectedClass;
}
|
922ec7cb76588ab1796bfd55488d68c8075da134 | 2,455 | java | Java | sample/src/main/java/com/jemshit/elitemvpsample/sample_4_rx2_disposable/Sample4Activity.java | jemshit/EliteMvp | 3844796242a7983ba46d31855b4102d2832869d0 | [
"Apache-2.0"
] | 34 | 2016-12-26T13:41:05.000Z | 2020-10-21T08:35:32.000Z | sample/src/main/java/com/jemshit/elitemvpsample/sample_4_rx2_disposable/Sample4Activity.java | jemshit/EliteMvp | 3844796242a7983ba46d31855b4102d2832869d0 | [
"Apache-2.0"
] | 1 | 2017-07-06T05:32:31.000Z | 2017-07-06T07:37:38.000Z | sample/src/main/java/com/jemshit/elitemvpsample/sample_4_rx2_disposable/Sample4Activity.java | jemshit/EliteMvp | 3844796242a7983ba46d31855b4102d2832869d0 | [
"Apache-2.0"
] | 5 | 2017-06-19T02:51:28.000Z | 2019-07-18T02:53:56.000Z | 34.577465 | 103 | 0.705499 | 994,864 | /*
* Copyright (c) 2017 Jemshit Iskanderov.
*
* 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.jemshit.elitemvpsample.sample_4_rx2_disposable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.TextView;
import com.jemshit.elitemvpsample.R;
public class Sample4Activity extends AppCompatActivity implements Sample4Contract.View {
private TextView textView;
private Sample4Contract.Presenter presenter;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_rx);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(getString(R.string.example_rx2));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Initialize Presenter
presenter = new Sample4Presenter();
// Attach View to it
presenter.attachView(this);
// FindViewByIds, ClickListeners
textView = (TextView) findViewById(R.id.text_sampleRx_list);
AppCompatButton buttonGenerate = (AppCompatButton) findViewById(R.id.button_sampleRx_generate);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
// Call Presenter Method
presenter.createList();
}
});
}
// Called by Presenter
@Override @SuppressWarnings("SetTextI18n")
public void showList(String item) {
textView.setText(textView.getText() + "\n" + item);
}
// Destroy (Detach View from) Presenter. Also unsubscribes from Subscriptions
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDestroy();
}
} |
922ec7e3ced53f0475cd21214b06eb2ca6260664 | 7,430 | java | Java | monitor-object/src/main/java/com/iluwatar/monitor/AbstractMonitor.java | nikhilbarar/java-design-patterns | 535431fac16923a685afc59e287bc8d2a8d4636a | [
"MIT"
] | null | null | null | monitor-object/src/main/java/com/iluwatar/monitor/AbstractMonitor.java | nikhilbarar/java-design-patterns | 535431fac16923a685afc59e287bc8d2a8d4636a | [
"MIT"
] | null | null | null | monitor-object/src/main/java/com/iluwatar/monitor/AbstractMonitor.java | nikhilbarar/java-design-patterns | 535431fac16923a685afc59e287bc8d2a8d4636a | [
"MIT"
] | null | null | null | 31.350211 | 82 | 0.699865 | 994,865 | /**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.monitor;
import java.util.ArrayList;
/**
* A class for Monitors. Monitors provide coordination of concurrent threads.
* Each Monitor protects some resource, usually data. At each point in time a
* monitor object is occupied by at most one thread.
*/
public abstract class AbstractMonitor {
final Semaphore entrance = new Semaphore(1);
volatile Thread occupant = null;
private final ArrayList<MonitorListener> listOfListeners = new ArrayList<>();
private final String name;
public String getName() {
return name;
}
protected AbstractMonitor() {
this(null);
}
protected AbstractMonitor(String name) {
this.name = name;
}
/**
* The invariant. The default implementation always returns true. This method
* should be overridden if at all possible with the strongest economically
* evaluable invariant.
*/
protected boolean invariant() {
return true;
}
/**
* Enter the monitor. Any thread calling this method is delayed until the
* monitor is unoccupied. Upon returning from this method, the monitor is
* considered occupied. A thread must not attempt to enter a Monitor it is
* already in.
*/
protected void enter() {
notifyCallEnter();
entrance.acquire();
// The following assertion should never trip!
Assertion.check(occupant == null, "2 threads in one monitor");
occupant = Thread.currentThread();
notifyReturnFromEnter();
Assertion.check(invariant(), "Invariant of monitor " + getName());
}
/**
* Leave the monitor. After returning from this method, the thread no longer
* occupies the monitor. Only a thread that is in the monitor may leave it.
*
* @throws AssertionError
* if the thread that leaves is not the occupant.
*/
protected void leave() {
notifyLeaveMonitor();
leaveWithoutATrace();
}
/**
* Leave the monitor. After returning from this method, the thread no longer
* occupies the monitor. Only a thread that is in the monitor may leave it.
*
* @throws AssertionError
* if the thread that leaves is not the occupant.
*/
protected <T> T leave(T result) {
leave();
return result;
}
void leaveWithoutATrace() {
Assertion.check(invariant(), "Invariant of monitor " + getName());
Assertion.check(occupant == Thread.currentThread(), "Thread is not occupant");
occupant = null;
entrance.release();
}
/**
* Run the runnable inside the monitor. Any thread calling this method will be
* delayed until the monitor is empty. The "run" method of its argument is then
* executed within the protection of the monitor. When the run method returns,
* if the thread still occupies the monitor, it leaves the monitor.
*
* @param runnable
* A Runnable object.
*/
protected void doWithin(Runnable runnable) {
enter();
try {
runnable.run();
} finally {
if (occupant == Thread.currentThread()) {
leave();
}
}
}
/**
* Run the runnable inside the monitor. Any thread calling this method will be
* delayed until the monitor is empty. The "run" method of its argument is then
* executed within the protection of the monitor. When the run method returns,
* if the thread still occupies the monitor, it leaves the monitor. Thus the
* signalAndLeave method may be called within the run method.
*
* @param runnable
* A RunnableWithResult object.
* @return The value computed by the run method of the runnable.
*/
protected <T> T doWithin(RunnableWithResult<T> runnable) {
enter();
try {
return runnable.run();
} finally {
if (occupant == Thread.currentThread()) {
leave();
}
}
}
/**
* Create a condition queue associated with a checked Assertion. The Assertion
* will be checked prior to an signal of the condition.
*/
protected Condition makeCondition(Assertion prop) {
return makeCondition(null, prop);
}
/**
* Create a condition queue with no associated checked Assertion.
*/
protected Condition makeCondition() {
return makeCondition(null, TrueAssertion.SINGLETON);
}
/**
* Create a condition queue associated with a checked Assertion. The Assertion
* will be checked prior to an signal of the condition.
*/
protected Condition makeCondition(String name, Assertion prop) {
return new Condition(name, this, prop);
}
/**
* Create a condition queue with no associated checked Assertion.
*/
protected Condition makeCondition(String name) {
return makeCondition(name, TrueAssertion.SINGLETON);
}
/** Register a listener. */
public void addListener(MonitorListener newListener) {
listOfListeners.add(newListener);
}
private void notifyCallEnter() {
for (MonitorListener listener : listOfListeners) {
listener.callEnterMonitor(this);
}
}
private void notifyReturnFromEnter() {
for (MonitorListener listener : listOfListeners) {
listener.returnFromEnterMonitor(this);
}
}
private void notifyLeaveMonitor() {
for (MonitorListener listener : listOfListeners) {
listener.leaveMonitor(this);
}
}
void notifyCallAwait(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.callAwait(condition, this);
}
}
void notifyReturnFromAwait(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.returnFromAwait(condition, this);
}
}
void notifySignallerAwakesAwaitingThread(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.signallerAwakesAwaitingThread(condition, this);
}
}
void notifySignallerLeavesTemporarily(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.signallerLeavesTemporarily(condition, this);
}
}
void notifySignallerReenters(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.signallerReenters(condition, this);
}
}
void notifySignallerLeavesMonitor(Condition condition) {
for (MonitorListener listener : listOfListeners) {
listener.signallerLeavesMonitor(condition, this);
}
}
}
|
922ec9b5dc373be0332e30780218c78b503d1c20 | 222 | java | Java | lowesForGeeks/src/test/java/com/lowes/lowesForGeeks/LowesForGeeksApplicationTests.java | amangautm/lowesForGeeks | 76de2e7697ed7e78379a5d08fa23fb72c8570557 | [
"Apache-2.0"
] | 1 | 2020-05-13T15:24:42.000Z | 2020-05-13T15:24:42.000Z | lowesForGeeks/src/test/java/com/lowes/lowesForGeeks/LowesForGeeksApplicationTests.java | amangautm/lowesForGeeks | 76de2e7697ed7e78379a5d08fa23fb72c8570557 | [
"Apache-2.0"
] | 1 | 2020-05-20T17:05:31.000Z | 2020-05-20T17:18:55.000Z | lowesForGeeks/src/test/java/com/lowes/lowesForGeeks/LowesForGeeksApplicationTests.java | amangautm/lowesForGeeks | 76de2e7697ed7e78379a5d08fa23fb72c8570557 | [
"Apache-2.0"
] | null | null | null | 15.857143 | 60 | 0.797297 | 994,866 | package com.lowes.lowesForGeeks;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LowesForGeeksApplicationTests {
@Test
void contextLoads() {
}
}
|
922eca3961b5fc3e27620c8c6dc92d5303532963 | 95 | java | Java | socialbus-server/src/main/java/pt/sapo/labs/twitterecho/IApp.java | up201809108/socialbustl | 3a32a9184e7e2cea2a14091e74055eb8ed9cbcec | [
"MIT"
] | 3 | 2016-11-27T17:20:24.000Z | 2020-09-26T15:14:09.000Z | socialbus-server/src/main/java/pt/sapo/labs/twitterecho/IApp.java | up201809108/socialbustl | 3a32a9184e7e2cea2a14091e74055eb8ed9cbcec | [
"MIT"
] | 6 | 2021-06-04T01:08:16.000Z | 2021-08-09T20:49:36.000Z | socialbus-server/src/main/java/pt/sapo/labs/twitterecho/IApp.java | up201809108/socialbustl | 3a32a9184e7e2cea2a14091e74055eb8ed9cbcec | [
"MIT"
] | 1 | 2017-03-08T17:02:19.000Z | 2017-03-08T17:02:19.000Z | 11.875 | 33 | 0.715789 | 994,867 | package pt.sapo.labs.twitterecho;
public interface IApp {
void start();
void shutDown();
}
|
922eca7a666a0443e14e55df04c2e93891fe3b78 | 4,202 | java | Java | src/main/java/com/github/tm/stindex/MultiDimensionalCoordinateRangesArray.java | STDI-Sys/stindex | 42f175a9f2addc514cfafaea7d85ad1afafbc05e | [
"Apache-2.0"
] | 6 | 2020-01-29T03:00:53.000Z | 2020-05-21T08:59:20.000Z | src/main/java/com/github/tm/stindex/MultiDimensionalCoordinateRangesArray.java | STDI-Sys/stindex | 42f175a9f2addc514cfafaea7d85ad1afafbc05e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/tm/stindex/MultiDimensionalCoordinateRangesArray.java | STDI-Sys/stindex | 42f175a9f2addc514cfafaea7d85ad1afafbc05e | [
"Apache-2.0"
] | 1 | 2020-03-24T14:51:33.000Z | 2020-03-24T14:51:33.000Z | 38.2 | 99 | 0.721799 | 994,868 | /*
* Copyright 2020 Yu Liebing
*
* 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.tm.stindex;
import java.nio.ByteBuffer;
import com.github.tm.stindex.persist.Persistable;
public class MultiDimensionalCoordinateRangesArray implements Persistable {
private MultiDimensionalCoordinateRanges[] rangesArray;
public MultiDimensionalCoordinateRangesArray() {}
public MultiDimensionalCoordinateRangesArray(
final MultiDimensionalCoordinateRanges[] rangesArray) {
this.rangesArray = rangesArray;
}
public MultiDimensionalCoordinateRanges[] getRangesArray() {
return rangesArray;
}
@Override
public byte[] toBinary() {
final byte[][] rangesBinaries = new byte[rangesArray.length][];
int binaryLength = VarintUtils.unsignedIntByteLength(rangesBinaries.length);
for (int i = 0; i < rangesArray.length; i++) {
rangesBinaries[i] = rangesArray[i].toBinary();
binaryLength +=
(VarintUtils.unsignedIntByteLength(rangesBinaries[i].length) + rangesBinaries[i].length);
}
final ByteBuffer buf = ByteBuffer.allocate(binaryLength);
VarintUtils.writeUnsignedInt(rangesBinaries.length, buf);
for (final byte[] rangesBinary : rangesBinaries) {
VarintUtils.writeUnsignedInt(rangesBinary.length, buf);
buf.put(rangesBinary);
}
return buf.array();
}
@Override
public void fromBinary(final byte[] bytes) {
final ByteBuffer buf = ByteBuffer.wrap(bytes);
rangesArray = new MultiDimensionalCoordinateRanges[VarintUtils.readUnsignedInt(buf)];
for (int i = 0; i < rangesArray.length; i++) {
final byte[] rangesBinary = ByteArrayUtils.safeRead(buf, VarintUtils.readUnsignedInt(buf));
rangesArray[i] = new MultiDimensionalCoordinateRanges();
rangesArray[i].fromBinary(rangesBinary);
}
}
public static class ArrayOfArrays implements Persistable {
private MultiDimensionalCoordinateRangesArray[] coordinateArrays;
public ArrayOfArrays() {}
public ArrayOfArrays(final MultiDimensionalCoordinateRangesArray[] coordinateArrays) {
this.coordinateArrays = coordinateArrays;
}
public MultiDimensionalCoordinateRangesArray[] getCoordinateArrays() {
return coordinateArrays;
}
@Override
public byte[] toBinary() {
final byte[][] rangesBinaries = new byte[coordinateArrays.length][];
int binaryLength = VarintUtils.unsignedIntByteLength(rangesBinaries.length);
for (int i = 0; i < coordinateArrays.length; i++) {
rangesBinaries[i] = coordinateArrays[i].toBinary();
binaryLength +=
(VarintUtils.unsignedIntByteLength(rangesBinaries[i].length)
+ rangesBinaries[i].length);
}
final ByteBuffer buf = ByteBuffer.allocate(binaryLength);
VarintUtils.writeUnsignedInt(rangesBinaries.length, buf);
for (final byte[] rangesBinary : rangesBinaries) {
VarintUtils.writeUnsignedInt(rangesBinary.length, buf);
buf.put(rangesBinary);
}
return buf.array();
}
@Override
public void fromBinary(final byte[] bytes) {
final ByteBuffer buf = ByteBuffer.wrap(bytes);
final int coordinateArrayLength = VarintUtils.readUnsignedInt(buf);
ByteArrayUtils.verifyBufferSize(buf, coordinateArrayLength);
coordinateArrays = new MultiDimensionalCoordinateRangesArray[coordinateArrayLength];
for (int i = 0; i < coordinateArrayLength; i++) {
final byte[] rangesBinary = ByteArrayUtils.safeRead(buf, VarintUtils.readUnsignedInt(buf));
coordinateArrays[i] = new MultiDimensionalCoordinateRangesArray();
coordinateArrays[i].fromBinary(rangesBinary);
}
}
}
}
|
922ecb3e4fa53fd7f93a543c99d2d02a711e9b6a | 225 | java | Java | quick-code-core/src/main/java/cn/ablxyw/mapper/SysTokenInfoMapper.java | liangzv/ablxyw | ff4099cb486daa7345921f30e28d3f1be312ff86 | [
"Apache-2.0"
] | null | null | null | quick-code-core/src/main/java/cn/ablxyw/mapper/SysTokenInfoMapper.java | liangzv/ablxyw | ff4099cb486daa7345921f30e28d3f1be312ff86 | [
"Apache-2.0"
] | 1 | 2021-02-23T09:30:52.000Z | 2021-02-23T09:30:52.000Z | quick-code-core/src/main/java/cn/ablxyw/mapper/SysTokenInfoMapper.java | liangzv/ablxyw | ff4099cb486daa7345921f30e28d3f1be312ff86 | [
"Apache-2.0"
] | null | null | null | 16.071429 | 78 | 0.728889 | 994,869 | package cn.ablxyw.mapper;
import cn.ablxyw.entity.SysTokenInfo;
/**
* (TokenInfo)表数据库访问层
*
* @author 魏强
* @since 2018-10-12 16:35:57
*/
public interface SysTokenInfoMapper extends BaseMapper<SysTokenInfo, String> {
}
|
922ecbccd211e2ea1b81ff50e4a1c54069b0334e | 1,546 | java | Java | orders-service/src/main/java/org/famartin/OrdersService.java | famartinrh/dapr-quarkus-warehouse-demo | 563b7140efd8c009a15cd53be81176331083ed8a | [
"MIT"
] | 1 | 2021-09-28T22:07:39.000Z | 2021-09-28T22:07:39.000Z | orders-service/src/main/java/org/famartin/OrdersService.java | famartinrh/dapr-quarkus-warehouse-demo | 563b7140efd8c009a15cd53be81176331083ed8a | [
"MIT"
] | null | null | null | orders-service/src/main/java/org/famartin/OrdersService.java | famartinrh/dapr-quarkus-warehouse-demo | 563b7140efd8c009a15cd53be81176331083ed8a | [
"MIT"
] | null | null | null | 30.313725 | 129 | 0.691462 | 994,870 | package org.famartin;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.dapr.client.DaprClient;
import io.dapr.client.domain.Verb;
import io.vertx.core.json.JsonObject;
@Path("/orders")
public class OrdersService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Inject
DaprClient dapr;
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response processOrder(Order order) {
logger.info("Processing order, item {} quantity {}", order.itemId, order.quantity);
order.orderId = UUID.randomUUID().toString();
Map<String, Object> result = dapr.invokeService(Verb.POST, "stocks-service", "stocks/request", order, Map.class).block();
logger.info("Stock req result {}", result.toString());
Map<String, Object> processedOrder = new HashMap<>();
processedOrder.put("order-id", order.orderId);
processedOrder.put("approved", result.get("approved"));
processedOrder.put("message", result.get("message"));
logger.info("Sending result to processed-orders binding");
dapr.invokeBinding("processed-orders", processedOrder).block();
logger.info("Order successfully processed");
return Response.noContent().build();
}
} |
922ecc563380e0c9b0a483b29b726d31d0220dee | 1,818 | java | Java | src/gwtl-draw/src/main/java/org/discotools/gwt/leaflet/client/draw/edit/EditOptions.java | haleystorm/gwt-leaflet | f46b8d0dea2962379ad81b26f7d9ffe3165e7eff | [
"BSD-3-Clause"
] | null | null | null | src/gwtl-draw/src/main/java/org/discotools/gwt/leaflet/client/draw/edit/EditOptions.java | haleystorm/gwt-leaflet | f46b8d0dea2962379ad81b26f7d9ffe3165e7eff | [
"BSD-3-Clause"
] | null | null | null | src/gwtl-draw/src/main/java/org/discotools/gwt/leaflet/client/draw/edit/EditOptions.java | haleystorm/gwt-leaflet | f46b8d0dea2962379ad81b26f7d9ffe3165e7eff | [
"BSD-3-Clause"
] | null | null | null | 21.388235 | 79 | 0.709021 | 994,871 | package org.discotools.gwt.leaflet.client.draw.edit;
import org.discotools.gwt.leaflet.client.Options;
import org.discotools.gwt.leaflet.client.layers.others.FeatureGroup;
/**
* These options will allow you to configure the draw toolbar and its handlers.
*
* @author Haley Boyd
*
*/
public class EditOptions extends
Options
{
public EditOptions() {
super();
}
/**
* This is the FeatureGroup that stores all editable shapes. THIS IS
* REQUIRED FOR THE EDIT TOOLBAR TO WORK
*
* @param featureGroup
* @return
*/
public EditOptions setFeatureGroup(
FeatureGroup featureGroup ) {
return (EditOptions) setProperty(
"featureGroup",
featureGroup);
}
/**
* Edit handler options. Set to false to disable handler.
*
* @param editHandlerOptions
* @return
*/
public EditOptions setEditHandlerOptions(
EditHandlerOptions editHandlerOptions ) {
return (EditOptions) setProperty(
"edit",
editHandlerOptions);
}
/**
* Edit handler options. Set to false to disable handler.
*
* @param editHandlerOptions
* @return
*/
public EditOptions setEditHandlerOptions(
boolean editHandlerOptions ) {
return (EditOptions) setProperty(
"edit",
editHandlerOptions);
}
/**
* Delete handler options. Set to false to disable handler.
*
* @param deleteHandlerOptions
* @return
*/
public EditOptions setDeleteHandlerOptions(
DeleteHandlerOptions deleteHandlerOptions ) {
return (EditOptions) setProperty(
"remove",
deleteHandlerOptions);
}
/**
* Delete handler options. Set to false to disable handler.
*
* @param deleteHandlerOptions
* @return
*/
public EditOptions setDeleteHandlerOptions(
boolean deleteHandlerOptions ) {
return (EditOptions) setProperty(
"remove",
deleteHandlerOptions);
}
}
|
922eccc7597da9b5d5c60f4435df8549ea52684c | 3,122 | java | Java | modules/indexing/src/test/java/org/apache/ignite/internal/systemview/JmxExporterSpiTest.java | winterheart/ignite | 21a552a1259aff5f97930a4202efb9bde3ad1442 | [
"Apache-2.0"
] | 4,339 | 2015-08-21T21:13:25.000Z | 2022-03-30T09:56:44.000Z | modules/indexing/src/test/java/org/apache/ignite/internal/systemview/JmxExporterSpiTest.java | winterheart/ignite | 21a552a1259aff5f97930a4202efb9bde3ad1442 | [
"Apache-2.0"
] | 1,933 | 2015-08-24T11:37:40.000Z | 2022-03-31T08:37:08.000Z | modules/indexing/src/test/java/org/apache/ignite/internal/systemview/JmxExporterSpiTest.java | winterheart/ignite | 21a552a1259aff5f97930a4202efb9bde3ad1442 | [
"Apache-2.0"
] | 2,140 | 2015-08-21T22:09:00.000Z | 2022-03-25T07:57:34.000Z | 42.189189 | 108 | 0.699872 | 994,872 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.systemview;
import java.util.HashMap;
import java.util.Map;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularDataSupport;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.managers.systemview.JmxSystemViewExporterSpi;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static org.apache.ignite.internal.managers.systemview.SystemViewMBean.VIEWS;
import static org.apache.ignite.internal.processors.query.h2.SchemaManager.SQL_TBL_COLS_VIEW;
/**
* Tests {@link JmxSystemViewExporterSpi}.
*/
public class JmxExporterSpiTest extends GridCommonAbstractTest {
/** @throws Exception If failed. */
@Test
public void testTableColumns() throws Exception {
String tableName = "TEST";
IgniteEx ignite = startGrid(getConfiguration().setCacheConfiguration(
new CacheConfiguration<>(DEFAULT_CACHE_NAME)
.setQueryEntities(F.asList(
new QueryEntity()
.setTableName(tableName)
.setKeyFieldName("ID")
.setValueType(Integer.class.getName())
.addQueryField("ID", Integer.class.getName(), null)))));
Map<String, String> expTypes = new HashMap<>();
expTypes.put("_KEY", null);
expTypes.put("_VAL", null);
expTypes.put("ID", Integer.class.getName());
TabularDataSupport columns =
(TabularDataSupport)metricRegistry(ignite.name(), VIEWS, SQL_TBL_COLS_VIEW).getAttribute(VIEWS);
columns.values().stream().map(data -> (CompositeData)data)
.filter(data -> tableName.equals(data.get("tableName")))
.forEach(data -> {
String columnName = (String)data.get("columnName");
assertTrue("Unexpected column: " + columnName, expTypes.containsKey(columnName));
assertEquals(expTypes.remove(columnName), data.get("type"));
});
assertTrue("Expected columns: " + expTypes.keySet(), expTypes.isEmpty());
}
}
|
922ecd33d7a013541944c6472d2fc5e743bbc06c | 1,878 | java | Java | main/java/aws/proserve/bcs/ce/service/DocumentService.java | aws-samples/bcs-cloud-endure-common | f3356d2095b0508619e87381b5c924688ca0adf8 | [
"MIT-0"
] | null | null | null | main/java/aws/proserve/bcs/ce/service/DocumentService.java | aws-samples/bcs-cloud-endure-common | f3356d2095b0508619e87381b5c924688ca0adf8 | [
"MIT-0"
] | null | null | null | main/java/aws/proserve/bcs/ce/service/DocumentService.java | aws-samples/bcs-cloud-endure-common | f3356d2095b0508619e87381b5c924688ca0adf8 | [
"MIT-0"
] | 1 | 2021-06-10T18:54:38.000Z | 2021-06-10T18:54:38.000Z | 39.125 | 107 | 0.714058 | 994,873 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package aws.proserve.bcs.ce.service;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.model.DocumentFilter;
import com.amazonaws.services.simplesystemsmanagement.model.DocumentFilterKey;
import com.amazonaws.services.simplesystemsmanagement.model.DocumentIdentifier;
import com.amazonaws.services.simplesystemsmanagement.model.ListDocumentsRequest;
import com.amazonaws.services.simplesystemsmanagement.model.ListDocumentsResult;
import javax.annotation.Nullable;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
@Named
public class DocumentService {
@Nullable
public String getDocument(AWSSimpleSystemsManagement ssm, String name) {
return getDocuments(ssm)
.stream()
.filter(i -> i.getName().contains(name))
.findFirst()
.map(DocumentIdentifier::getName)
.orElse(null);
}
public List<DocumentIdentifier> getDocuments(AWSSimpleSystemsManagement ssm) {
final var documents = new ArrayList<DocumentIdentifier>();
final var describeRequest = new ListDocumentsRequest()
.withDocumentFilterList(
new DocumentFilter().withKey(DocumentFilterKey.Owner).withValue("Self"),
new DocumentFilter().withKey(DocumentFilterKey.DocumentType).withValue("Command"));
ListDocumentsResult result;
do {
result = ssm.listDocuments(describeRequest);
describeRequest.setNextToken(result.getNextToken());
documents.addAll(result.getDocumentIdentifiers());
} while (result.getNextToken() != null);
return documents;
}
}
|
922ecd680e54b8fff1c2e5189c5cd04694c0294d | 5,812 | java | Java | src/main/java/com/rultor/agents/github/qtn/QnMerge.java | Piterden/rultor | 6282be86a628683e2916f906a0d4348746b17377 | [
"BSD-3-Clause"
] | 419 | 2015-01-04T00:37:38.000Z | 2022-03-23T19:50:37.000Z | src/main/java/com/rultor/agents/github/qtn/QnMerge.java | Piterden/rultor | 6282be86a628683e2916f906a0d4348746b17377 | [
"BSD-3-Clause"
] | 687 | 2015-01-01T12:49:12.000Z | 2022-03-14T02:00:51.000Z | src/main/java/com/rultor/agents/github/qtn/QnMerge.java | Piterden/rultor | 6282be86a628683e2916f906a0d4348746b17377 | [
"BSD-3-Clause"
] | 168 | 2015-01-03T16:47:03.000Z | 2022-02-22T10:13:16.000Z | 35.278788 | 76 | 0.568287 | 994,874 | /**
* Copyright (c) 2009-2021 Yegor Bugayenko
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.agents.github.qtn;
import com.jcabi.aspects.Immutable;
import com.jcabi.github.Comment;
import com.jcabi.github.Issue;
import com.jcabi.github.Pull;
import com.jcabi.github.PullRef;
import com.jcabi.log.Logger;
import com.rultor.agents.github.Answer;
import com.rultor.agents.github.Question;
import com.rultor.agents.github.Req;
import java.io.IOException;
import java.net.URI;
import java.util.ResourceBundle;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.cactoos.map.MapEntry;
import org.cactoos.map.SolidMap;
/**
* Merge request.
*
* @author Yegor Bugayenko (dycjh@example.com)
* @version $Id: 922ecd680e54b8fff1c2e5189c5cd04694c0294d $
* @since 1.3
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
@Immutable
@ToString
@EqualsAndHashCode
public final class QnMerge implements Question {
/**
* Message bundle.
*/
private static final ResourceBundle PHRASES =
ResourceBundle.getBundle("phrases");
@Override
public Req understand(final Comment.Smart comment,
final URI home) throws IOException {
final Issue.Smart issue = new Issue.Smart(comment.issue());
final Req req;
if (issue.isPull() && issue.isOpen()) {
new Answer(comment).post(
true,
String.format(
QnMerge.PHRASES.getString("QnMerge.start"),
home.toASCIIString()
)
);
Logger.info(
this, "merge request found in %s#%d, comment #%d",
issue.repo().coordinates(), issue.number(), comment.number()
);
req = QnMerge.pack(
comment,
issue.repo().pulls().get(issue.number())
);
} else {
new Answer(comment).post(
false,
QnMerge.PHRASES.getString("QnMerge.already-closed")
);
req = Req.EMPTY;
}
return req;
}
/**
* Pack a pull request.
* @param comment The comment we're in
* @param pull Pull
* @return Req
* @throws IOException If fails
*/
private static Req pack(final Comment.Smart comment,
final Pull pull) throws IOException {
final PullRef head = pull.head();
final PullRef base = pull.base();
final Req req;
final String repo = "repo";
if (head.json().isNull(repo)) {
new Answer(comment).post(
false,
QnMerge.PHRASES.getString("QnMerge.head-is-gone")
);
req = Req.EMPTY;
} else if (base.json().isNull(repo)) {
new Answer(comment).post(
false,
QnMerge.PHRASES.getString("QnMerge.base-is-gone")
);
req = Req.EMPTY;
} else {
req = new Req.Simple(
"merge",
new SolidMap<String, String>(
new MapEntry<String, String>(
"pull_id",
Integer.toString(pull.number())
),
new MapEntry<String, String>(
"pull_title",
new Issue.Smart(comment.issue()).title()
),
new MapEntry<String, String>(
"fork_branch",
head.ref()
),
new MapEntry<String, String>(
"head_branch",
base.ref()
),
new MapEntry<String, String>(
"head",
String.format(
"envkt@example.com",
base.repo().coordinates().toString()
)
),
new MapEntry<String, String>(
"fork",
String.format(
"envkt@example.com",
head.repo().coordinates().toString()
)
)
)
);
}
return req;
}
}
|
922ece6a867fac7a5757b19ef2d20b85c3cffab2 | 1,876 | java | Java | openbanking-api-soap-transform/src/main/gen/com/laegler/openbanking/soap/model/GETGetallorganisationsthattheclientisauthorisedtoretrieveInputMessage.java | thlaegler/openbanking | 924a29ac8c0638622fba7a5674c21c803d6dc5a9 | [
"MIT"
] | null | null | null | openbanking-api-soap-transform/src/main/gen/com/laegler/openbanking/soap/model/GETGetallorganisationsthattheclientisauthorisedtoretrieveInputMessage.java | thlaegler/openbanking | 924a29ac8c0638622fba7a5674c21c803d6dc5a9 | [
"MIT"
] | 6 | 2019-10-20T18:56:35.000Z | 2021-12-09T21:41:46.000Z | openbanking-api-soap-transform/src/main/gen/com/laegler/openbanking/soap/model/GETGetallorganisationsthattheclientisauthorisedtoretrieveInputMessage.java | thlaegler/openbanking | 924a29ac8c0638622fba7a5674c21c803d6dc5a9 | [
"MIT"
] | null | null | null | 28 | 118 | 0.685501 | 994,875 |
package com.laegler.openbanking.soap.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="OrganisationType" type="{http://laegler.com/openbanking/soap/model}OrganisationType"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"organisationType"
})
@XmlRootElement(name = "GET_Getallorganisationsthattheclientisauthorisedtoretrieve_InputMessage")
public class GETGetallorganisationsthattheclientisauthorisedtoretrieveInputMessage {
@XmlElement(name = "OrganisationType", required = true)
@XmlSchemaType(name = "string")
protected OrganisationType organisationType;
/**
* Gets the value of the organisationType property.
*
* @return
* possible object is
* {@link OrganisationType }
*
*/
public OrganisationType getOrganisationType() {
return organisationType;
}
/**
* Sets the value of the organisationType property.
*
* @param value
* allowed object is
* {@link OrganisationType }
*
*/
public void setOrganisationType(OrganisationType value) {
this.organisationType = value;
}
}
|
922ecf36eb7baaa90a4849228a6c344d4b0b38b0 | 2,579 | java | Java | egov/egov-edcr/src/main/java/org/egov/edcr/feature/Helipad.java | mithunvelocis/eGov-dcr-service | 51340a5177cce7e0e72608dc29e9b6b163489075 | [
"MIT"
] | null | null | null | egov/egov-edcr/src/main/java/org/egov/edcr/feature/Helipad.java | mithunvelocis/eGov-dcr-service | 51340a5177cce7e0e72608dc29e9b6b163489075 | [
"MIT"
] | null | null | null | egov/egov-edcr/src/main/java/org/egov/edcr/feature/Helipad.java | mithunvelocis/eGov-dcr-service | 51340a5177cce7e0e72608dc29e9b6b163489075 | [
"MIT"
] | null | null | null | 27.147368 | 100 | 0.722373 | 994,876 | package org.egov.edcr.feature;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.egov.common.entity.edcr.Block;
import org.egov.common.entity.edcr.Occupancy;
import org.egov.common.entity.edcr.OccupancyType;
import org.egov.common.entity.edcr.Plan;
import org.egov.common.entity.edcr.Result;
import org.egov.common.entity.edcr.ScrutinyDetail;
import org.springframework.stereotype.Service;
@Service
public class Helipad extends FeatureProcess {
private static final Logger LOG = Logger.getLogger(Helipad.class);
@Override
public Plan validate(Plan pl) {
return pl;
}
@Override
public Plan process(Plan pl) {
boolean status = false;
String provided = "";
scrutinyDetail = new ScrutinyDetail();
scrutinyDetail.setKey("Common_Helipad Provision");
scrutinyDetail.addColumnHeading(1, RULE_NO);
scrutinyDetail.addColumnHeading(2, DESCRIPTION);
scrutinyDetail.addColumnHeading(3, REQUIRED);
scrutinyDetail.addColumnHeading(4, PROVIDED);
scrutinyDetail.addColumnHeading(5, STATUS);
for (Block b : pl.getBlocks()) {
if (b.getBuilding().getBuildingHeight().doubleValue() >= 200) {
BigDecimal helipadDetails = getHelipad(pl);
if (helipadDetails.doubleValue() > 0) {
status = true;
provided = "Present";
} else {
provided = "Not Present";
}
Map<String, String> details = new HashMap<>();
details.put(RULE_NO, "");
details.put(DESCRIPTION, "Provision for Helipad");
details.put(REQUIRED, "Required");
details.put(PROVIDED, provided);
details.put(STATUS, status ? Result.Verify.getResultVal() : Result.Not_Accepted.getResultVal());
scrutinyDetail.getDetail().add(details);
} else if (b.getBuilding().getBuildingHeight().doubleValue() < 200) {
Map<String, String> details = new HashMap<>();
details.put(RULE_NO, "");
details.put(DESCRIPTION, "Provision for Helipad");
details.put(REQUIRED, " NA");
details.put(PROVIDED, " -");
details.put(STATUS, Result.Accepted.getResultVal());
scrutinyDetail.getDetail().add(details);
}
}
pl.getReportOutput().getScrutinyDetails().add(scrutinyDetail);
return pl;
}
private BigDecimal getHelipad(Plan pl) {
BigDecimal helipad = BigDecimal.ZERO;
// helipad=pl.getUtility().getWaterTankCapacity().doubleValue();
return helipad;
}
@Override
public Map<String, Date> getAmendments() {
return new LinkedHashMap<>();
}
}
|
922ecff4bf3ac11185ba8d5782775ae1ba8e9bbb | 5,204 | java | Java | fop-core/src/main/java/org/apache/fop/apps/EnvironmentalProfileFactory.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 40 | 2019-10-15T06:00:14.000Z | 2022-03-30T05:17:34.000Z | fop-core/src/main/java/org/apache/fop/apps/EnvironmentalProfileFactory.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 6 | 2019-10-07T16:33:08.000Z | 2021-12-11T09:00:42.000Z | fop-core/src/main/java/org/apache/fop/apps/EnvironmentalProfileFactory.java | Vazid546/xmlgraphics-fop | 07d912eba54173aaee3053054b9fe56888437f29 | [
"Apache-2.0"
] | 44 | 2019-11-13T04:52:48.000Z | 2022-03-08T10:33:46.000Z | 40.030769 | 107 | 0.707533 | 994,877 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.apps;
import java.net.URI;
import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.FallbackResolver;
import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.RestrictedFallbackResolver;
import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.UnrestrictedFallbackResolver;
import org.apache.xmlgraphics.io.ResourceResolver;
import org.apache.fop.apps.io.InternalResourceResolver;
import org.apache.fop.apps.io.ResourceResolverFactory;
import org.apache.fop.fonts.FontCacheManager;
import org.apache.fop.fonts.FontCacheManagerFactory;
import org.apache.fop.fonts.FontDetector;
import org.apache.fop.fonts.FontDetectorFactory;
import org.apache.fop.fonts.FontManager;
/**
* Creates an {@link EnvironmentProfile} that sets the environment in which a FOP instance is run.
*/
public final class EnvironmentalProfileFactory {
private EnvironmentalProfileFactory() {
};
/**
* Creates the default environment that FOP is invoked in. This default profile has no
* operational restrictions for FOP.
*
* @param defaultBaseUri the default base URI for resolving resource URIs
* @param resourceResolver the resource resolver
* @return the environment profile
*/
public static EnvironmentProfile createDefault(URI defaultBaseUri,
ResourceResolver resourceResolver) {
return new Profile(defaultBaseUri, resourceResolver,
createFontManager(defaultBaseUri, resourceResolver,
FontDetectorFactory.createDefault(),
FontCacheManagerFactory.createDefault()),
new UnrestrictedFallbackResolver());
}
/**
* Creates an IO-restricted environment for FOP by disabling some of the environment-specific
* functionality within FOP.
*
* @param defaultBaseUri the default base URI for resolving resource URIs
* @param resourceResolver the resource resolver
* @return the environment profile
*/
public static EnvironmentProfile createRestrictedIO(URI defaultBaseUri,
ResourceResolver resourceResolver) {
return new Profile(defaultBaseUri, resourceResolver,
createFontManager(defaultBaseUri, resourceResolver,
FontDetectorFactory.createDisabled(),
FontCacheManagerFactory.createDisabled()),
new RestrictedFallbackResolver());
}
private static final class Profile implements EnvironmentProfile {
private final ResourceResolver resourceResolver;
private final FontManager fontManager;
private final URI defaultBaseURI;
private final FallbackResolver fallbackResolver;
private Profile(URI defaultBaseURI, ResourceResolver resourceResolver,
FontManager fontManager, FallbackResolver fallbackResolver) {
if (defaultBaseURI == null) {
throw new IllegalArgumentException("Default base URI must not be null");
}
if (resourceResolver == null) {
throw new IllegalArgumentException("ResourceResolver must not be null");
}
if (fontManager == null) {
throw new IllegalArgumentException("The FontManager must not be null");
}
this.defaultBaseURI = defaultBaseURI;
this.resourceResolver = resourceResolver;
this.fontManager = fontManager;
this.fallbackResolver = fallbackResolver;
}
public ResourceResolver getResourceResolver() {
return resourceResolver;
}
public FontManager getFontManager() {
return fontManager;
}
public URI getDefaultBaseURI() {
return defaultBaseURI;
}
public FallbackResolver getFallbackResolver() {
return fallbackResolver;
}
}
private static FontManager createFontManager(URI defaultBaseUri, ResourceResolver resourceResolver,
FontDetector fontDetector, FontCacheManager fontCacheManager) {
InternalResourceResolver internalResolver = ResourceResolverFactory.createInternalResourceResolver(
defaultBaseUri, resourceResolver);
return new FontManager(internalResolver, fontDetector, fontCacheManager);
}
}
|
922ed051e22be03b90ad98b731e56c4f00b2d497 | 6,049 | java | Java | bmc-loadbalancer/src/main/java/com/oracle/bmc/loadbalancer/requests/ChangeLoadBalancerCompartmentRequest.java | fankh/oci-java-sdk | 93a4a2a4560b3613c31ef9cf82ddf61b3973328c | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2021-04-09T18:17:14.000Z | 2021-04-09T18:17:14.000Z | bmc-loadbalancer/src/main/java/com/oracle/bmc/loadbalancer/requests/ChangeLoadBalancerCompartmentRequest.java | Varulv1997/oci-java-sdk | cb27aba36ea0e4c68b88ba13c0ca4a85c17620b4 | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | bmc-loadbalancer/src/main/java/com/oracle/bmc/loadbalancer/requests/ChangeLoadBalancerCompartmentRequest.java | Varulv1997/oci-java-sdk | cb27aba36ea0e4c68b88ba13c0ca4a85c17620b4 | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 42.006944 | 273 | 0.681104 | 994,878 | /**
* Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
* This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
*/
package com.oracle.bmc.loadbalancer.requests;
import com.oracle.bmc.loadbalancer.model.*;
/**
* <b>Example: </b>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/java-sdk-examples/latest/loadbalancer/ChangeLoadBalancerCompartmentExample.java.html" target="_blank" rel="noopener noreferrer">here</a> to see how to use ChangeLoadBalancerCompartmentRequest.
*/
@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20170115")
@lombok.Builder(
builderClassName = "Builder",
buildMethodName = "buildWithoutInvocationCallback",
toBuilder = true
)
@lombok.ToString(callSuper = true)
@lombok.EqualsAndHashCode(callSuper = true)
@lombok.Getter
public class ChangeLoadBalancerCompartmentRequest
extends com.oracle.bmc.requests.BmcRequest<ChangeLoadBalancerCompartmentDetails> {
/**
* The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the load balancer to move.
*/
private String loadBalancerId;
/**
* The configuration details for moving a load balancer to a different compartment.
*/
private ChangeLoadBalancerCompartmentDetails changeLoadBalancerCompartmentDetails;
/**
* The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
* particular request, please provide the request ID.
*
*/
private String opcRequestId;
/**
* A token that uniquely identifies a request so it can be retried in case of a timeout or
* server error without risk of executing that same action again. Retry tokens expire after 24
* hours, but can be invalidated before then due to conflicting operations (e.g., if a resource
* has been deleted and purged from the system, then a retry of the original creation request
* may be rejected).
*
*/
private String opcRetryToken;
/**
* For optimistic concurrency control. Set the if-match parameter to the value of the ETag from a
* previous GET or POST response for that resource. The resource is moved only if the ETag you
* provide matches the resource's current ETag value.
* <p>
* Example: `example-etag`
*
*/
private String ifMatch;
/**
* Alternative accessor for the body parameter.
* @return body parameter
*/
@Override
@com.oracle.bmc.InternalSdk
public ChangeLoadBalancerCompartmentDetails getBody$() {
return changeLoadBalancerCompartmentDetails;
}
public static class Builder
implements com.oracle.bmc.requests.BmcRequest.Builder<
ChangeLoadBalancerCompartmentRequest, ChangeLoadBalancerCompartmentDetails> {
private com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
invocationCallback = null;
private com.oracle.bmc.retrier.RetryConfiguration retryConfiguration = null;
/**
* Set the invocation callback for the request to be built.
* @param invocationCallback the invocation callback to be set for the request
* @return this builder instance
*/
public Builder invocationCallback(
com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
invocationCallback) {
this.invocationCallback = invocationCallback;
return this;
}
/**
* Set the retry configuration for the request to be built.
* @param retryConfiguration the retry configuration to be used for the request
* @return this builder instance
*/
public Builder retryConfiguration(
com.oracle.bmc.retrier.RetryConfiguration retryConfiguration) {
this.retryConfiguration = retryConfiguration;
return this;
}
/**
* Copy method to populate the builder with values from the given instance.
* @return this builder instance
*/
public Builder copy(ChangeLoadBalancerCompartmentRequest o) {
loadBalancerId(o.getLoadBalancerId());
changeLoadBalancerCompartmentDetails(o.getChangeLoadBalancerCompartmentDetails());
opcRequestId(o.getOpcRequestId());
opcRetryToken(o.getOpcRetryToken());
ifMatch(o.getIfMatch());
invocationCallback(o.getInvocationCallback());
retryConfiguration(o.getRetryConfiguration());
return this;
}
/**
* Build the instance of ChangeLoadBalancerCompartmentRequest as configured by this builder
*
* Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,
* while the method {@link Builder#buildWithoutInvocationCallback} does not.
*
* This is the preferred method to build an instance.
*
* @return instance of ChangeLoadBalancerCompartmentRequest
*/
public ChangeLoadBalancerCompartmentRequest build() {
ChangeLoadBalancerCompartmentRequest request = buildWithoutInvocationCallback();
request.setInvocationCallback(invocationCallback);
request.setRetryConfiguration(retryConfiguration);
return request;
}
/**
* Alternative setter for the body parameter.
* @param body the body parameter
* @return this builder instance
*/
@com.oracle.bmc.InternalSdk
public Builder body$(ChangeLoadBalancerCompartmentDetails body) {
changeLoadBalancerCompartmentDetails(body);
return this;
}
}
}
|
922ed067e8ab98cc11d8c55be58df61e3c41d624 | 1,410 | java | Java | transpiler/src/test/java/source/nativestructures/Exceptions.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 1,374 | 2015-11-18T19:09:59.000Z | 2022-03-27T16:33:01.000Z | transpiler/src/test/java/source/nativestructures/Exceptions.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 661 | 2015-11-22T08:00:56.000Z | 2022-03-07T07:11:15.000Z | transpiler/src/test/java/source/nativestructures/Exceptions.java | chfeiler/jsweet | 2421eea53d6f83b8e0cd1574de50492a41ccd385 | [
"Apache-2.0"
] | 193 | 2015-12-04T16:00:18.000Z | 2022-03-22T06:06:07.000Z | 18.076923 | 62 | 0.668794 | 994,879 | package source.nativestructures;
import static jsweet.util.Lang.$export;
import def.js.Array;
public class Exceptions {
static Array<String> trace = new Array<>();
public static void main(String[] args) {
try {
new Exceptions().m();
} catch (Exception e) {
trace.push(e.getMessage());
}
try {
new Exceptions().m();
} catch (NoSuchMethodError e1) {
trace.push(e1.getMessage());
} catch (NumberFormatException e2) {
trace.push(e2.getMessage());
} catch (TestException3 e3) {
trace.push(e3.getMessage());
} finally {
trace.push("finally");
}
try {
new Exceptions().m2();
} catch (Exception e) {
trace.push(e.getMessage());
}
try {
new Exceptions().m3();
} catch (TestException e) {
trace.push(e.getMessage());
}
$export("trace", trace.join(","));
}
public void m() throws NumberFormatException {
throw new NumberFormatException("test");
}
public void m2() {
throw new RuntimeException(new IllegalAccessError("test2"));
}
public void m3() throws TestException {
throw new TestException("test3");
}
}
class TestException extends Exception {
public TestException(String msg) {
super(msg);
}
}
class TestException2 extends java.lang.Exception {
public TestException2(String msg) {
super(msg);
}
}
class TestException3 extends java.lang.RuntimeException {
public TestException3(String msg) {
super(msg);
}
}
|
922ed06bbea314741f0203a6c9c2a6650f57e6cd | 501 | java | Java | leetcode/src/easy/RemoveDuplicates.java | Shubhamsdr3/problem-solving | d1fbd5de3276dc6dafe899b7be62c9b20700632b | [
"Apache-2.0"
] | null | null | null | leetcode/src/easy/RemoveDuplicates.java | Shubhamsdr3/problem-solving | d1fbd5de3276dc6dafe899b7be62c9b20700632b | [
"Apache-2.0"
] | null | null | null | leetcode/src/easy/RemoveDuplicates.java | Shubhamsdr3/problem-solving | d1fbd5de3276dc6dafe899b7be62c9b20700632b | [
"Apache-2.0"
] | null | null | null | 20.875 | 53 | 0.487026 | 994,880 | package easy;
import java.util.Arrays;
public class RemoveDuplicates {
private static int removeDuplicates(int[] nums) {
int i = nums.length > 0 ? 1: 0;
for (int num: nums) {
if (num > nums[i-1]) {
nums[i++] = num;
}
}
return i;
}
public static void main(String[] args) {
int[] input = new int[]{
0,0,1,1,1,2,2,3,3,4
};
System.out.println(removeDuplicates(input));
}
}
|
922ed20c0ab6e473f4759a64b1c334f1b525230d | 1,443 | java | Java | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/model/consoleportal/ClusterListUnhealthyClusterModel.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 1,652 | 2016-04-18T10:34:30.000Z | 2022-03-30T06:15:35.000Z | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/model/consoleportal/ClusterListUnhealthyClusterModel.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 342 | 2016-07-27T10:38:01.000Z | 2022-03-31T11:11:46.000Z | redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/model/consoleportal/ClusterListUnhealthyClusterModel.java | coral-cloud/x-pipe | d4ad1d9039a83f55439b69ae7d6954171002fa39 | [
"Apache-2.0"
] | 492 | 2016-04-25T05:14:10.000Z | 2022-03-16T01:40:38.000Z | 22.904762 | 91 | 0.699238 | 994,881 | package com.ctrip.xpipe.redis.console.model.consoleportal;
import java.util.List;
/**
* @author chen.zhu
* <p>
* Jan 31, 2018
*/
public class ClusterListUnhealthyClusterModel extends AbstractClusterModel {
private Long activedcId;
private List<String> messages;
private int unhealthyShardsCnt;
private int unhealthyRedisCnt;
public ClusterListUnhealthyClusterModel(String clusterName) {
super(clusterName);
}
public ClusterListUnhealthyClusterModel() {
}
public Long getActivedcId() {
return activedcId;
}
public ClusterListUnhealthyClusterModel setActivedcId(Long activedcId) {
this.activedcId = activedcId;
return this;
}
public List<String> getMessages() {
return messages;
}
public ClusterListUnhealthyClusterModel setMessages(List<String> messages) {
this.messages = messages;
return this;
}
public int getUnhealthyShardsCnt() {
return unhealthyShardsCnt;
}
public ClusterListUnhealthyClusterModel setUnhealthyShardsCnt(int unhealthyShardsCnt) {
this.unhealthyShardsCnt = unhealthyShardsCnt;
return this;
}
public int getUnhealthyRedisCnt() {
return unhealthyRedisCnt;
}
public ClusterListUnhealthyClusterModel setUnhealthyRedisCnt(int unhealthyRedisCnt) {
this.unhealthyRedisCnt = unhealthyRedisCnt;
return this;
}
}
|
922ed34231aa6f0196e04fe463891a29909fe289 | 1,427 | java | Java | util/src/main/java/com/ning/billing/util/queue/PersistentQueueEntryLifecycle.java | kevinpostlewaite/killbill | 19e9ee463fa88cc33c890b1068f6f1f89e5b879d | [
"Apache-2.0"
] | null | null | null | util/src/main/java/com/ning/billing/util/queue/PersistentQueueEntryLifecycle.java | kevinpostlewaite/killbill | 19e9ee463fa88cc33c890b1068f6f1f89e5b879d | [
"Apache-2.0"
] | null | null | null | util/src/main/java/com/ning/billing/util/queue/PersistentQueueEntryLifecycle.java | kevinpostlewaite/killbill | 19e9ee463fa88cc33c890b1068f6f1f89e5b879d | [
"Apache-2.0"
] | null | null | null | 28.54 | 103 | 0.734408 | 994,882 | /*
* Copyright 2010-2011 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.util.queue;
import java.util.UUID;
import org.joda.time.DateTime;
public interface PersistentQueueEntryLifecycle {
public enum PersistentQueueEntryLifecycleState {
AVAILABLE,
IN_PROCESSING,
PROCESSED,
REMOVED
}
public Long getTenantRecordId();
public Long getAccountRecordId();
public String getOwner();
public String getCreatedOwner();
public DateTime getNextAvailableDate();
public PersistentQueueEntryLifecycleState getProcessingState();
public boolean isAvailableForProcessing(DateTime now);
// User token associated with this bus event or notification (i.e. user token from the context that
// was used to generate this PersistentQueueEntryLifecycle)
public UUID getUserToken();
}
|
922ed37f94b465a8d5b0d4fd6af5fae55b5c4d83 | 6,102 | java | Java | src/tankgame/Collision.java | Nimiksha/TankGame | 4d2c7f4cf8d228cb8779f797ddcc97add280f0f3 | [
"MIT"
] | null | null | null | src/tankgame/Collision.java | Nimiksha/TankGame | 4d2c7f4cf8d228cb8779f797ddcc97add280f0f3 | [
"MIT"
] | null | null | null | src/tankgame/Collision.java | Nimiksha/TankGame | 4d2c7f4cf8d228cb8779f797ddcc97add280f0f3 | [
"MIT"
] | null | null | null | 44.540146 | 122 | 0.560144 | 994,883 | package tankgame;
import java.awt.Rectangle;
//defines what happens when the objects (bullets, tanks, walls, power ups) in the game collide/intersect with each other
public class Collision {
private Music music = new Music(); //create an object of Music class to insert music effects on collisions
/*
Collision() checks for collisions and their types in the Tank Game
We assume the things colliding (intersection of rectangles) are a tank and some other object -
either a tank, a wall or a Power up feature */
public void Collision(GameObject tank, GameObject object) {
Rectangle rec1 = tank.getRectangle(); //get the rectangle of the tank
Rectangle rec2 = object.getRectangle(); //get the rectangle of the other object
int speedX = ((Tank) tank).getSpeedX(); //speed of object in X direction (casting the Game objects to type tank)
int speedY = ((Tank) tank).getSpeedY(); //speed of object in Y direction (casting the Game objects to type tank)
//Check Reverse collision
Rectangle rec1Reverse = new Rectangle(tank.getX_coordinate()-speedX, tank.getY_coordinate()-speedY ,
tank.getImageWidth(), tank.getImageHeight());
//Check Forward collision
Rectangle rec1Forward = new Rectangle(tank.getX_coordinate()+ speedX, tank.getY_coordinate()+speedY ,
tank.getImageWidth(), tank.getImageHeight());
//if object is a tank
if(object instanceof Tank) {
//check forward and reverse collisions
if(rec1Forward.intersects(rec2)) {
((Tank) tank).setForwardCollision(true);
}
else if (rec1Reverse.intersects(rec2)) {
((Tank) tank).setReverseCollision(true);
}
//Check for collision of ammunition's, from the tank -- i.e see if a bullet hits the other tank
//iterate through the ammo array list for the tanl
for (int i = 0; i < ((Tank) tank).getAmmoList().size(); i++) {
GameObject ammoObject = ((Tank) tank).getAmmoList().get(i); //get the bullet object(s)
Rectangle ammoRec = ammoObject.getRectangle(); //get the rectangle of the ammunition
//if the bullet hits the tank, give a explosion sound and remove the bullet object
if(rec2.intersects(ammoRec)) {
music.explosion();
ammoObject.setRemoval(true);
//for the bullet from the tank increase the tank(shooter's) score by 10
// and decrease the health of the tank hit by 5
if(ammoObject instanceof Bullet) {
((Tank) tank).incScore(10);
((Tank) object).decHealth(5);
}
}
}
}
//if object is a breakable wall
else if (object instanceof BreakableWall) {
//check forward and reverse collisions
if(rec1Forward.intersects(rec2)) {
((Tank) tank).setForwardCollision(true);
}
else if (rec1Reverse.intersects(rec2)) {
((Tank) tank).setReverseCollision(true);
}
//iterating through the ammo list (which are the bullets fired) of the tank
for(int i = 0; i < ((Tank) tank).getAmmoList().size(); i++) {
GameObject ammoObject = ((Tank) tank).getAmmoList().get(i);
Rectangle ammoRec = ammoObject.getRectangle();
//if an ammunition hits the wall, explosion sound, along with removal of both the wall and the ammunition.
// Also the tank player gets 5 points
if(rec2.intersects(ammoRec)) {
music.explosion();
ammoObject.setRemoval(true);
object.setRemoval(true);
((Tank) tank).incScore(5);
}
}
}
//if object is a unbreakable wall
else if (object instanceof UnbreakableWall) {
//check forward and reverse collisions
if(rec1Forward.intersects(rec2)) {
((Tank) tank).setForwardCollision(true);
}
else if (rec1Reverse.intersects(rec2)) {
((Tank) tank).setReverseCollision(true);
}
for(int i = 0; i<((Tank) tank).getAmmoList().size(); i++) {
GameObject ammoObject = ((Tank) tank).getAmmoList().get(i);
Rectangle ammoRec = ammoObject.getRectangle();
//if an ammunition hits the wall, no points given and the wall is not removed. only the bullet is removed
if(rec2.intersects(ammoRec)) {
music.explosion();
ammoObject.setRemoval(true);
}
}
}
//if object is a Life power up
else if (object instanceof Power && ((Power) object).getPowerType() == PowerType.PowerLife) {
//if the tank rectangle intersects the life powerUp rectangle, the tank gains 1 life
if(rec1.intersects(rec2)) {
((Tank) tank).setLifePower(true);
object.setRemoval(true); //remove the power up object from the screen
music.powerUpSound();
((Tank) tank).lifeBoost();
}
}
//if object is a Shield power up
else if (object instanceof Power && ((Power) object).getPowerType() == PowerType.PowerShield) {
//if the tank rectangle intersects the shield powerUp rectangle, the tank health increases by 20 points
if(rec1.intersects(rec2)) {
((Tank) tank).setShieldPower(true);
object.setRemoval(true); //remove the power up object from the screen
music.powerUpSound();
((Tank) tank).incHealth();
}
}
}
} |
922ed458542a133ba2a1525825725aff7c07fdf6 | 718 | java | Java | bootique-job-zookeeper/src/main/java/io/bootique/job/zookeeper/ZkJobModule.java | MegaPapa/bootique-job | bcb181ecac9b0ba8f70008ccc0e533f54ccaeb37 | [
"Apache-2.0"
] | null | null | null | bootique-job-zookeeper/src/main/java/io/bootique/job/zookeeper/ZkJobModule.java | MegaPapa/bootique-job | bcb181ecac9b0ba8f70008ccc0e533f54ccaeb37 | [
"Apache-2.0"
] | null | null | null | bootique-job-zookeeper/src/main/java/io/bootique/job/zookeeper/ZkJobModule.java | MegaPapa/bootique-job | bcb181ecac9b0ba8f70008ccc0e533f54ccaeb37 | [
"Apache-2.0"
] | null | null | null | 23.16129 | 64 | 0.735376 | 994,884 | package io.bootique.job.zookeeper;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import io.bootique.ConfigModule;
import io.bootique.job.lock.LockHandler;
import io.bootique.job.zookeeper.lock.ZkClusterLockHandler;
@SuppressWarnings("unused")
public class ZkJobModule extends ConfigModule {
public ZkJobModule() {
}
public ZkJobModule(String configPrefix) {
super(configPrefix);
}
@Override
protected String defaultConfigPrefix() {
return "job-consul";
}
@Provides
@Singleton
LockHandler provideClusteredLockHandler(Injector injector) {
return new ZkClusterLockHandler(injector);
}
}
|
922ed47c3acd66f9453c70a814d1292dc13317ea | 1,417 | java | Java | archunit/src/main/java/com/tngtech/archunit/lang/conditions/JavaAccessCondition.java | stuartwdouglas/ArchUnit | 502ecd53c6ab53c9798740586ae8fbfb5dc6f3f9 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2,143 | 2017-04-21T09:45:03.000Z | 2022-03-31T18:14:04.000Z | archunit/src/main/java/com/tngtech/archunit/lang/conditions/JavaAccessCondition.java | stuartwdouglas/ArchUnit | 502ecd53c6ab53c9798740586ae8fbfb5dc6f3f9 | [
"Apache-2.0",
"BSD-3-Clause"
] | 678 | 2017-04-26T19:26:48.000Z | 2022-03-31T16:34:39.000Z | archunit/src/main/java/com/tngtech/archunit/lang/conditions/JavaAccessCondition.java | stuartwdouglas/ArchUnit | 502ecd53c6ab53c9798740586ae8fbfb5dc6f3f9 | [
"Apache-2.0",
"BSD-3-Clause"
] | 274 | 2017-04-24T21:58:44.000Z | 2022-03-01T12:38:30.000Z | 38.297297 | 97 | 0.754411 | 994,885 | /*
* Copyright 2014-2022 TNG Technology Consulting GmbH
*
* 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.tngtech.archunit.lang.conditions;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaAccess;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;
class JavaAccessCondition<T extends JavaAccess<?>> extends ArchCondition<T> {
private final DescribedPredicate<? super T> predicate;
JavaAccessCondition(DescribedPredicate<? super T> predicate) {
super("access target where " + predicate.getDescription());
this.predicate = predicate;
}
@Override
public void check(T item, ConditionEvents events) {
events.add(new SimpleConditionEvent(item, predicate.apply(item), item.getDescription()));
}
}
|
922ed558d96401e1c9c5cd230e14dc7ba3c9a3b3 | 286 | java | Java | app/src/main/java/com/schneewittchen/rosandroid/model/entities/widgets/IPublisherEntity.java | sunmaxwll/ROS-Mobile-Android | 6b2ab8448af4edef41225c126cfbe384cff33e35 | [
"MIT",
"Unlicense"
] | 283 | 2020-07-12T11:13:16.000Z | 2022-03-31T06:50:31.000Z | app/src/main/java/com/schneewittchen/rosandroid/model/entities/widgets/IPublisherEntity.java | Bolt108/ROS-Mobile-Android | 91f9df8d1326a06a14114c8464637b96c45a2036 | [
"MIT",
"Unlicense"
] | 70 | 2020-05-26T07:55:29.000Z | 2022-03-30T19:15:28.000Z | app/src/main/java/com/schneewittchen/rosandroid/model/entities/widgets/IPublisherEntity.java | Bolt108/ROS-Mobile-Android | 91f9df8d1326a06a14114c8464637b96c45a2036 | [
"MIT",
"Unlicense"
] | 88 | 2020-07-12T10:42:16.000Z | 2022-03-29T15:50:14.000Z | 22 | 61 | 0.737762 | 994,886 | package com.schneewittchen.rosandroid.model.entities.widgets;
/**
* Entity with publisher information to be able
* to create a appropriate publisher node in the ROS-network.
*
* @author Nico Studt
* @version 1.0.0
* @created on 10.03.21
*/
public interface IPublisherEntity {
}
|
922ed56def9c0c3dbe6f8553d049115fc47ff73a | 777 | java | Java | hommin-security-core/src/main/java/com/hommin/security/core/validate/code/ValidateCode.java | HomminLee/hommin-security | f01fdd9f219624ffd7872cd92323bd8ef734a75e | [
"Apache-2.0"
] | 1 | 2019-12-28T02:28:32.000Z | 2019-12-28T02:28:32.000Z | hommin-security-core/src/main/java/com/hommin/security/core/validate/code/ValidateCode.java | HomminLee/hommin-security | f01fdd9f219624ffd7872cd92323bd8ef734a75e | [
"Apache-2.0"
] | null | null | null | hommin-security-core/src/main/java/com/hommin/security/core/validate/code/ValidateCode.java | HomminLee/hommin-security | f01fdd9f219624ffd7872cd92323bd8ef734a75e | [
"Apache-2.0"
] | null | null | null | 21.583333 | 71 | 0.700129 | 994,887 | package com.hommin.security.core.validate.code;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 验证码
*
* @author Hommin
* 2019年06月19日 4:11 PM
*/
@Data
public class ValidateCode implements Serializable{
private static final long serialVersionUID = -6482231418968354764L;
private String code;
private LocalDateTime expireTime;
public ValidateCode(String code, LocalDateTime expireTime) {
this.code = code;
this.expireTime = expireTime;
}
public ValidateCode(String code, int expireTime) {
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireTime);
}
public boolean isExpried(){
return LocalDateTime.now().isAfter(expireTime);
}
}
|
922ed64fee300b58ee1895b7711d654e70951d41 | 4,072 | java | Java | apps/cfm/src/main/java/org/onosproject/cfm/cli/CfmMdAddCommand.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 3 | 2017-05-24T01:14:09.000Z | 2018-07-23T10:07:29.000Z | apps/cfm/src/main/java/org/onosproject/cfm/cli/CfmMdAddCommand.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 13 | 2020-01-31T18:04:44.000Z | 2022-03-02T02:23:18.000Z | apps/cfm/src/main/java/org/onosproject/cfm/cli/CfmMdAddCommand.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 8 | 2016-11-08T21:32:18.000Z | 2021-07-29T13:58:04.000Z | 40.316832 | 84 | 0.666994 | 994,888 | /*
* Copyright 2017-present Open Networking Foundation
*
* 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 org.onosproject.cfm.cli;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Argument;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.incubator.net.l2monitoring.cfm.DefaultMaintenanceDomain;
import org.onosproject.incubator.net.l2monitoring.cfm.MaintenanceDomain;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MdId;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MdIdCharStr;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MdIdDomainName;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MdIdMacUint;
import org.onosproject.incubator.net.l2monitoring.cfm.identifier.MdIdNone;
import org.onosproject.incubator.net.l2monitoring.cfm.service.CfmConfigException;
import org.onosproject.incubator.net.l2monitoring.cfm.service.CfmMdService;
import java.util.Optional;
/**
* Adds a Maintenance Domain to the existing list.
*/
@Command(scope = "onos", name = "cfm-md-add",
description = "Add a CFM Maintenance Domain.")
public class CfmMdAddCommand extends AbstractShellCommand {
@Argument(index = 0, name = "name-type",
description = "Maintenance Domain name type",
required = true, multiValued = false)
String nameType = null;
@Argument(index = 1, name = "name",
description = "Maintenance Domain name. Restrictions apply depending " +
"on name-type. Leave empty if name type is none",
required = true, multiValued = false)
String name = null;
@Argument(index = 2, name = "level",
description = "Maintenance Domain level LEVEL0-LEVEL7",
required = true, multiValued = false)
String level = null;
@Argument(index = 3, name = "numeric-id",
description = "An optional numeric id for Maintenance Domain [1-65535]",
required = false, multiValued = false)
short numericId = 0;
@Override
protected void execute() {
CfmMdService service = get(CfmMdService.class);
MdId mdId = null;
MdId.MdNameType nameTypeEnum = MdId.MdNameType.valueOf(nameType);
switch (nameTypeEnum) {
case DOMAINNAME:
mdId = MdIdDomainName.asMdId(name);
break;
case MACANDUINT:
mdId = MdIdMacUint.asMdId(name);
break;
case NONE:
mdId = MdIdNone.asMdId();
break;
case CHARACTERSTRING:
default:
mdId = MdIdCharStr.asMdId(name);
}
MaintenanceDomain.MdLevel levelEnum =
MaintenanceDomain.MdLevel.valueOf(level);
Optional<Short> numericIdOpt = Optional.empty();
if (numericId > 0) {
numericIdOpt = Optional.of(numericId);
}
MaintenanceDomain.MdBuilder builder = null;
try {
builder = DefaultMaintenanceDomain.builder(mdId).mdLevel(levelEnum);
if (numericIdOpt.isPresent()) {
builder = builder.mdNumericId(numericIdOpt.get());
}
boolean created = service.createMaintenanceDomain(builder.build());
print("Maintenance Domain with id %s is successfully %s.",
mdId, created ? "updated" : "created");
} catch (CfmConfigException e) {
throw new IllegalArgumentException(e);
}
}
}
|
922ed6d6f598c9a3ca607436ae9cdd07ea4b8e21 | 3,057 | java | Java | rhymecity/src/main/java/com/metech/firefly/api/obj/JourneyInfo.java | imalpasha/meV2 | 8ff1f9cb9449ddce2453d2d04cfc01f97544b2ef | [
"MIT"
] | null | null | null | rhymecity/src/main/java/com/metech/firefly/api/obj/JourneyInfo.java | imalpasha/meV2 | 8ff1f9cb9449ddce2453d2d04cfc01f97544b2ef | [
"MIT"
] | null | null | null | rhymecity/src/main/java/com/metech/firefly/api/obj/JourneyInfo.java | imalpasha/meV2 | 8ff1f9cb9449ddce2453d2d04cfc01f97544b2ef | [
"MIT"
] | null | null | null | 24.853659 | 74 | 0.68335 | 994,889 | package com.metech.firefly.api.obj;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Dell on 11/24/2015.
*/
public class JourneyInfo {
public String departure_date;
public String type;
public String departure_station_code;
public String departure_station_name;
public String arrival_station_code;
public String arrival_station_name;
public String flight_status;
public String mh_flight_number;
public String departure_station;
public String getMh_flight_number() {
return mh_flight_number;
}
public void setMh_flight_number(String mh_flight_number) {
this.mh_flight_number = mh_flight_number;
}
public String getFlight_status() {
return flight_status;
}
public void setFlight_status(String flight_status) {
this.flight_status = flight_status;
}
//changeFlight
public String getArrival_station() {
return arrival_station;
}
public void setArrival_station(String arrival_station) {
this.arrival_station = arrival_station;
}
public String getDeparture_station() {
return departure_station;
}
public void setDeparture_station(String departure_station) {
this.departure_station = departure_station;
}
public String arrival_station;
private List<FlightInfo> flights = new ArrayList<FlightInfo>();
public String getDeparture_date() {
return departure_date;
}
public void setDeparture_date(String departure_date) {
this.departure_date = departure_date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDeparture_station_code() {
return departure_station_code;
}
public void setDeparture_station_code(String departure_station_code) {
this.departure_station_code = departure_station_code;
}
public String getDeparture_station_name() {
return departure_station_name;
}
public void setDeparture_station_name(String departure_station_name) {
this.departure_station_name = departure_station_name;
}
public String getArrival_station_code() {
return arrival_station_code;
}
public void setArrival_station_code(String arrival_station_code) {
this.arrival_station_code = arrival_station_code;
}
public String getArrival_station_name() {
return arrival_station_name;
}
public void setArrival_station_name(String arrival_station_name) {
this.arrival_station_name = arrival_station_name;
}
public List<FlightInfo> getFlights() {
return flights;
}
public void setFlights(List<FlightInfo> flights) {
this.flights = flights;
}
@Override
public String toString() {
return "JourneyInfo{" +
"departure_station='" + departure_station + '\'' +
", arrival_station='" + arrival_station + '\'' +
'}';
}
}
|
922ed82157fdd971c2d121506b21009263ccff8f | 2,663 | java | Java | repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/RSecurityPolicy.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/RSecurityPolicy.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/data/common/RSecurityPolicy.java | bshp/midpoint | 6dfa3fecb76d1516a22eb4b7f3da04031ade04d3 | [
"Apache-2.0"
] | null | null | null | 35.506667 | 119 | 0.705595 | 994,890 | /**
* Copyright (c) 2010-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.repo.sql.data.common;
import com.evolveum.midpoint.repo.sql.data.RepositoryContext;
import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString;
import com.evolveum.midpoint.repo.sql.query.definition.JaxbName;
import com.evolveum.midpoint.repo.sql.util.DtoTranslationException;
import com.evolveum.midpoint.repo.sql.util.IdGeneratorResult;
import com.evolveum.midpoint.repo.sql.util.MidPointJoinedPersister;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityPolicyType;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.Persister;
import javax.persistence.*;
@Entity
@Table(uniqueConstraints = @UniqueConstraint(name = "uc_security_policy_name", columnNames = {"name_norm"}),
indexes = {
@Index(name = "iSecurityPolicyNameOrig", columnList = "name_orig"),
}
)
@ForeignKey(name = "fk_security_policy")
@Persister(impl = MidPointJoinedPersister.class)
public class RSecurityPolicy extends RObject<SecurityPolicyType> {
private RPolyString nameCopy;
@JaxbName(localPart = "name")
@AttributeOverrides({
@AttributeOverride(name = "orig", column = @Column(name = "name_orig")),
@AttributeOverride(name = "norm", column = @Column(name = "name_norm"))
})
@Embedded
public RPolyString getNameCopy() {
return nameCopy;
}
public void setNameCopy(RPolyString nameCopy) {
this.nameCopy = nameCopy;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
RSecurityPolicy that = (RSecurityPolicy) o;
if (nameCopy != null ? !nameCopy.equals(that.nameCopy) : that.nameCopy != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (nameCopy != null ? nameCopy.hashCode() : 0);
return result;
}
// dynamically called
public static void copyFromJAXB(SecurityPolicyType jaxb, RSecurityPolicy repo, RepositoryContext repositoryContext,
IdGeneratorResult generatorResult) throws DtoTranslationException {
copyAssignmentHolderInformationFromJAXB(jaxb, repo, repositoryContext, generatorResult);
repo.setNameCopy(RPolyString.copyFromJAXB(jaxb.getName()));
}
}
|
922ed87668151dfa8a692f2c7e7c3998c81da63b | 5,100 | java | Java | src/test/java/io/hyperfoil/tools/qdup/config/rule/NonObservingCommandsTest.java | jesperpedersen/qDup | 549d660a321fb6c7d6e3f15e9460c2d103b48ef3 | [
"Apache-2.0"
] | 4 | 2019-10-07T12:21:54.000Z | 2022-03-01T06:25:45.000Z | src/test/java/io/hyperfoil/tools/qdup/config/rule/NonObservingCommandsTest.java | jesperpedersen/qDup | 549d660a321fb6c7d6e3f15e9460c2d103b48ef3 | [
"Apache-2.0"
] | 61 | 2019-06-19T13:17:14.000Z | 2022-03-21T14:10:16.000Z | src/test/java/io/hyperfoil/tools/qdup/config/rule/NonObservingCommandsTest.java | jesperpedersen/qDup | 549d660a321fb6c7d6e3f15e9460c2d103b48ef3 | [
"Apache-2.0"
] | 2 | 2021-03-30T11:41:25.000Z | 2022-03-10T11:10:29.000Z | 38.931298 | 152 | 0.486471 | 994,891 | package io.hyperfoil.tools.qdup.config.rule;
import io.hyperfoil.tools.qdup.SshTestBase;
import io.hyperfoil.tools.qdup.config.RunConfig;
import io.hyperfoil.tools.qdup.config.RunConfigBuilder;
import io.hyperfoil.tools.qdup.config.RunSummary;
import io.hyperfoil.tools.qdup.config.yaml.Parser;
import org.junit.Test;
import java.util.Objects;
import java.util.stream.Collectors;
import static org.junit.Assert.assertTrue;
public class NonObservingCommandsTest extends SshTestBase {
@Test
public void sh_in_script_in_watch() {
Parser parser = Parser.getInstance();
RunConfigBuilder builder = new RunConfigBuilder();
builder.loadYaml(parser.loadFile("test", stream("" +
"scripts:",
" doit:",
" - sh: echo bad",
" test:",
" - sh: echo foo",
" watch:",
" - script: ${{FOO}}",
"hosts:",
" local: me@localhost",
"roles:",
" role:",
" hosts: [local]",
" run-scripts:",
" - test",
"states:",
" FOO: doit"
)));
RunConfig config = builder.buildConfig(parser);
RunSummary summary = new RunSummary();
NonObservingCommands rule = new NonObservingCommands();
summary.addRule("observer",rule);
summary.scan(config.getRolesValues(), builder);
assertTrue("expect errors:\n" + summary.getErrors().stream().map(Objects::toString).collect(Collectors.joining("\n")), summary.hasErrors());
}
@Test
public void sh_in_onsignal () {
Parser parser = Parser.getInstance();
RunConfigBuilder builder = new RunConfigBuilder();
builder.loadYaml(parser.loadFile("test", stream("" +
"scripts:",
" test:",
" - sh: echo foo",
" on-signal:",
" foo:",
" - sh: echo bad",
"hosts:",
" local: me@localhost",
"roles:",
" role:",
" hosts: [local]",
" run-scripts:",
" - test"
)));
RunConfig config = builder.buildConfig(parser);
RunSummary summary = new RunSummary();
NonObservingCommands rule = new NonObservingCommands();
summary.addRule("observer",rule);
summary.scan(config.getRolesValues(), builder);
assertTrue("expect errors:\n" + summary.getErrors().stream().map(Objects::toString).collect(Collectors.joining("\n")), summary.hasErrors());
}
@Test
public void sh_in_timer () {
Parser parser = Parser.getInstance();
RunConfigBuilder builder = new RunConfigBuilder();
builder.loadYaml(parser.loadFile("test", stream("" +
"scripts:",
" test:",
" - sh: echo foo",
" timer:",
" 10s:",
" - sh: echo bad",
"hosts:",
" local: me@localhost",
"roles:",
" role:",
" hosts: [local]",
" run-scripts:",
" - test"
)));
RunConfig config = builder.buildConfig(parser);
RunSummary summary = new RunSummary();
NonObservingCommands rule = new NonObservingCommands();
summary.addRule("observer",rule);
summary.scan(config.getRolesValues(), builder);
assertTrue("expect errors:\n" + summary.getErrors().stream().map(Objects::toString).collect(Collectors.joining("\n")), summary.hasErrors());
}
@Test
public void sh_in_watch () {
Parser parser = Parser.getInstance();
RunConfigBuilder builder = new RunConfigBuilder();
builder.loadYaml(parser.loadFile("test", stream("" +
"scripts:",
" test:",
" - sh: echo foo",
" watch:",
" - sh: echo bad",
"hosts:",
" local: me@localhost",
"roles:",
" role:",
" hosts: [local]",
" run-scripts:",
" - test"
)));
RunConfig config = builder.buildConfig(parser);
RunSummary summary = new RunSummary();
NonObservingCommands rule = new NonObservingCommands();
summary.addRule("observer",rule);
summary.scan(config.getRolesValues(), builder);
assertTrue("expect errors:\n" + summary.getErrors().stream().map(Objects::toString).collect(Collectors.joining("\n")), summary.hasErrors());
}
}
|
922eda56e6312643a6dc58f5580757d08d8d96c3 | 1,857 | java | Java | src/main/java/com/freetymekiyan/algorithms/level/medium/PerfectSquares.java | petercdcn/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 1,958 | 2015-01-30T01:19:03.000Z | 2022-03-17T03:34:47.000Z | src/main/java/com/freetymekiyan/algorithms/level/medium/PerfectSquares.java | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 135 | 2016-03-03T04:53:10.000Z | 2022-03-03T21:14:37.000Z | src/main/java/com/freetymekiyan/algorithms/level/medium/PerfectSquares.java | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 914 | 2015-01-27T22:27:22.000Z | 2022-03-05T04:25:10.000Z | 28.136364 | 120 | 0.570275 | 994,892 | package com.freetymekiyan.algorithms.level.medium;
import java.util.Arrays;
/**
* 279. Perfect Squares
* <p>
* Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum
* to n.
* <p>
* For example,
* given n = 12, return 3 because 12 = 4 + 4 + 4;
* given n = 13, return 2 because 13 = 4 + 9.
* <p>
* Tags: Dynamic Programming, Breadth-first Search, Math
* Similar Problems: (E) Count Primes, (M) Ugly Number II
*/
public class PerfectSquares {
public static void main(String[] args) {
PerfectSquares ps = new PerfectSquares();
int res = ps.numSquares1(13);
System.out.println("res: " + res);
res = ps.numSquares2(13);
System.out.println("res: " + res);
}
/**
* A natural number is...
* <p>
* 1. a square if and only if each prime factor occurs to an even power in the number's prime factorization.
* 2. a sum of two squares if and only if each prime factor that's 3 modulo 4 occurs to an even power in the
* number's prime factorization.
* 3. a sum of three squares if and only if it's not of the form 4a(8b+7) with integers a and b.
* 4. a sum of four squares. Period. No condition. You never need more than four.
*/
public int numSquares1(int n) {
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
for (int a = 0; a * a <= n; a++) {
int b = (int) Math.sqrt(n - a * a);
if (a * a + b * b == n) {
return 1 + (a > 0 ? 1 : 0);
}
}
return 3;
}
/**
* DP, bottom-up
*/
public int numSquares2(int n) {
int[] res = new int[n + 1];
Arrays.fill(res, Integer.MAX_VALUE);
res[0] = 0;
for (int i = 0; i <= n; i++) {
for (int j = 1; j * j <= i; j++) {
res[i] = Math.min(res[i], res[i - j * j] + 1);
}
}
return res[n];
}
}
|
922eda81d00d67ab5292b08f11e82af2c159a295 | 2,878 | java | Java | src/main/resources/archetype-resources/src/main/java/data/model/Book.java | leandrocgsi/RestWithSpringBootUdemyArchetype | fec60ce4e3b1c6f387ac6a02f5bac2374436752c | [
"Apache-2.0"
] | 5 | 2021-03-08T20:39:30.000Z | 2022-03-27T18:27:48.000Z | src/main/resources/archetype-resources/src/main/java/data/model/Book.java | leandrocgsi/RestWithSpringBootUdemyArchetype | fec60ce4e3b1c6f387ac6a02f5bac2374436752c | [
"Apache-2.0"
] | null | null | null | src/main/resources/archetype-resources/src/main/java/data/model/Book.java | leandrocgsi/RestWithSpringBootUdemyArchetype | fec60ce4e3b1c6f387ac6a02f5bac2374436752c | [
"Apache-2.0"
] | 3 | 2021-02-03T00:32:23.000Z | 2021-12-31T11:55:40.000Z | 21.639098 | 79 | 0.664698 | 994,893 | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.data.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="books")
public class Book implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "author", nullable = false, length = 180)
private String author;
@Column(name = "launch_date", nullable = false)
@Temporal(TemporalType.DATE)
private Date launchDate;
@Column(nullable = false)
private Double price;
@Column(nullable = false, length = 250)
private String title;
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getLaunchDate() {
return launchDate;
}
public void setLaunchDate(Date launchDate) {
this.launchDate = launchDate;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((launchDate == null) ? 0 : launchDate.hashCode());
result = prime * result + ((price == null) ? 0 : price.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (launchDate == null) {
if (other.launchDate != null)
return false;
} else if (!launchDate.equals(other.launchDate))
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
} |
922eda8674a307dd4abd1cffb75000d10abd2ed3 | 1,396 | java | Java | samplestore/src/main/java/com/stripe/samplestore/ItemDivider.java | dri94/stripe-android | 7fa981b0a3e32d0ff152048b4bd8e71226926eb4 | [
"MIT"
] | null | null | null | samplestore/src/main/java/com/stripe/samplestore/ItemDivider.java | dri94/stripe-android | 7fa981b0a3e32d0ff152048b4bd8e71226926eb4 | [
"MIT"
] | null | null | null | samplestore/src/main/java/com/stripe/samplestore/ItemDivider.java | dri94/stripe-android | 7fa981b0a3e32d0ff152048b4bd8e71226926eb4 | [
"MIT"
] | null | null | null | 32.465116 | 99 | 0.680516 | 994,894 | package com.stripe.samplestore;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
class ItemDivider extends RecyclerView.ItemDecoration {
@NonNull private final Drawable divider;
/**
* Custom divider will be used in the list.
*/
ItemDivider(@NonNull Context context, @DrawableRes int resId) {
divider = ContextCompat.getDrawable(context, resId);
}
@Override
public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent,
@NonNull RecyclerView.State state) {
final int start = parent.getPaddingStart();
final int end = parent.getWidth() - parent.getPaddingEnd();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + divider.getIntrinsicHeight();
divider.setBounds(start, top, end, bottom);
divider.draw(c);
}
}
}
|
922eda877e4be6730f9f2dbef5dcd6d719799dc0 | 6,200 | java | Java | src/b2p/search/aima/minmax/MinMaxAlphaBetaSearch.java | AlessandroPomponio/B2P-Penicilin-Tablut-AI | c8a5664c86a51154afd5c193c567d98441a2146d | [
"BSD-3-Clause"
] | 28 | 2020-05-20T18:52:50.000Z | 2022-02-21T17:32:06.000Z | src/b2p/search/aima/minmax/MinMaxAlphaBetaSearch.java | AlessandroPomponio/B2P-Penicilin-Tablut-AI | c8a5664c86a51154afd5c193c567d98441a2146d | [
"BSD-3-Clause"
] | null | null | null | src/b2p/search/aima/minmax/MinMaxAlphaBetaSearch.java | AlessandroPomponio/B2P-Penicilin-Tablut-AI | c8a5664c86a51154afd5c193c567d98441a2146d | [
"BSD-3-Clause"
] | 2 | 2020-11-25T18:29:50.000Z | 2021-06-04T11:45:16.000Z | 30.097087 | 123 | 0.636774 | 994,895 | package b2p.search.aima.minmax;
import b2p.model.IAction;
import b2p.model.IState;
import b2p.search.aima.TablutGame;
import it.unibo.ai.didattica.competition.tablut.domain.State;
import java.util.concurrent.Callable;
/**
* This class represents a Minimax search with alpha-beta pruning to be ran on a game state.
* It implements {@link Callable} in order to allow for asynchronous execution.
*
* @author Alessandro Buldini
* @author Alessandro Pomponio
* @author Federico Zanini
* @see <a href="https://github.com/aimacode/aima-java">AIMA Java</a>
*/
public class MinMaxAlphaBetaSearch implements Callable<Integer> {
/**
* Object that represents the Iterative Deepening strategy
*/
private final IterativeDeepening strategy;
/**
* Instance of the game that needs to be evaluated
*/
private final TablutGame game;
/**
* Current state of the game that needs to be evaluated
*/
private final IState state;
/**
* Initial action based on which the function's decision tree is created
*/
private final IAction action;
/**
* Player for which the decision needs to be made
*/
private final State.Turn player;
/**
* Minimum value the heuristic function can assume
*/
private final int utilMin;
/**
* Maximum value the heuristic function can assume
*/
private final int utilMax;
/**
* Depth limit set by the Iterative Deepening strategy
*/
private final int depthLimit;
/**
* Builds a MinMaxAlphaBetaSearch object given the strategy, the current state of the game, the initial action and
* the player for whom the best decision has to be made
*
* @param strategy instance of {@code Iterative Deepening} strategy
* @param state current state of the game
* @param action initial action performed for this thread based on which the function's decision tree is created
* @param player player for whom the best decision has to be made
* @see IterativeDeepening
*/
protected MinMaxAlphaBetaSearch(IterativeDeepening strategy, IState state, IAction action, State.Turn player) {
//
super();
//
this.strategy = strategy;
//
game = new TablutGame(state);
//
this.state = state;
this.action = action;
this.player = player;
//
utilMax = strategy.getUtilMax();
utilMin = strategy.getUtilMin();
//
depthLimit = strategy.getCurrDepthLimit();
}
/**
* function needed to implement correctly the alpha-beta pruning: detects the maximum value between two possible states
* and prunes all the sub-trees that won't be explored according to the current heuristic function
*
* @param state current state of the game
* @param player player that performs the move
* @param alpha alpha value
* @param beta beta value
* @param depth current depth
* @return maximum heuristic value between two states within the decision tree
* @see IState
*/
public int maxValue(IState state, State.Turn player, int alpha, int beta, int depth) {
//
strategy.updateMetrics(depth);
//
if (game.isTerminal(state) || depth >= depthLimit || strategy.getTimer().timeOutOccurred())
return eval(state, player);
// The worst case for the maximizer is the minimum value
int value = utilMin;
for (IAction action : game.getActions(state)) {
// Min/Max depth-first
int minimizerValue = minValue(game.getResult(state, action), player, alpha, beta, depth + 1);
value = Math.max(value, minimizerValue);
// Alpha/Beta pruning
if (value >= beta)
return value;
// Update alpha value for maximizer
alpha = Math.max(alpha, value);
}
return value;
}
/**
* function needed to implement correctly the alpha-beta pruning: detects the minimum value between two possible states
* and prunes all the sub-trees that won't be explored according to the current heuristic function
*
* @param state current state of the game
* @param player player that performs the move
* @param alpha alpha value
* @param beta beta value
* @param depth current depth
* @return minimum heuristic value between two states within the decision tree
* @see IState
*/
public int minValue(IState state, State.Turn player, int alpha, int beta, int depth) {
//
strategy.updateMetrics(depth);
//
if (game.isTerminal(state) || depth >= depthLimit || strategy.getTimer().timeOutOccurred())
return eval(state, player);
// The worst case scenario for the minimizer is Maxvalue
int value = utilMax;
for (IAction action : game.getActions(state)) {
// Min/Max depth-first
int maximizerValue = maxValue(game.getResult(state, action), player, alpha, beta, depth + 1);
value = Math.min(value, maximizerValue);
// Alpha/Beta pruning
if (value <= alpha)
return value;
// Update beta value for minimizer
beta = Math.min(beta, value);
}
return value;
}
/**
* Evaluates a state according to {@link TablutGame}'s heuristic function
*
* @param state current state of the game
* @param player player for whom the heuristic value has to be calculated
* @return an heuristic integer value
* @see TablutGame
*/
private int eval(IState state, State.Turn player) {
return game.getUtility(state, player);
}
/**
* Starts searching for the best decision to be made given an initial action
*
* @return an integer containing the best heuristic value according to Iterative Deepening MiniMax search with
* alpha-beta pruning
*/
@Override
public Integer call() {
return minValue(game.getResult(state, action), player, utilMin, utilMax, 1);
}
}
|
922edaa63ad91802586b92384488b650bc5b2ae8 | 1,224 | java | Java | src/main/java/com/zzpage/visitant/model/VisitantRequestUserAgent.java | khanorder/visitant | 232dcdf476d8661158eaf1c0204e57264c7ce8ec | [
"MIT"
] | null | null | null | src/main/java/com/zzpage/visitant/model/VisitantRequestUserAgent.java | khanorder/visitant | 232dcdf476d8661158eaf1c0204e57264c7ce8ec | [
"MIT"
] | 6 | 2019-11-13T12:04:47.000Z | 2021-12-14T21:33:10.000Z | src/main/java/com/zzpage/visitant/model/VisitantRequestUserAgent.java | khanorder/visitant | 232dcdf476d8661158eaf1c0204e57264c7ce8ec | [
"MIT"
] | null | null | null | 21.103448 | 124 | 0.663399 | 994,896 | package com.zzpage.visitant.model;
import java.util.Map;
public class VisitantRequestUserAgent {
private String ua;
private Map<String, String> browser;
private Map<String, String> engine;
private Map<String, String> os;
private Map<String, String> device;
private Map<String, String> cpu;
public VisitantRequestUserAgent() {
}
public VisitantRequestUserAgent(String ua, Map<String, String> browser, Map<String, String> engine, Map<String, String> os,
Map<String, String> device, Map<String, String> cpu) {
this.ua = ua;
this.browser = browser;
this.engine = engine;
this.os = os;
this.device = device;
this.cpu = cpu;
}
public String getUa() {
return ua;
}
public Map<String, String> getBrowser() {
return browser;
}
public Map<String, String> getEngine() {
return engine;
}
public Map<String, String> getOs() {
return os;
}
public Map<String, String> getDevice() {
return device;
}
public Map<String, String> getCpu() {
return cpu;
}
@Override
public String toString() {
return "VisitantUserAgent [\n\tua=" + ua + ", \n\tbrowser=" + browser + ", \n\tengine=" + engine + ", \n\tos="
+ os + ", \n\tdevice=" + device + ", \n\tcpu=" + cpu + "\n]";
}
}
|
922edae351d22dab8b45638e835cdeaa68953482 | 1,596 | java | Java | pta-intelligent-search-metadata-annotation/src/main/java/fi/maanmittauslaitos/pta/search/text/TextSplitterProcessor.java | spatineo/pta-intelligent-search | 194588904345ddaee284a8b8846c23dedbc1cc2c | [
"CC-BY-4.0"
] | 2 | 2018-08-23T01:47:40.000Z | 2019-11-29T15:04:45.000Z | pta-intelligent-search-metadata-annotation/src/main/java/fi/maanmittauslaitos/pta/search/text/TextSplitterProcessor.java | spatineo/pta-intelligent-search | 194588904345ddaee284a8b8846c23dedbc1cc2c | [
"CC-BY-4.0"
] | 9 | 2019-08-21T08:20:40.000Z | 2021-12-14T21:11:34.000Z | pta-intelligent-search-metadata-annotation/src/main/java/fi/maanmittauslaitos/pta/search/text/TextSplitterProcessor.java | spatineo/pta-intelligent-search | 194588904345ddaee284a8b8846c23dedbc1cc2c | [
"CC-BY-4.0"
] | 3 | 2019-08-01T07:21:14.000Z | 2020-05-11T12:30:50.000Z | 26.6 | 123 | 0.726817 | 994,897 | package fi.maanmittauslaitos.pta.search.text;
import fi.maanmittauslaitos.pta.search.text.stemmer.Stemmer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class TextSplitterProcessor implements TextProcessor {
private static final String PATTERN = "(?U)(?!-\\w)\\W+";
private static final String HYPHEN = "-";
private final Stemmer stemmer;
private final boolean joinHyphened;
private final Collection<String> wellKnownPostfixes;
private TextSplitterProcessor(Stemmer stemmer, Collection<String> wellKnownPostfixes, boolean joinHyphened) {
this.stemmer = stemmer;
this.wellKnownPostfixes = wellKnownPostfixes;
this.joinHyphened = joinHyphened;
}
public static TextSplitterProcessor create(Stemmer stemmer, Collection<String> wellKnownPostfixes, boolean joinHyphened) {
return new TextSplitterProcessor(stemmer, wellKnownPostfixes, joinHyphened);
}
@Override
public List<String> process(List<String> input) {
List<String> ret = new ArrayList<>();
for (String str : input) {
String[] words = str.split(PATTERN);
for (String w : words) {
if (w == null || w.length() == 0) continue;
if (w.contains(HYPHEN)) {
handleHyphened(ret, w);
}
ret.add(w);
}
}
return ret;
}
private void handleHyphened(List<String> ret, String w) {
String[] wordParts = w.split(HYPHEN);
if (wellKnownPostfixes.contains(stemmer.stem(wordParts[wordParts.length - 1]))) {
ret.addAll(Arrays.asList(wordParts));
}
if (joinHyphened) {
ret.add(String.join("", wordParts));
}
}
}
|
922edb0cf4ab59c9cdcf71c5a22bc307a3916a66 | 18,214 | java | Java | src/main/java/org/monster/common/util/UnitCache.java | RoySRose/Monster | 5dfedbac19cf8777ba71bc4ab0389a51efc61177 | [
"MIT"
] | null | null | null | src/main/java/org/monster/common/util/UnitCache.java | RoySRose/Monster | 5dfedbac19cf8777ba71bc4ab0389a51efc61177 | [
"MIT"
] | null | null | null | src/main/java/org/monster/common/util/UnitCache.java | RoySRose/Monster | 5dfedbac19cf8777ba71bc4ab0389a51efc61177 | [
"MIT"
] | 2 | 2021-05-17T14:40:48.000Z | 2021-12-08T22:59:20.000Z | 35.78389 | 193 | 0.617986 | 994,898 | package org.monster.common.util;
import bwapi.Game;
import bwapi.TilePosition;
import bwapi.Unit;
import bwapi.UnitType;
import org.monster.build.base.ConstructionManager;
import org.monster.build.base.ConstructionTask;
import org.monster.common.MapGrid;
import org.monster.common.UnitInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/// 유닛 리스트를 부하가 걸리지 않도록 관리
public class UnitCache implements InfoCollector {
private static UnitCache unitCache = new UnitCache();
public static UnitCache getCurrentCache() {
return unitCache;
}
private Game Broodwar;
// 아군 UnitType 발견 여부
private Map<UnitType, Boolean> selfUnitDiscovered = new HashMap<>();
private Map<UnitType, Boolean> selfCompleteUnitDiscovered = new HashMap<>();
// 아군 모든 UnitType 리스트
private List<Unit> selfCompleteUnitList = new ArrayList<>(); /// 아군 완성 유닛 리스트
private List<Unit> selfIncompleteUnitList = new ArrayList<>(); /// 아군 미완성 유닛 리스트
private List<ConstructionTask> selfConstructionTaskList = new ArrayList<>(); /// 아군 건설큐의 건물 리스트
// 아군 UnitType별 맵
private Map<UnitType, List<Unit>> selfAllUnitByTypeMap = new HashMap<>(); /// 아군 모든 유닛
private Map<UnitType, List<Unit>> selfCompleteUnitByTypeMap = new HashMap<>(); /// 아군 완성 유닛
private Map<UnitType, List<Unit>> selfIncompleteUnitByTypeMap = new HashMap<>(); /// 아군 미완성 유닛
private Map<UnitType, List<ConstructionTask>> selfConstructionTaskMap = new HashMap<>(); /// 아군 건설큐의 건물
// 적군 UnitType 발견 여부
private Map<UnitType, Boolean> enemyUnitDiscovered = new HashMap<>();
private Map<UnitType, Boolean> enemyCompleteUnitDiscovered = new HashMap<>();
//TODO completed, incompleted enemey unit list 가 필요할까?
// 적군 맵
private Map<Integer, UnitInfo> enemyAllUnitInfoMap = new HashMap<>(); /// 적군 모든 유닛정보
// 적군 UnitType별 맵
private Map<UnitType, List<UnitInfo>> enemyAllUnitInfoByTypeMap = new HashMap<>(); /// 적군 모든 유닛정보
private Map<UnitType, List<UnitInfo>> enemyVisibleUnitInfoByTypeMap = new HashMap<>(); /// 보이는 적군 유닛정보
//TODO badUnitstoRemove needed?
private Vector<Integer> badUnitstoRemove = new Vector<Integer>();
@Override
public void onStart(Game Broodwar) {
this.Broodwar = Broodwar;
}
@Override
public void update() {
clearAll();
putSelfData();
//putEnemyData();
removeBadUnits();
updateDiscoveredMap();
//TODO issue 11?
cacheToUnmodifiable();
}
private void cacheToUnmodifiable() {
}
protected Map<UnitType, Boolean> selfUnitDiscovered() {
return selfUnitDiscovered;
}
protected Map<UnitType, Boolean> selfCompleteUnitDiscovered() {
return selfCompleteUnitDiscovered;
}
protected int allCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return Broodwar.self().getUnits().size();
} else {
return selfAllUnitByTypeMap.getOrDefault(unitType, new ArrayList<>()).size();
}
}
protected List<Unit> allUnits(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return Broodwar.self().getUnits();
} else {
return selfAllUnitByTypeMap.getOrDefault(unitType, new ArrayList<>());
}
}
protected int completeCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return selfCompleteUnitList.size();
} else {
return selfCompleteUnitByTypeMap.getOrDefault(unitType, new ArrayList<>()).size();
}
}
protected List<Unit> completeUnits(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return selfCompleteUnitList;
} else {
return selfCompleteUnitByTypeMap.getOrDefault(unitType, new ArrayList<>());
}
}
protected int incompleteCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return selfIncompleteUnitList.size();
} else {
return selfIncompleteUnitByTypeMap.getOrDefault(unitType, new ArrayList<>()).size();
}
}
protected List<Unit> incompleteUnits(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return selfIncompleteUnitList;
} else {
return selfIncompleteUnitByTypeMap.getOrDefault(unitType, new ArrayList<>());
}
}
protected int underConstructionCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return selfConstructionTaskList.size();
} else {
return selfConstructionTaskMap.getOrDefault(unitType, new ArrayList<>()).size();
}
}
//TODO 필요한가?
// 실제 construction queue의 사이즈보다 유닛리스트의 수가 적을 수 있다.(건설시작 전인 빌딩이 있을수 있으므로)
protected List<Unit> underConstructionUnits(UnitType unitType) {
List<Unit> unitList = new ArrayList<>();
List<ConstructionTask> tasks;
if (unitType == UnitType.AllUnits) {
tasks = selfConstructionTaskList;
} else {
tasks = selfConstructionTaskMap.get(unitType);
}
for (ConstructionTask task : tasks) {
if (task.getBuildingUnit() != null) {
unitList.add(task.getBuildingUnit());
}
}
return unitList;
}
////////////////////// 적군 유닛정보 리스트 관련
protected Map<UnitType, Boolean> enemyUnitDiscovered() {
return enemyUnitDiscovered;
}
protected Map<UnitType, Boolean> enemyCompleteUnitDiscovered() {
return enemyCompleteUnitDiscovered;
}
protected int enemyAllCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return enemyAllUnitInfoMap.size();
} else {
return enemyAllUnitInfoByTypeMap.getOrDefault(unitType, new ArrayList<>()).size();
}
}
protected List<UnitInfo> enemyAllUnits(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return new ArrayList<>(enemyAllUnitInfoMap.values());
} else {
return enemyAllUnitInfoByTypeMap.getOrDefault(unitType, new ArrayList<>());
}
}
protected int enemyVisibleCount(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return Broodwar.enemy().allUnitCount();
} else {
return Broodwar.enemy().allUnitCount(unitType);
}
}
protected List<Unit> getEnemyUnitList() {
return Broodwar.enemy().getUnits();
}
protected List<UnitInfo> enemyVisibleUnits(UnitType unitType) {
if (unitType == UnitType.AllUnits) {
return new ArrayList(enemyAllUnitInfoMap.values());
} else {
if (enemyVisibleUnitInfoByTypeMap.size() == 0) {
//create enemyVisibleUnitInfoByTypeMap at first request in frame
for (Unit unit : Broodwar.enemy().getUnits()) {
List<UnitInfo> unitInfoList = enemyVisibleUnitInfoByTypeMap.getOrDefault(unit.getType(), new ArrayList<>());
UnitInfo unitInfo = new UnitInfo(unit);
unitInfoList.add(unitInfo);
enemyVisibleUnitInfoByTypeMap.put(unit.getType(), unitInfoList);
}
}
return new ArrayList<>(enemyVisibleUnitInfoByTypeMap.getOrDefault(unitType, new ArrayList<>()));
}
}
private void clearAll() {
selfCompleteUnitList.clear();
selfIncompleteUnitList.clear();
selfConstructionTaskList.clear();
selfAllUnitByTypeMap.clear();
selfCompleteUnitByTypeMap.clear();
selfIncompleteUnitByTypeMap.clear();
selfConstructionTaskMap.clear();
// enemyAllUnitInfoList.clear();
// enemyVisibileUnitInfoList.clear();
// enemyInvisibleUnitInfoList.clear();
//
// enemyAllUnitInfoByTypeMap.clear();
// enemyVisibleUnitInfoByTypeMap.clear();
// enemyInvisibleUnitInfoByTypeMap.clear();
}
private void putSelfData() {
for (Unit unit : Broodwar.self().getUnits()) {
if (unit == null) {
continue;
}
List<Unit> allUnitList = selfAllUnitByTypeMap.getOrDefault(unit.getType(), new ArrayList<>());
List<Unit> completeUnitList = selfCompleteUnitByTypeMap.getOrDefault(unit.getType(), new ArrayList<>());
List<Unit> incompleteUnitList = selfIncompleteUnitByTypeMap.getOrDefault(unit.getType(), new ArrayList<>());
allUnitList.add(unit);
if (unit.isCompleted()) {
completeUnitList.add(unit);
selfCompleteUnitList.add(unit);
} else {
incompleteUnitList.add(unit);
selfIncompleteUnitList.add(unit);
}
selfAllUnitByTypeMap.put(unit.getType(), allUnitList);
selfCompleteUnitByTypeMap.put(unit.getType(), completeUnitList);
selfIncompleteUnitByTypeMap.put(unit.getType(), incompleteUnitList);
}
Vector<ConstructionTask> constructionTaskvector = ConstructionManager.Instance().getConstructionQueue();
for (ConstructionTask constructionTask : constructionTaskvector) {
List<ConstructionTask> constructionTaskList = selfConstructionTaskMap.getOrDefault(constructionTask.getType(), new ArrayList<ConstructionTask>());
selfConstructionTaskList.add(constructionTask);
constructionTaskList.add(constructionTask);
selfConstructionTaskMap.put(constructionTask.getType(), constructionTaskList);
}
}
// private void putEnemyData() {
// UnitData enemyUnitData = InformationManager.Instance().getUnitData(Broodwar.enemy());
// for (int unitId : enemyUnitData.getUnitAndUnitInfoMap().keySet()) {
// UnitInfo unitInfo = enemyUnitData.getUnitAndUnitInfoMap().get(unitId);
//
// List<UnitInfo> allUnitList = enemyAllUnitInfoByTypeMap.getOrDefault(unitInfo.getType(), new ArrayList<>());
// List<UnitInfo> visibleUnitList = enemyVisibleUnitInfoByTypeMap.getOrDefault(unitInfo.getType(), new ArrayList<>());
//
// allUnitList.add(unitInfo);
// enemyAllUnitInfoList.add(unitInfo);
// Unit enemy = Broodwar.getUnit(unitInfo.getUnitID());
// if (enemy != null && enemy.getType() != UnitType.Unknown) {
// visibleUnitList.add(unitInfo);
// enemyVisibileUnitInfoList.add(unitInfo);
// }
//
// enemyAllUnitInfoByTypeMap.put(unitInfo.getType(), allUnitList);
// enemyVisibleUnitInfoByTypeMap.put(unitInfo.getType(), visibleUnitList);
// }
// }
protected void updateEnemyUnitInfo(Unit newUnit) {
if (newUnit == null) {
return;
}
if (newUnit.getPlayer() != PlayerUtils.enemyPlayer()) {
return;
}
//TODO 이러는게 맞나? 실제 호출되는 타이밍이 보이거나 사라질때뿐인데. 만약에 지속적으로 보일때는?
if (!enemyAllUnitInfoMap.containsKey(newUnit.getID())) {
enemyAllUnitInfoMap.put(newUnit.getID(), new UnitInfo(newUnit));
UnitInfo unitInfo = new UnitInfo(newUnit);
List<UnitInfo> unitInfoList = enemyAllUnitInfoByTypeMap.getOrDefault(newUnit.getType(), new ArrayList<>());
unitInfoList.add(unitInfo);
enemyAllUnitInfoByTypeMap.put(newUnit.getType(), unitInfoList);
} else {
UnitInfo unitInfo = enemyAllUnitInfoMap.get(newUnit.getID());
if (unitInfo.getUnitID() == newUnit.getID() && newUnit.getType() != unitInfo.getType()) {
if (unitInfo.getType() != UnitType.None) {
removeUnitbyMorph(unitInfo, unitInfo.getType());
enemyAllUnitInfoMap.put(newUnit.getID(), new UnitInfo(newUnit));
List<UnitInfo> unitInfoList = enemyAllUnitInfoByTypeMap.getOrDefault(newUnit.getType(), new ArrayList<>());
unitInfoList.add(unitInfo);
}
}
}
}
protected void destroyedUnitInfo(Unit destroyedUnit) {
if (destroyedUnit == null) {
return;
}
if (destroyedUnit.getPlayer() != PlayerUtils.enemyPlayer()) {
return;
}
// if (enemyAllUnitInfoMap.containsKey(destroyedUnit.getID())) {
enemyAllUnitInfoMap.remove(destroyedUnit.getID());
List<UnitInfo> allUnitInfoList = enemyAllUnitInfoByTypeMap.get(destroyedUnit.getType());
for (UnitInfo unitInfo : allUnitInfoList) {
if (unitInfo.getUnitID() == destroyedUnit.getID()) {
allUnitInfoList.remove(unitInfo);
break;
}
}
}
protected void removeUnitbyMorph(UnitInfo morphedUnit, UnitType type) {
if (morphedUnit == null) {
return;
}
if (type == null) {
return;
}
enemyAllUnitInfoMap.remove(morphedUnit.getUnitID());
List<UnitInfo> unitInfoList = enemyAllUnitInfoByTypeMap.get(type);
for (UnitInfo unitInfo : unitInfoList) {
if (unitInfo.getUnitID() == morphedUnit.getUnitID()) {
unitInfoList.remove(unitInfo);
break;
}
}
}
private void updateDiscoveredMap() {
for (Unit selfUnit : Broodwar.self().getUnits()) {
if (selfUnit == null) {
return;
}
UnitType unitType = selfUnit.getType();
Boolean discovered = selfUnitDiscovered.get(unitType);
if (discovered == null || discovered == Boolean.FALSE) {
selfUnitDiscovered.put(unitType, Boolean.TRUE);
}
if (selfUnit.isCompleted()) {
Boolean discoveredComplete = selfCompleteUnitDiscovered.get(unitType);
if (discoveredComplete == null || discoveredComplete == Boolean.FALSE) {
selfCompleteUnitDiscovered.put(unitType, Boolean.TRUE);
}
}
}
for (Unit enemyUnit : Broodwar.enemy().getUnits()) {
if (enemyUnit == null) {
return;
}
UnitType unitType = enemyUnit.getType();
Boolean discovered = enemyUnitDiscovered.get(unitType);
if (discovered == null || discovered == Boolean.FALSE) {
enemyUnitDiscovered.put(unitType, Boolean.TRUE);
}
if (enemyUnit.isCompleted()) {
Boolean discoveredComplete = enemyCompleteUnitDiscovered.get(unitType);
if (discoveredComplete == null || discoveredComplete == Boolean.FALSE) {
enemyCompleteUnitDiscovered.put(unitType, Boolean.TRUE);
}
}
}
}
/// 포인터가 null 이 되었거나, 파괴되어 Resource_Vespene_Geyser로 돌아간 Refinery, 예전에는 건물이 있었던 걸로 저장해두었는데 지금은 파괴되어 없어진 건물 (특히, 테란의 경우 불타서 소멸한 건물) 데이터를 제거합니다
private void removeBadUnits() {
Iterator<Integer> it = enemyAllUnitInfoMap.keySet().iterator();
while (it.hasNext()) {
UnitInfo unitInfo = enemyAllUnitInfoMap.get(it.next());
if (isBadUnitInfo(unitInfo)) {
List<UnitInfo> allUnitInfoList = enemyAllUnitInfoByTypeMap.get(unitInfo.getType());
if (unitInfo.getUnitID() == unitInfo.getUnitID()) {
allUnitInfoList.remove(unitInfo);
}
enemyAllUnitInfoMap.remove(unitInfo);
}
}
}
private final boolean isBadUnitInfo(final UnitInfo ui) {
if (ui.getUnit() == null) {
return false;
}
// Cull away any refineries/assimilators/extractors that were destroyed and reverted to vespene geysers
if (ui.getUnit().getType() == UnitType.Resource_Vespene_Geyser) {
return true;
}
if (ui.getType().isBuilding() && Broodwar.isVisible(ui.getLastPosition().getX() / 32, ui.getLastPosition().getY() / 32) && (!ui.getUnit().isTargetable() || !ui.getUnit().isVisible())) {
if (MapGrid.Instance().scanAbnormalTime()) {
return false;
} else {
return true;
}
}
return false;
}
public void onUnitShow(Unit unit) {
updateEnemyUnitInfo(unit);
}
public void onUnitHide(Unit unit) {
updateEnemyUnitInfo(unit);
}
public void onUnitCreate(Unit unit) {
updateEnemyUnitInfo(unit);
}
public void onUnitComplete(Unit unit) {
updateEnemyUnitInfo(unit);
}
//TODO how about morph cancel?
public void onUnitMorph(Unit unit) {
updateEnemyUnitInfo(unit);
}
public void onUnitRenegade(Unit unit) {
updateEnemyUnitInfo(unit);
}
/// Unit 에 대한 정보를 업데이트합니다 <br>
/// 유닛이 파괴/사망한 경우, 해당 유닛 정보를 삭제합니다
public void onUnitDestroy(Unit unit) {
destroyedUnitInfo(unit);
}
protected Unit enemyUnitInSight(UnitInfo eui) {
Unit enemyUnit = Broodwar.getUnit(eui.getUnitID());
if (UnitUtils.isValidUnit(enemyUnit)) {
return enemyUnit;
} else {
return null;
}
}
protected Unit enemyUnitInSight(int euiId) {
Unit enemyUnit = Broodwar.getUnit(euiId);
if (UnitUtils.isValidUnit(enemyUnit)) {
return enemyUnit;
} else {
return null;
}
}
protected List<Unit> getUnitsOnTile(TilePosition tilePosition) {
return Broodwar.getUnitsOnTile(tilePosition);
}
protected boolean canMake(UnitType unitType, Unit unit) {
return Broodwar.canMake(unitType, unit);
}
protected boolean canMake(UnitType unitType) {
return Broodwar.canMake(unitType);
}
protected Unit getUnit(int unitId) {
return Broodwar.getUnit(unitId);
}
protected int myDeadNumUnits(UnitType unitType) {
return Broodwar.self().deadUnitCount(unitType);
}
protected int enemyDeadNumUnits(UnitType unitType) {
return Broodwar.enemy().deadUnitCount(unitType);
}
} |
922edc264169e823f90b923e1b7259d10d823a56 | 1,395 | java | Java | Blocks/old/seia/gra/block/movable/player/InventoryPlayer.java | Sejoslaw/Blocks | 26311a2f6d5d7ab8b932235897742e7f59f587ca | [
"Zlib"
] | 1 | 2015-12-08T20:26:40.000Z | 2015-12-08T20:26:40.000Z | Blocks/old/seia/gra/block/movable/player/InventoryPlayer.java | Sejoslaw/Blocks | 26311a2f6d5d7ab8b932235897742e7f59f587ca | [
"Zlib"
] | null | null | null | Blocks/old/seia/gra/block/movable/player/InventoryPlayer.java | Sejoslaw/Blocks | 26311a2f6d5d7ab8b932235897742e7f59f587ca | [
"Zlib"
] | null | null | null | 17.884615 | 68 | 0.658065 | 994,899 | package seia.gra.block.movable.player;
import seia.gra.item.Item;
import seia.gra.item.ItemStack;
public class InventoryPlayer
{
public BlockPlayer player;
public int inventorySize = 10;
public ItemStack[] currentInventory = new ItemStack[inventorySize];
public ItemStack currentlyInHand;
public InventoryPlayer(BlockPlayer blockPlayer)
{
player = blockPlayer;
}
public void addItemToInventory(int slot, Item item)
{
currentInventory[slot].stackSize++;
}
public int getFirstEmptySlot()
{
for(int i = 0; i < inventorySize; i++)
{
if(currentInventory[i] == null)
{
return i;
}
}
return 0;
}
public boolean isItemValidForSlot(int slot, Item item)
{
ItemStack st = currentInventory[slot];
if(st != null)
{
if(st.item.itemID == item.itemID)
{
if(st.stackSize < ItemStack.stackLimit)
{
return true;
}
}
}
return false;
}
public void addItemToFirstAvaiable(Item item)
{
for(int i = 0; i < inventorySize; i++)
{
ItemStack st = currentInventory[i];
if(isItemValidForSlot(i, item))
{
addItemToInventory(i, item);
return;
}
if(st == null)
{
currentInventory[i] = new ItemStack(item);
return;
}
if(st.item == null)
{
currentInventory[i].addSingleItem(item);
return;
}
}
}
public void clearSlot(int slot)
{
currentInventory[slot].emptyStack();
}
} |
922edc5e9fbc6484f29373b76110a24d4ccd596c | 7,009 | java | Java | src/Compiler/Opt/InvariantConditionResort.java | KurodaKanbei/Compiler-2018 | 49d10c79786a59ac71a1eb9e977fbefe15c9eabb | [
"MIT"
] | 1 | 2019-01-10T14:42:48.000Z | 2019-01-10T14:42:48.000Z | src/Compiler/Opt/InvariantConditionResort.java | KurodaKanbei/Compiler-2018 | 49d10c79786a59ac71a1eb9e977fbefe15c9eabb | [
"MIT"
] | null | null | null | src/Compiler/Opt/InvariantConditionResort.java | KurodaKanbei/Compiler-2018 | 49d10c79786a59ac71a1eb9e977fbefe15c9eabb | [
"MIT"
] | 4 | 2018-04-28T18:30:05.000Z | 2018-11-11T15:34:13.000Z | 78.752809 | 183 | 0.601512 | 994,900 | package Compiler.Opt;
import Compiler.AST.Statement.ForStatement;
import Compiler.AST.Statement.IfStatement;
import Compiler.AST.Statement.Statement;
import Compiler.CFG.Block;
import Compiler.CFG.FunctionIR;
import Compiler.CFG.Instruction.*;
import Compiler.CFG.Operand.VirtualRegister;
import java.util.List;
public class InvariantConditionResort {
public static void invariantCodeResort(FunctionIR functionIR) {
for (int i = 0; i + 14 < functionIR.getBlockList().size(); i++) {
if (isLoop(functionIR, i, i + 1, i + 13, i + 14)
&& isLoop(functionIR, i + 2, i + 3, i + 11, i + 12)
&& isLoop(functionIR, i + 4, i + 5, i + 9, i + 10)
&& isBranch(functionIR, i + 6, i + 7, i + 8)) {
if (functionIR.getBlockList().get(i).getInstructionList().size() == 5
&& functionIR.getBlockList().get(i + 1).getInstructionList().size() == 2
&& functionIR.getBlockList().get(i + 2).getInstructionList().size() == 5
&& functionIR.getBlockList().get(i + 3).getInstructionList().size() == 2
&& functionIR.getBlockList().get(i + 4).getInstructionList().size() == 5
&& functionIR.getBlockList().get(i + 5).getInstructionList().size() == 5) {
Block block_i = functionIR.getBlockList().get(i);
Block block_j = functionIR.getBlockList().get(i + 2);
Block block_if = functionIR.getBlockList().get(i + 5);
if (block_i.getInstructionList().get(0) instanceof CompareInstruction
&& block_j.getInstructionList().get(0) instanceof CompareInstruction
&& block_if.getInstructionList().get(0) instanceof CompareInstruction) {
CompareInstruction compareInstruction1 = (CompareInstruction) block_i.getInstructionList().get(0);
CompareInstruction compareInstruction2 = (CompareInstruction) block_j.getInstructionList().get(0);
CompareInstruction compareInstruction3 = (CompareInstruction) block_if.getInstructionList().get(0);
if (compareInstruction1.getLeftOperand() instanceof VirtualRegister
&& compareInstruction2.getLeftOperand() instanceof VirtualRegister
&& compareInstruction3.getLeftOperand() instanceof VirtualRegister
&& compareInstruction3.getRightOperand() instanceof VirtualRegister) {
VirtualRegister virtualRegister1 = (VirtualRegister) compareInstruction1.getLeftOperand();
VirtualRegister virtualRegister2 = (VirtualRegister) compareInstruction2.getLeftOperand();
if (virtualRegister1 == compareInstruction3.getLeftOperand() && virtualRegister2 == compareInstruction3.getRightOperand()
|| virtualRegister1 == compareInstruction3.getRightOperand() && virtualRegister2 == compareInstruction3.getLeftOperand()) {
LabelInstruction labelInstruction = new LabelInstruction("resort_condition");
Block insertedBlock = new Block(functionIR, labelInstruction, labelInstruction.getName(), functionIR.getBlockList().size());
labelInstruction.setBlock(insertedBlock);
insertedBlock.getInstructionList().addAll(block_if.getInstructionList());
if (insertedBlock.getInstructionList().get(3) instanceof CJumpInstruction
&& insertedBlock.getInstructionList().get(4) instanceof JumpInstruction) {
((CJumpInstruction) insertedBlock.getInstructionList().get(3)).setTarget(functionIR.getBlockList().get(i + 3).getLabelInstruction());
((JumpInstruction) insertedBlock.getInstructionList().get(4)).setTarget(functionIR.getBlockList().get(i + 11).getLabelInstruction());
if (functionIR.getBlockList().get(i + 2).getInstructionList().get(3) instanceof CJumpInstruction) {
((CJumpInstruction) functionIR.getBlockList().get(i + 2).getInstructionList().get(3)).setTarget(insertedBlock.getLabelInstruction());
block_if.getInstructionList().clear();
block_if.getInstructionList().add(new JumpInstruction(functionIR.getBlockList().get(i + 6).getLabelInstruction()));
List<Instruction> instructionList = functionIR.getBlockList().get(i + 6).getInstructionList();
functionIR.getBlockList().get(i + 6).setInstructionList(instructionList.subList(0, 39));
functionIR.getBlockList().get(i + 6).getInstructionList().add(new JumpInstruction(functionIR.getBlockList().get(i + 8).getLabelInstruction()));
functionIR.getBlockList().remove(i + 7);
functionIR.getBlockList().add(i + 3, insertedBlock);
//System.out.println(functionIR.toString(0));
}
}
}
}
}
}
}
}
}
private static boolean isLoop(FunctionIR functionIR, int conditionIndex, int bodyIndex, int incrementIndex, int exitIndex) {
Statement loop1 = functionIR.getBlockList().get(conditionIndex).getLabelInstruction().getBelongTo();
Statement loop2 = functionIR.getBlockList().get(bodyIndex).getLabelInstruction().getBelongTo();
Statement loop3 = functionIR.getBlockList().get(incrementIndex).getLabelInstruction().getBelongTo();
Statement loop4 = functionIR.getBlockList().get(exitIndex).getLabelInstruction().getBelongTo();
return loop1 instanceof ForStatement && loop2 instanceof ForStatement && loop3 instanceof ForStatement && loop4 instanceof ForStatement &&
loop1 == loop2 && loop2 == loop3 && loop3 == loop4;
}
private static boolean isBranch(FunctionIR functionIR, int trueIndex, int falseIndex, int exitIndex) {
Statement branch1 = functionIR.getBlockList().get(trueIndex).getLabelInstruction().getBelongTo();
Statement branch2 = functionIR.getBlockList().get(falseIndex).getLabelInstruction().getBelongTo();
Statement branch3 = functionIR.getBlockList().get(exitIndex).getLabelInstruction().getBelongTo();
return branch1 instanceof IfStatement && branch2 instanceof IfStatement && branch3 instanceof IfStatement
&& branch1 == branch2 && branch2 == branch3;
}
}
|
922edd1e223b989152edc1004d3dbc049fabcf79 | 2,562 | java | Java | mFinance/src/main/java/edu/psu/ist412/mFinance/controllers/HomeController.java | IST412-FA19/mFinanceMaven | 05ef5a6b348a9a11fa5578cab4840bd92035ee02 | [
"MIT"
] | 1 | 2019-11-07T20:18:39.000Z | 2019-11-07T20:18:39.000Z | mFinance/src/main/java/edu/psu/ist412/mFinance/controllers/HomeController.java | IST412-FA19/mFinanceMaven | 05ef5a6b348a9a11fa5578cab4840bd92035ee02 | [
"MIT"
] | 3 | 2019-12-07T23:06:30.000Z | 2019-12-09T03:56:33.000Z | mFinance/src/main/java/edu/psu/ist412/mFinance/controllers/HomeController.java | IST412-FA19/mFinanceGradle | 05ef5a6b348a9a11fa5578cab4840bd92035ee02 | [
"MIT"
] | null | null | null | 35.09589 | 123 | 0.714286 | 994,901 | /*
* 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 edu.psu.ist412.mFinance.controllers;
import edu.psu.ist412.mFinance.dao.ApplicationUserRepository;
import edu.psu.ist412.mFinance.dao.BusinessLoanRepository;
import edu.psu.ist412.mFinance.dao.CarLoanRepository;
import edu.psu.ist412.mFinance.dao.PersonalLoanRepository;
import edu.psu.ist412.mFinance.models.BusinessLoan;
import edu.psu.ist412.mFinance.models.CarLoan;
import edu.psu.ist412.mFinance.models.Loan;
import edu.psu.ist412.mFinance.models.PersonalLoan;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author garre
*/
@Controller
public class HomeController {
@Autowired
ApplicationUserRepository userRepository;
@Autowired
BusinessLoanRepository businessLoanRepository;
@Autowired
CarLoanRepository carLoanRepository;
@Autowired
PersonalLoanRepository personalLoanRepository;
@GetMapping("/home")
public String index() {
return "home";
}
@GetMapping("/loanSummary")
public ModelAndView summary() {
ModelAndView response = new ModelAndView("loanSummary");
String user = ((UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
int userId = userRepository.findByUsername(user).getId();
List<BusinessLoan> businessLoans = businessLoanRepository.findByApplicantAccountId(userId);
List<CarLoan> autoLoans = carLoanRepository.findByApplicantAccountId(userId);
List<PersonalLoan> personalLoans = personalLoanRepository.findByApplicantAccountId(userId);
List<Loan> loans = new ArrayList<>();
businessLoans.stream().forEach((loan) -> loans.add(loan));
autoLoans.stream().forEach((loan) -> loans.add(loan));
personalLoans.stream().forEach((loan) -> loans.add(loan));
response.addObject("loans", loans);
return response;
}
} |
922edd5bbae5e0ff5a0b32d90e0b5ba0959cbc95 | 4,843 | java | Java | src/com/Tests/Model/AccountRelated/AccountTest.java | AP2020Fall/project-team-4 | 424e14fec0b5d3d7c3595bc1b38976e21655ea45 | [
"MIT"
] | 1 | 2021-08-07T13:22:22.000Z | 2021-08-07T13:22:22.000Z | src/com/Tests/Model/AccountRelated/AccountTest.java | AP2020Fall/project-team-4 | 424e14fec0b5d3d7c3595bc1b38976e21655ea45 | [
"MIT"
] | null | null | null | src/com/Tests/Model/AccountRelated/AccountTest.java | AP2020Fall/project-team-4 | 424e14fec0b5d3d7c3595bc1b38976e21655ea45 | [
"MIT"
] | null | null | null | 29.319018 | 99 | 0.627746 | 994,902 | //package Model.AccountRelated;
//
//import org.junit.jupiter.api.AfterEach;
//import org.junit.jupiter.api.BeforeEach;
//import org.junit.jupiter.api.Test;
//
//import java.util.LinkedList;
//
//import static org.junit.jupiter.api.Assertions.*;
//import static org.junit.jupiter.api.Assumptions.assumeTrue;
//
//public class AccountTest {
// @AfterEach
// @BeforeEach
// public void clearAccounts () {
// Account.setAccounts(new LinkedList<>());
// }
//
// @Test
// public void editAccountFirstNameTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("fn", account.getFirstName());
//
// Account.getAccount("testAccUN").editField("first name", "editedFN");
//
// assertEquals("editedFN", account.getFirstName());
// }
//
// @Test
// public void editAccountLastNameTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("ln", account.getLastName());
//
// Account.getAccount("testAccUN").editField("last name", "editedLN");
//
// assertEquals("editedLN", account.getLastName());
// }
//
// @Test
// public void editAccountUsernameTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("testAccUN", account.getUsername());
//
// Account.getAccount("testAccUN").editField("username", "editedUN");
//
// assertEquals("editedUN", account.getUsername());
// }
//
// @Test
// public void editAccountPasswordTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("pw", account.getPassword());
//
// Account.getAccount("testAccUN").editField("password", "editedPW");
//
// assertEquals("editedPW", account.getPassword());
// }
//
// @Test
// public void editAccountEmailTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("ychag@example.com", account.getEmail());
//
// Account.getAccount("testAccUN").editField("email", "hzdkv@example.com");
//
// assertEquals("hzdkv@example.com", account.getEmail());
// }
//
// @Test
// public void editAccountPhoneNumTest () {
// Account.addAccount(Gamer.class, null,
// "fn",
// "ln", "testAccUN",
// "pw", "ychag@example.com", "00011122233", 50);
//
// Account account = Account.getAccount("testAccUN");
//
// assertEquals("00011122233", account.getPhoneNum());
//
// Account.getAccount("testAccUN").editField("phone num", "33322211100");
//
// assertEquals("33322211100", account.getPhoneNum());
// }
//
// @Test
// public void isEmailOkTest () {
// assertAll("checking is email ok",
// () -> assertFalse(Account.isEmailOK("")),
// () -> assertTrue(Account.isEmailOK("lyhxr@example.com")),
// () -> assertTrue(Account.isEmailOK("hzdkv@example.com")),
// () -> assertTrue(Account.isEmailOK("upchh@example.com")),
// () -> assertTrue(Account.isEmailOK("envkt@example.com"))
// );
// }
//
// @Test
// public void isPhoneNumOkTest () {
// assertAll("checking is email ok",
// () -> assertFalse(Account.isPhoneNumOK("")),
// () -> assertTrue(Account.isPhoneNumOK("00011122233")),
// () -> assertFalse(Account.isPhoneNumOK("000111222332")),
// () -> assertTrue(Account.isPhoneNumOK("9999922233")),
// () -> assertFalse(Account.isPhoneNumOK("999992233"))
// );
// }
//
// @Test
// public void addAccountTest () {
// assertAll("add account tests",
// () -> {
// Account.addAccount(Admin.class, null, "1", "1", "1", "1", "upchh@example.com", "00011122233", 25);
// assertTrue(Account.accountExists("1"));
// assertTrue(Admin.adminHasBeenCreated());
// assertEquals("1", Admin.getAdmin().getUsername());
// assertEquals("1", Account.getAccount("1").getUsername());
// },
// () -> {
// Account.addAccount(Gamer.class, null, "2", "2", "2", "2", "upchh@example.com", "00011122233", 2);
// assertTrue(Account.accountExists("2"));
// assertEquals("2", Account.getAccount("2").getUsername());
// }
// );
// }
//
// @Test
// public void removeAccountTest () {
// Account.addAccount(Gamer.class, null, "1", "1", "1", "1", "upchh@example.com", "00011122233", 1);
// assumeTrue(Account.accountExists("1"));
// Account.removeAccount("1");
// assertFalse(Account.accountExists("1"));
// }
//}
|
922edda271252455ed64632516e359bca67935f7 | 3,424 | java | Java | src/main/java/com/example/algamoney/api/resource/CategoriaResource.java | olavowilke/algamoney-api | cb5384d7376fbab6829f605a3630300c3692eda6 | [
"MIT"
] | null | null | null | src/main/java/com/example/algamoney/api/resource/CategoriaResource.java | olavowilke/algamoney-api | cb5384d7376fbab6829f605a3630300c3692eda6 | [
"MIT"
] | null | null | null | src/main/java/com/example/algamoney/api/resource/CategoriaResource.java | olavowilke/algamoney-api | cb5384d7376fbab6829f605a3630300c3692eda6 | [
"MIT"
] | null | null | null | 36.042105 | 124 | 0.745619 | 994,903 | package com.example.algamoney.api.resource;
import com.example.algamoney.api.event.RecursoCriadoEvent;
import com.example.algamoney.api.model.Categoria;
import com.example.algamoney.api.model.Pessoa;
import com.example.algamoney.api.repository.CategoriaRepository;
import com.example.algamoney.api.service.CategoriaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@RestController
@RequestMapping("/categorias")
public class CategoriaResource {
//Atributos
@Autowired
private CategoriaRepository categoriaRepository;
@Autowired
private CategoriaService categoriaService;
//Métodos
@GetMapping
public List<Categoria> listar(){
return categoriaRepository.findAll();
}
// @GetMapping
// public ResponseEntity<?> listar(){
// List<Categoria> categorias = categoriaRepository.findAll();
// return !categorias.isEmpty() ? ResponseEntity.ok(categorias) : ResponseEntity.noContent().build();
// }
@Autowired
private ApplicationEventPublisher publisher;
//^Fará a publicação do evento
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Categoria> criar(@Valid @RequestBody Categoria categoria, HttpServletResponse response){
Categoria categoriaSalva = categoriaRepository.save(categoria);
publisher.publishEvent(new RecursoCriadoEvent(this, response, categoriaSalva.getId()));
return ResponseEntity.status(HttpStatus.CREATED).body(categoriaSalva);
}
// @GetMapping("/{id}")
// public Optional<Categoria> buscarPeloId(@PathVariable UUID id){
// return categoriaRepository.findById(id);
// }
@GetMapping("/{id}")
public ResponseEntity<?> buscarPeloId(@PathVariable UUID id){
Optional<Categoria> categoriaOptional = categoriaRepository.findById(id);
return categoriaOptional.isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(categoriaOptional.get());
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void remover(@PathVariable UUID id) {
categoriaRepository.deleteById(id);
}
@PutMapping("/{id}")
public ResponseEntity<Categoria> atualizar(@PathVariable UUID id, @Valid @RequestBody Categoria categoria) {
Categoria categoriaEntity = categoriaService.atualizar(id, categoria);
return ResponseEntity.ok(categoriaEntity);
}
}
// @RestController É um controlador REST, seu retorno será facilitado
// @RequestMapping Faz o mapeamento da requisição.
// @Autowired Injeção: Irá encontrar automaticamente uma implementação para o tipo especificado
// @GetMapping
// Faz o mapeamento do GET para URL /categorias
// É possível incrementar o GetMapping.
// Exemplo: @GetMapping/outros (irá usar o método abaixo da descrição.
// @PostMapping Faz o mapeamento do POST.
|
922edebc68d8a39f3ee6772f653a05370b4f0cba | 1,319 | java | Java | src/main/de/hsmainz/cs/semgis/arqextension/linestring/attribute/IsValidTrajectory.java | lisha992610/jena-geo | c674d9b6bed762b6fd59163eb4b06120dfa8e10c | [
"Apache-2.0"
] | 1 | 2021-05-05T06:35:22.000Z | 2021-05-05T06:35:22.000Z | src/main/de/hsmainz/cs/semgis/arqextension/linestring/attribute/IsValidTrajectory.java | lisha992610/jena-geo | c674d9b6bed762b6fd59163eb4b06120dfa8e10c | [
"Apache-2.0"
] | 3 | 2020-11-07T22:48:31.000Z | 2021-05-04T09:41:34.000Z | src/main/de/hsmainz/cs/semgis/arqextension/linestring/attribute/IsValidTrajectory.java | lisha992610/jena-geo | c674d9b6bed762b6fd59163eb4b06120dfa8e10c | [
"Apache-2.0"
] | 4 | 2021-05-06T03:14:40.000Z | 2022-01-13T07:35:01.000Z | 30.674419 | 96 | 0.720243 | 994,904 | package de.hsmainz.cs.semgis.arqextension.linestring.attribute;
import org.apache.jena.datatypes.DatatypeFormatException;
import org.apache.jena.sparql.expr.ExprEvalException;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.function.FunctionBase1;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import io.github.galbiston.geosparql_jena.implementation.GeometryWrapper;
/**
* Returns true if the geometry is a valid trajectory
*
*/
public class IsValidTrajectory extends FunctionBase1 {
@Override
public NodeValue exec(NodeValue arg0) {
try {
GeometryWrapper geometry = GeometryWrapper.extract(arg0);
Geometry geom = geometry.getParsingGeometry();
if (geom instanceof LineString || geom.getGeometryType().equalsIgnoreCase("LINESTRING M")) {
Double lastM = Double.MIN_VALUE;
for (Coordinate coord : geom.getCoordinates()) {
if (Double.isNaN(coord.getM()) || coord.getM() <= lastM) {
return NodeValue.FALSE;
} else {
lastM = coord.getM();
}
}
return NodeValue.TRUE;
}
return NodeValue.FALSE;
} catch (DatatypeFormatException ex) {
throw new ExprEvalException(ex.getMessage(), ex);
}
}
}
|
922edf349e2b71a5fd366d91401b63383199adf7 | 751 | java | Java | morph-r2rml-rdb/src/main/scala/es/upm/fi/dia/oeg/morph/r2rml/rdb/yaml/Resource.java | jatoledo/morph-rdb | 8ac243da58c8b47db316042cdbd9259f39236a96 | [
"Apache-2.0"
] | null | null | null | morph-r2rml-rdb/src/main/scala/es/upm/fi/dia/oeg/morph/r2rml/rdb/yaml/Resource.java | jatoledo/morph-rdb | 8ac243da58c8b47db316042cdbd9259f39236a96 | [
"Apache-2.0"
] | null | null | null | morph-r2rml-rdb/src/main/scala/es/upm/fi/dia/oeg/morph/r2rml/rdb/yaml/Resource.java | jatoledo/morph-rdb | 8ac243da58c8b47db316042cdbd9259f39236a96 | [
"Apache-2.0"
] | null | null | null | 19.25641 | 57 | 0.728362 | 994,905 | package es.upm.fi.dia.oeg.morph.r2rml.rdb.yaml;
public class Resource {
private String driverClassName;
private String url;
private String username;
private String password;
// getters and setters
Resource(){
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
922edf3dc07fb8ce483441e04f2ea2d684fef6f4 | 2,816 | java | Java | src/main/java/duelistmod/cards/pools/machine/PsychicShockwave.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 3 | 2019-06-20T08:52:04.000Z | 2020-06-17T19:32:05.000Z | src/main/java/duelistmod/cards/pools/machine/PsychicShockwave.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 7 | 2019-04-22T12:26:08.000Z | 2021-01-18T02:45:58.000Z | src/main/java/duelistmod/cards/pools/machine/PsychicShockwave.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 2 | 2019-12-06T14:30:34.000Z | 2020-03-29T15:43:02.000Z | 32 | 97 | 0.712003 | 994,906 | package duelistmod.cards.pools.machine;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import duelistmod.DuelistMod;
import duelistmod.abstracts.DuelistCard;
import duelistmod.patches.AbstractCardEnum;
import duelistmod.variables.Tags;
public class PsychicShockwave extends DuelistCard
{
// TEXT DECLARATION
public static final String ID = DuelistMod.makeID("PsychicShockwave");
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String IMG = DuelistMod.makeCardPath("PsychicShockwave.png");
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION;
// /TEXT DECLARATION/
// STAT DECLARATION
private static final CardRarity RARITY = CardRarity.UNCOMMON;
private static final CardTarget TARGET = CardTarget.ALL_ENEMY;
private static final CardType TYPE = CardType.ATTACK;
public static final CardColor COLOR = AbstractCardEnum.DUELIST_TRAPS;
private static final int COST = 2;
// /STAT DECLARATION/
public PsychicShockwave()
{
super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET);
this.originalName = this.name;
this.baseDamage = this.damage = 15;
this.baseMagicNumber = this.magicNumber = 3;
this.misc = 0;
this.tags.add(Tags.TRAP);
this.isMultiDamage = true;
}
@Override
public void use(AbstractPlayer p, AbstractMonster m)
{
normalMultidmg();
slowAllEnemies(this.magicNumber);
}
// Upgraded stats.
@Override
public void upgrade()
{
if (!upgraded)
{
if (this.timesUpgraded > 0) { this.upgradeName(NAME + "+" + this.timesUpgraded); }
else { this.upgradeName(NAME + "+"); }
this.upgradeDamage(3);
this.upgradeMagicNumber(1);
this.rawDescription = UPGRADE_DESCRIPTION;
this.initializeDescription();
}
}
@Override
public void onTribute(DuelistCard tributingCard)
{
}
@Override
public void onResummon(int summons)
{
}
@Override
public String getID() { return ID; }
@Override
public AbstractCard makeCopy() { return new PsychicShockwave(); }
public void summonThis(int summons, DuelistCard c, int var) {}
public void summonThis(int summons, DuelistCard c, int var, AbstractMonster m) {}
public void optionSelected(AbstractPlayer arg0, AbstractMonster arg1, int arg2) {}
} |
922edf7e23f0dfc77479049cb16e3181124e96a9 | 1,304 | java | Java | opensrp-chw/src/main/java/org/smartregister/chw/model/DefaultNavigationModelFlv.java | BlueCodeSystems/opensrp-client-chw | 7866048f154b64e1c3ecc326769be95465e6f45e | [
"Apache-2.0"
] | 2 | 2019-03-20T08:43:34.000Z | 2019-12-13T17:17:50.000Z | opensrp-chw/src/main/java/org/smartregister/chw/model/DefaultNavigationModelFlv.java | BlueCodeSystems/opensrp-client-chw | 7866048f154b64e1c3ecc326769be95465e6f45e | [
"Apache-2.0"
] | 915 | 2019-03-18T08:42:59.000Z | 2021-04-23T08:57:36.000Z | opensrp-chw/src/main/java/org/smartregister/chw/model/DefaultNavigationModelFlv.java | Afro-Don-San/opensrp-client-chw | 53665b561c049572ed05e753c44b511416c3201f | [
"Apache-2.0"
] | 9 | 2019-03-15T13:20:55.000Z | 2021-03-01T06:44:39.000Z | 44.965517 | 187 | 0.775307 | 994,907 | package org.smartregister.chw.model;
import org.smartregister.chw.R;
import org.smartregister.chw.core.model.NavigationModel;
import org.smartregister.chw.core.model.NavigationOption;
import org.smartregister.chw.util.Constants;
import java.util.ArrayList;
import java.util.List;
public abstract class DefaultNavigationModelFlv implements NavigationModel.Flavor {
private List<NavigationOption> navigationOptions = new ArrayList<>();
@Override
public List<NavigationOption> getNavigationItems() {
if (navigationOptions.size() == 0) {
navigationOptions.add(new NavigationOption(R.mipmap.sidemenu_families, R.mipmap.sidemenu_families_active, R.string.menu_all_families, Constants.DrawerMenu.ALL_FAMILIES, 0));
navigationOptions.add(new NavigationOption(R.mipmap.sidemenu_anc, R.mipmap.sidemenu_anc_active, R.string.menu_anc, Constants.DrawerMenu.ANC, 0));
navigationOptions.add(new NavigationOption(R.mipmap.sidemenu_pnc, R.mipmap.sidemenu_pnc_active, R.string.menu_pnc, Constants.DrawerMenu.PNC, 0));
navigationOptions.add(new NavigationOption(R.mipmap.sidemenu_children, R.mipmap.sidemenu_children_active, R.string.menu_child_clients, Constants.DrawerMenu.CHILD_CLIENTS, 0));
}
return navigationOptions;
}
}
|
922ee0c4004577039823c0c1fbdcaf87ada0778f | 2,427 | java | Java | src/java/com/netflix/ice/common/WorkBucketDataConfig.java | rudderlabs/ice | c396c9ac84c1345abd1282846b5563fcfb02119d | [
"Apache-2.0"
] | null | null | null | src/java/com/netflix/ice/common/WorkBucketDataConfig.java | rudderlabs/ice | c396c9ac84c1345abd1282846b5563fcfb02119d | [
"Apache-2.0"
] | null | null | null | src/java/com/netflix/ice/common/WorkBucketDataConfig.java | rudderlabs/ice | c396c9ac84c1345abd1282846b5563fcfb02119d | [
"Apache-2.0"
] | null | null | null | 27.579545 | 127 | 0.718583 | 994,908 | /*
*
* Copyright 2013 Netflix, 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.netflix.ice.common;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.netflix.ice.common.Config.TagCoverage;
import com.netflix.ice.tag.Account;
/**
* Work bucket data-dependent configuration items used by the reader
*/
public class WorkBucketDataConfig {
private final String startMonth;
private final List<String> userTags;
private final List<Account> accounts;
private final Map<String, List<String>> zones;
private final TagCoverage tagCoverage;
private final Map<String, Map<String, TagConfig>> tagConfigs;
public WorkBucketDataConfig(String startMonth, List<Account> accounts, Map<String, List<String>> zones, List<String> userTags,
TagCoverage tagCoverage, Map<String, Map<String, TagConfig>> tagConfigs) {
this.startMonth = startMonth;
this.accounts = accounts;
this.zones = zones;
this.userTags = userTags;
this.tagCoverage = tagCoverage;
this.tagConfigs = tagConfigs;
}
public WorkBucketDataConfig(String json) {
Gson gson = new Gson();
WorkBucketDataConfig c = gson.fromJson(json, this.getClass());
this.startMonth = c.startMonth;
this.accounts = c.accounts;
this.zones = c.zones;
this.userTags = c.userTags;
this.tagCoverage = c.tagCoverage;
this.tagConfigs = c.tagConfigs;
}
public String getStartMonth() {
return startMonth;
}
public List<Account> getAccounts() {
return accounts;
}
public Map<String, List<String>> getZones() {
return zones;
}
public List<String> getUserTags() {
return userTags;
}
public TagCoverage getTagCoverage() {
return tagCoverage;
}
public Map<String, Map<String, TagConfig>> getTagConfigs() {
return tagConfigs;
}
public String toJSON() {
Gson gson = new Gson();
return gson.toJson(this);
}
}
|
922ee18a282ab82b93db4ef5fc4db4d8137045cc | 982 | java | Java | map-fragment/src/com/bignerdranch/android/mapfragment/MapFragment.java | bignerdranch/map-fragment | 08be56da073fbb8ed49bee16c5993536a1444244 | [
"Apache-2.0"
] | null | null | null | map-fragment/src/com/bignerdranch/android/mapfragment/MapFragment.java | bignerdranch/map-fragment | 08be56da073fbb8ed49bee16c5993536a1444244 | [
"Apache-2.0"
] | null | null | null | map-fragment/src/com/bignerdranch/android/mapfragment/MapFragment.java | bignerdranch/map-fragment | 08be56da073fbb8ed49bee16c5993536a1444244 | [
"Apache-2.0"
] | null | null | null | 30.6875 | 75 | 0.729124 | 994,909 | /*
* Copyright (C) 2012 Big Nerd Ranch, Inc.
* - Updated to use the library project.
*
* Based on previous work:
* Copyright (C) 2011 Ievgenii Nazaruk
*
* 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.bignerdranch.android.mapfragment;
import android.app.Activity;
public class MapFragment extends ActivityHostFragment {
@Override
protected Class<? extends Activity> getActivityClass() {
return SimpleMapActivity.class;
}
}
|
922ee1b001efe2d4be30ab2f3637817e989dbf03 | 1,538 | java | Java | src/scientigrapher/pdfs/MainExtractPDF.java | lvanhee/scientigrapher | 06b1ad2286cbc231228338f7a2586f22f787747b | [
"MIT"
] | null | null | null | src/scientigrapher/pdfs/MainExtractPDF.java | lvanhee/scientigrapher | 06b1ad2286cbc231228338f7a2586f22f787747b | [
"MIT"
] | null | null | null | src/scientigrapher/pdfs/MainExtractPDF.java | lvanhee/scientigrapher | 06b1ad2286cbc231228338f7a2586f22f787747b | [
"MIT"
] | null | null | null | 26.517241 | 91 | 0.696359 | 994,910 | package scientigrapher.pdfs;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.pdfbox.io.RandomAccessRead;
public class MainExtractPDF {
public static void main(String args[]) throws IOException {
String fileName = "data/thesis.pdf";
String outOfFile = PdfReader.getStringContentsOutOfFile(new File(fileName));
System.out.println(outOfFile);
}
private static Map<String, Map<String, Integer>> bigramAssociationCounter(String string) {
Map<String, Map<String, Integer>> map = new HashMap<>();
String[] t = string.split(" ");
String prev = ".";
for(int i = 0 ; i < t.length ; i++)
{
String current = t[i].toLowerCase();
if(!map.containsKey(prev)) map.put(prev, new HashMap<>());
if(!map.get(prev).containsKey(current))map.get(prev).put(current, 0);
map.get(prev).put(current, map.get(prev).get(current)+1);
prev = current;
}
return map;
}
private static String removePunctuation(String string) {
return string
.replaceAll("\n", "")
.replaceAll("\\)","").replaceAll(",", "");
}
private static String getStringContentsOutOfFolder(String folderName) {
File folder = new File(folderName);
return Arrays.asList(folder.listFiles()).stream().map(x->{
return PdfReader.getStringContentsOutOfFile(x);
}).reduce("", (x,y)-> x+"\n\n"+y);
}
}
|
922ee1c9e667a98eedd60cc5a4b53177b79bea72 | 4,448 | java | Java | src/main/java/net/dodogang/crumbs/block/PebblesBlock.java | linzexin022/crumbs | 30009340398e67039fddb0d5fd5d1916121fd2c9 | [
"MIT"
] | null | null | null | src/main/java/net/dodogang/crumbs/block/PebblesBlock.java | linzexin022/crumbs | 30009340398e67039fddb0d5fd5d1916121fd2c9 | [
"MIT"
] | null | null | null | src/main/java/net/dodogang/crumbs/block/PebblesBlock.java | linzexin022/crumbs | 30009340398e67039fddb0d5fd5d1916121fd2c9 | [
"MIT"
] | null | null | null | 41.570093 | 122 | 0.706835 | 994,911 | package net.dodogang.crumbs.block;
import net.dodogang.crumbs.state.property.CrumbsProperties;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.ShapeContext;
import net.minecraft.block.Waterloggable;
import net.minecraft.entity.ai.pathing.NavigationType;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.IntProperty;
import net.minecraft.state.property.Properties;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.BlockView;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.WorldView;
public class PebblesBlock extends Block implements Waterloggable {
public static final IntProperty PEBBLES = CrumbsProperties.PEBBLES;
public static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED;
protected static final VoxelShape ONE_PEBBLE_SHAPE = Block.createCuboidShape(3.0D, 0.0D, 3.0D, 13.0D, 2.0D, 13.0D);
protected static final VoxelShape TWO_PEBBLES_SHAPE = Block.createCuboidShape(3.0D, 0.0D, 3.0D, 13.0D, 3.0D, 13.0D);
protected static final VoxelShape THREE_PEBBLES_SHAPE = Block.createCuboidShape(1.0D, 0.0D, 1.0D, 15.0D, 6.0D, 15.0D);
protected static final VoxelShape FOUR_PEBBLES_SHAPE = Block.createCuboidShape(1.0D, 0.0D, 1.0D, 15.0D, 10.0D, 15.0D);
public PebblesBlock(AbstractBlock.Settings settings) {
super(settings);
this.setDefaultState(this.stateManager.getDefaultState().with(PEBBLES, 1));
}
@Override
public BlockState getPlacementState(ItemPlacementContext context) {
BlockState blockState = context.getWorld().getBlockState(context.getBlockPos());
if (blockState.isOf(this)) {
return blockState.with(PEBBLES, Math.min(4, (Integer) blockState.get(PEBBLES) + 1));
} else {
FluidState fluidState = context.getWorld().getFluidState(context.getBlockPos());
return super.getPlacementState(context).with(WATERLOGGED, fluidState.getFluid() == Fluids.WATER);
}
}
@Override
public boolean canPlaceAt(BlockState state, WorldView world, BlockPos pos) {
pos = pos.down();
return !world.getBlockState(pos).getCollisionShape(world, pos).getFace(Direction.UP).isEmpty();
}
@Override
public BlockState getStateForNeighborUpdate(BlockState state, Direction direction, BlockState newState,
WorldAccess world, BlockPos pos, BlockPos posFrom) {
if (!state.canPlaceAt(world, pos)) {
return Blocks.AIR.getDefaultState();
} else {
if ((Boolean) state.get(WATERLOGGED)) {
world.getFluidTickScheduler().schedule(pos, Fluids.WATER, Fluids.WATER.getTickRate(world));
}
return super.getStateForNeighborUpdate(state, direction, newState, world, pos, posFrom);
}
}
@Override
public boolean canReplace(BlockState state, ItemPlacementContext context) {
return context.getStack().getItem() == this.asItem() && (Integer) state.get(PEBBLES) < 4
? true
: super.canReplace(state, context);
}
@Override
public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
switch ((Integer) state.get(PEBBLES)) {
case 1:
default:
return ONE_PEBBLE_SHAPE;
case 2:
return TWO_PEBBLES_SHAPE;
case 3:
return THREE_PEBBLES_SHAPE;
case 4:
return FOUR_PEBBLES_SHAPE;
}
}
@Override
public FluidState getFluidState(BlockState state) {
return (Boolean) state.get(WATERLOGGED) ? Fluids.WATER.getStill(false) : super.getFluidState(state);
}
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
super.appendProperties(builder);
builder.add(PEBBLES, WATERLOGGED);
}
@Override
public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) {
return false;
}
}
|
922ee2f5e6d4ea98205d52d8755d0b1bbc185ea4 | 12,833 | java | Java | EclipseTestWorkspace/net.oschina.app/src/net/oschina/app/ui/UserFavorite.java | secure-software-engineering/TS4J | ea3d8da3c656a7f93b2ae8889a360b843df00af9 | [
"BSD-2-Clause"
] | null | null | null | EclipseTestWorkspace/net.oschina.app/src/net/oschina/app/ui/UserFavorite.java | secure-software-engineering/TS4J | ea3d8da3c656a7f93b2ae8889a360b843df00af9 | [
"BSD-2-Clause"
] | null | null | null | EclipseTestWorkspace/net.oschina.app/src/net/oschina/app/ui/UserFavorite.java | secure-software-engineering/TS4J | ea3d8da3c656a7f93b2ae8889a360b843df00af9 | [
"BSD-2-Clause"
] | null | null | null | 34.967302 | 127 | 0.685342 | 994,912 | package net.oschina.app.ui;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewFavoriteAdapter;
import net.oschina.app.bean.FavoriteList;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.Result;
import net.oschina.app.bean.FavoriteList.Favorite;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.PullToRefreshListView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* 用户收藏
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-3-21
*/
public class UserFavorite extends BaseActivity {
private ImageView mBack;
private ProgressBar mProgressbar;
private Button favorite_catalog_software;
private Button favorite_catalog_post;
private Button favorite_catalog_code;
private Button favorite_catalog_blog;
private Button favorite_catalog_news;
private PullToRefreshListView mlvFavorite;
private ListViewFavoriteAdapter lvFavoriteAdapter;
private List<Favorite> lvFavoriteData = new ArrayList<Favorite>();
private View lvFavorite_footer;
private TextView lvFavorite_foot_more;
private ProgressBar lvFavorite_foot_progress;
private Handler mFavoriteHandler;
private int lvSumData;
private int curFavoriteCatalog;
private int curLvDataState;
private final static int DATA_LOAD_ING = 0x001;
private final static int DATA_LOAD_COMPLETE = 0x002;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_favorite);
this.initView();
this.initData();
}
/**
* 头部按钮展示
* @param type
*/
private void headButtonSwitch(int type) {
switch (type) {
case DATA_LOAD_ING:
mProgressbar.setVisibility(View.VISIBLE);
break;
case DATA_LOAD_COMPLETE:
mProgressbar.setVisibility(View.GONE);
break;
}
}
//初始化视图控件
private void initView()
{
mBack = (ImageView)findViewById(R.id.favorite_head_back);
mBack.setOnClickListener(UIHelper.finish(this));
mProgressbar = (ProgressBar)findViewById(R.id.favorite_head_progress);
favorite_catalog_software = (Button)findViewById(R.id.favorite_catalog_software);
favorite_catalog_post = (Button)findViewById(R.id.favorite_catalog_post);
favorite_catalog_code = (Button)findViewById(R.id.favorite_catalog_code);
favorite_catalog_blog = (Button)findViewById(R.id.favorite_catalog_blog);
favorite_catalog_news = (Button)findViewById(R.id.favorite_catalog_news);
favorite_catalog_software.setOnClickListener(this.favoriteBtnClick(favorite_catalog_software,FavoriteList.TYPE_SOFTWARE));
favorite_catalog_post.setOnClickListener(this.favoriteBtnClick(favorite_catalog_post,FavoriteList.TYPE_POST));
favorite_catalog_code.setOnClickListener(this.favoriteBtnClick(favorite_catalog_code,FavoriteList.TYPE_CODE));
favorite_catalog_blog.setOnClickListener(this.favoriteBtnClick(favorite_catalog_blog,FavoriteList.TYPE_BLOG));
favorite_catalog_news.setOnClickListener(this.favoriteBtnClick(favorite_catalog_news,FavoriteList.TYPE_NEWS));
favorite_catalog_software.setEnabled(false);
curFavoriteCatalog = FavoriteList.TYPE_SOFTWARE;
lvFavorite_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
lvFavorite_foot_more = (TextView)lvFavorite_footer.findViewById(R.id.listview_foot_more);
lvFavorite_foot_progress = (ProgressBar)lvFavorite_footer.findViewById(R.id.listview_foot_progress);
lvFavoriteAdapter = new ListViewFavoriteAdapter(this, lvFavoriteData, R.layout.favorite_listitem);
mlvFavorite = (PullToRefreshListView)findViewById(R.id.favorite_listview);
mlvFavorite.addFooterView(lvFavorite_footer);//添加底部视图 必须在setAdapter前
mlvFavorite.setAdapter(lvFavoriteAdapter);
mlvFavorite.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击头部、底部栏无效
if(position == 0 || view == lvFavorite_footer) return;
Favorite fav = null;
//判断是否是TextView
if(view instanceof TextView){
fav = (Favorite)view.getTag();
}else{
TextView title = (TextView)view.findViewById(R.id.favorite_listitem_title);
fav = (Favorite)title.getTag();
}
if(fav == null) return;
//跳转
UIHelper.showUrlRedirect(view.getContext(), fav.url);
}
});
mlvFavorite.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
mlvFavorite.onScrollStateChanged(view, scrollState);
//数据为空--不用继续下面代码了
if(lvFavoriteData.size() == 0) return;
//判断是否滚动到底部
boolean scrollEnd = false;
try {
if(view.getPositionForView(lvFavorite_footer) == view.getLastVisiblePosition())
scrollEnd = true;
} catch (Exception e) {
scrollEnd = false;
}
if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
{
mlvFavorite.setTag(UIHelper.LISTVIEW_DATA_LOADING);
lvFavorite_foot_more.setText(R.string.load_ing);
lvFavorite_foot_progress.setVisibility(View.VISIBLE);
//当前pageIndex
int pageIndex = lvSumData/20;
loadLvFavoriteData(curFavoriteCatalog, pageIndex, mFavoriteHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
}
}
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
mlvFavorite.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
});
mlvFavorite.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//点击头部、底部栏无效
if(position == 0 || view == lvFavorite_footer) return false;
Favorite _fav = null;
//判断是否是TextView
if(view instanceof TextView){
_fav = (Favorite)view.getTag();
}else{
TextView title = (TextView)view.findViewById(R.id.favorite_listitem_title);
_fav = (Favorite)title.getTag();
}
if(_fav == null) return false;
final Favorite fav = _fav;
final AppContext ac = (AppContext)getApplication();
//操作--删除
final int uid = ac.getLoginUid();
final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(msg.what == 1){
Result res = (Result)msg.obj;
if(res.OK()){
lvFavoriteData.remove(fav);
lvFavoriteAdapter.notifyDataSetChanged();
}
UIHelper.ToastMessage(UserFavorite.this, res.getErrorMessage());
}else{
((AppException)msg.obj).makeToast(UserFavorite.this);
}
}
};
final Thread thread = new Thread(){
public void run() {
Message msg = new Message();
try {
Result res = ac.delFavorite(uid, fav.objid, fav.type);
msg.what = 1;
msg.obj = res;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
handler.sendMessage(msg);
}
};
UIHelper.showFavoriteOptionDialog(UserFavorite.this, thread);
return true;
}
});
mlvFavorite.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
public void onRefresh() {
loadLvFavoriteData(curFavoriteCatalog, 0, mFavoriteHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
}
});
}
//初始化控件数据
private void initData()
{
mFavoriteHandler = new Handler()
{
public void handleMessage(Message msg) {
headButtonSwitch(DATA_LOAD_COMPLETE);
if(msg.what >= 0){
FavoriteList list = (FavoriteList)msg.obj;
Notice notice = list.getNotice();
//处理listview数据
switch (msg.arg1) {
case UIHelper.LISTVIEW_ACTION_INIT:
case UIHelper.LISTVIEW_ACTION_REFRESH:
case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
lvSumData = msg.what;
lvFavoriteData.clear();//先清除原有数据
lvFavoriteData.addAll(list.getFavoritelist());
break;
case UIHelper.LISTVIEW_ACTION_SCROLL:
lvSumData += msg.what;
if(lvFavoriteData.size() > 0){
for(Favorite fav1 : list.getFavoritelist()){
boolean b = false;
for(Favorite fav2 : lvFavoriteData){
if(fav1.objid == fav2.objid){
b = true;
break;
}
}
if(!b) lvFavoriteData.add(fav1);
}
}else{
lvFavoriteData.addAll(list.getFavoritelist());
}
break;
}
if(msg.what < 20){
curLvDataState = UIHelper.LISTVIEW_DATA_FULL;
lvFavoriteAdapter.notifyDataSetChanged();
lvFavorite_foot_more.setText(R.string.load_full);
}else if(msg.what == 20){
curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
lvFavoriteAdapter.notifyDataSetChanged();
lvFavorite_foot_more.setText(R.string.load_more);
}
//发送通知广播
if(notice != null){
UIHelper.sendBroadCast(UserFavorite.this, notice);
}
}
else if(msg.what == -1){
//有异常--显示加载出错 & 弹出错误消息
curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
lvFavorite_foot_more.setText(R.string.load_error);
((AppException)msg.obj).makeToast(UserFavorite.this);
}
if(lvFavoriteData.size()==0){
curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY;
lvFavorite_foot_more.setText(R.string.load_empty);
}
lvFavorite_foot_progress.setVisibility(View.GONE);
if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
mlvFavorite.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
mlvFavorite.setSelection(0);
}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
mlvFavorite.onRefreshComplete();
mlvFavorite.setSelection(0);
}
}
};
this.loadLvFavoriteData(curFavoriteCatalog,0,mFavoriteHandler,UIHelper.LISTVIEW_ACTION_INIT);
}
/**
* 线程加载收藏数据
* @param type 0:全部收藏 1:软件 2:话题 3:博客 4:新闻 5:代码
* @param pageIndex 当前页数
* @param handler 处理器
* @param action 动作标识
*/
private void loadLvFavoriteData(final int type,final int pageIndex,final Handler handler,final int action){
headButtonSwitch(DATA_LOAD_ING);
new Thread(){
public void run() {
Message msg = new Message();
boolean isRefresh = false;
if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
isRefresh = true;
try {
FavoriteList favoriteList = ((AppContext)getApplication()).getFavoriteList(type, pageIndex, isRefresh);
msg.what = favoriteList.getPageSize();
msg.obj = favoriteList;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
msg.arg1 = action;//告知handler当前action
if(curFavoriteCatalog == type)
handler.sendMessage(msg);
}
}.start();
}
private View.OnClickListener favoriteBtnClick(final Button btn,final int catalog){
return new View.OnClickListener() {
public void onClick(View v) {
if(btn == favorite_catalog_blog)
favorite_catalog_blog.setEnabled(false);
else
favorite_catalog_blog.setEnabled(true);
if(btn == favorite_catalog_code)
favorite_catalog_code.setEnabled(false);
else
favorite_catalog_code.setEnabled(true);
if(btn == favorite_catalog_news)
favorite_catalog_news.setEnabled(false);
else
favorite_catalog_news.setEnabled(true);
if(btn == favorite_catalog_post)
favorite_catalog_post.setEnabled(false);
else
favorite_catalog_post.setEnabled(true);
if(btn == favorite_catalog_software)
favorite_catalog_software.setEnabled(false);
else
favorite_catalog_software.setEnabled(true);
lvFavorite_foot_more.setText(R.string.load_more);
lvFavorite_foot_progress.setVisibility(View.GONE);
curFavoriteCatalog = catalog;
loadLvFavoriteData(curFavoriteCatalog, 0, mFavoriteHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
}
};
}
}
|
922ee358962e0fec58dad0a9ff7830ddd963b08f | 555 | java | Java | src/main/java/tk/mybatis/springboot/mapper/UpStreamInstanceMapper.java | goodguytt01/Power-GR | 385266e877cf80bf68a0bd14d3884ac5659d36e1 | [
"Apache-2.0"
] | 1 | 2020-10-31T09:05:09.000Z | 2020-10-31T09:05:09.000Z | src/main/java/tk/mybatis/springboot/mapper/UpStreamInstanceMapper.java | goodguytt01/Power-GR | 385266e877cf80bf68a0bd14d3884ac5659d36e1 | [
"Apache-2.0"
] | null | null | null | src/main/java/tk/mybatis/springboot/mapper/UpStreamInstanceMapper.java | goodguytt01/Power-GR | 385266e877cf80bf68a0bd14d3884ac5659d36e1 | [
"Apache-2.0"
] | null | null | null | 29.210526 | 62 | 0.803604 | 994,913 | package tk.mybatis.springboot.mapper;
import tk.mybatis.springboot.model.Upstream;
import tk.mybatis.springboot.model.UpstreamInstance;
import java.util.List;
public interface UpStreamInstanceMapper {
int insert(UpstreamInstance upstream);
List<UpstreamInstance> getList(UpstreamInstance instance);
UpstreamInstance getUrl(UpstreamInstance upstream);
int updateUpStream(UpstreamInstance upstream);
int deleteUpStream(UpstreamInstance upstream);
int enableOrDisable(UpstreamInstance upstream);
Upstream getById(Long id);
}
|
922ee406c34286e9b963269f2ee562e686a865e6 | 3,072 | java | Java | webcommon/html.knockout/test/unit/src/org/netbeans/modules/html/knockout/KOModelTest.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | webcommon/html.knockout/test/unit/src/org/netbeans/modules/html/knockout/KOModelTest.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | webcommon/html.knockout/test/unit/src/org/netbeans/modules/html/knockout/KOModelTest.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 39.896104 | 104 | 0.693685 | 994,914 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.html.knockout;
import org.netbeans.modules.html.knockout.model.KOModel;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.csl.api.test.CslTestBase;
import org.netbeans.modules.html.editor.api.gsf.HtmlParserResult;
import org.netbeans.modules.html.editor.lib.api.elements.Attribute;
import org.netbeans.modules.parsing.api.ParserManager;
import org.netbeans.modules.parsing.api.ResultIterator;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.modules.parsing.api.UserTask;
import org.netbeans.modules.parsing.spi.ParseException;
import org.netbeans.modules.web.common.api.WebUtils;
/**
*
* @author marekfukala
*/
public class KOModelTest extends CslTestBase {
public KOModelTest(String name) {
super(name);
}
public void testBasic() {
KOModel model = createModel("<div data-bind=\"text: name\"></div>");
Collection<Attribute> bindings = model.getBindings();
assertNotNull(bindings);
assertEquals(1, bindings.size());
Attribute a = bindings.iterator().next();
assertEquals("text: name", a.unquotedValue().toString());
assertTrue(model.containsKnockout());
}
private KOModel createModel(String code) {
try {
BaseDocument document = getDocument(code, "text/html");
Source source = Source.create(document);
final AtomicReference<KOModel> modelRef = new AtomicReference<>();
ParserManager.parse(Collections.singleton(source), new UserTask() {
@Override
public void run(ResultIterator resultIterator) throws Exception {
ResultIterator htmlResult = WebUtils.getResultIterator(resultIterator, "text/html");
assertNotNull(htmlResult);
modelRef.set(KOModel.getModel((HtmlParserResult)htmlResult.getParserResult()));
}
});
assertNotNull(modelRef.get());
return modelRef.get();
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
} |
922ee4238294deb0269ac6189950cb950da8c699 | 2,237 | java | Java | app/src/main/java/arcus/app/device/removal/zwave/ZWaveUnpairingFragment.java | eanderso/arcusandroid | fabe1eeb73aa19598198dc57487d7e72076f9daf | [
"Apache-2.0"
] | 30 | 2019-03-01T01:25:19.000Z | 2020-09-12T02:27:22.000Z | app/src/main/java/arcus/app/device/removal/zwave/ZWaveUnpairingFragment.java | eanderso/arcusandroid | fabe1eeb73aa19598198dc57487d7e72076f9daf | [
"Apache-2.0"
] | 21 | 2019-09-16T07:37:00.000Z | 2020-04-30T05:00:06.000Z | app/src/main/java/arcus/app/device/removal/zwave/ZWaveUnpairingFragment.java | eanderso/arcusandroid | fabe1eeb73aa19598198dc57487d7e72076f9daf | [
"Apache-2.0"
] | 29 | 2019-03-09T00:24:20.000Z | 2021-01-07T14:34:03.000Z | 30.643836 | 123 | 0.717032 | 994,915 | /*
* Copyright 2019 Arcus Project.
*
* 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 arcus.app.device.removal.zwave;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import arcus.app.R;
import arcus.app.common.sequence.SequencedFragment;
import arcus.app.common.view.Version1Button;
import arcus.app.common.view.Version1ButtonColor;
import arcus.app.device.removal.zwave.controller.ZWaveUnpairingSequenceController;
public class ZWaveUnpairingFragment extends SequencedFragment<ZWaveUnpairingSequenceController> {
@NonNull
public static ZWaveUnpairingFragment newInstance () {
return new ZWaveUnpairingFragment();
}
@Override
public void onResume() {
super.onResume();
setTitle();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
Version1Button button = (Version1Button) view.findViewById(R.id.remove_zwave_devices);
button.setColorScheme(Version1ButtonColor.WHITE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
goNext();
}
});
return view;
}
@Nullable
@Override
public String getTitle() {
return getString(R.string.zwave_remove_devices);
}
@Override
public Integer getLayoutId() {
return R.layout.fragment_zwave_unpairing;
}
}
|
922ee4cd5493c3bec0ab8cf11801b0bb92fcd619 | 922 | java | Java | java-examples/src/test/java/ru/qa/training/javaexamples/MyFirstTest.java | AleksandraTokareva/seleniumWebDriver_training | 6b4bfc3234ba5e453f5898a238c0ea2f7646aa39 | [
"Apache-2.0"
] | null | null | null | java-examples/src/test/java/ru/qa/training/javaexamples/MyFirstTest.java | AleksandraTokareva/seleniumWebDriver_training | 6b4bfc3234ba5e453f5898a238c0ea2f7646aa39 | [
"Apache-2.0"
] | null | null | null | java-examples/src/test/java/ru/qa/training/javaexamples/MyFirstTest.java | AleksandraTokareva/seleniumWebDriver_training | 6b4bfc3234ba5e453f5898a238c0ea2f7646aa39 | [
"Apache-2.0"
] | null | null | null | 23.05 | 107 | 0.665944 | 994,916 | package ru.qa.training.javaexamples;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class MyFirstTest {
private WebDriver driver;
private WebDriverWait wait;
@Before
public void start() {
//System.setProperty("webdriver.chrome.driver", "C:\\Tools\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
wait = new WebDriverWait(driver, 10);
}
@Test
public void myFirstTest() {
driver.get("https://mail.ru/");
driver.findElement(By.name("q")).sendKeys("Новости в Самаре");
driver.findElement(By.id("search:submit")).click();
}
@After
public void stop() {
driver.quit();
driver = null;
}
}
|
922ee5884d5d1c6fc87adb460bee0b88c5bbd5ca | 1,376 | java | Java | art/tools/dexfuzz/src/dexfuzz/rawdex/DebugInfoItem.java | lihuibng/marshmallow | 950cf8de3b4d63af9fc9699374e4ec45ad09b3a7 | [
"Apache-2.0"
] | 234 | 2017-07-18T05:30:27.000Z | 2022-01-07T02:21:31.000Z | tools/dexfuzz/src/dexfuzz/rawdex/DebugInfoItem.java | sanshao27/xposed_art_n | 5c4082fbb47fae1bb891725cd9f4b2e3c34efb75 | [
"MIT"
] | 21 | 2017-07-18T04:56:09.000Z | 2018-08-10T17:32:16.000Z | tools/dexfuzz/src/dexfuzz/rawdex/DebugInfoItem.java | sanshao27/xposed_art_n | 5c4082fbb47fae1bb891725cd9f4b2e3c34efb75 | [
"MIT"
] | 56 | 2017-07-18T10:37:10.000Z | 2022-01-07T02:19:22.000Z | 28.666667 | 75 | 0.732558 | 994,917 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 dexfuzz.rawdex;
import java.io.IOException;
// Right now we are not parsing debug_info_item, just take the raw size
public class DebugInfoItem implements RawDexObject {
private int size;
private byte[] data;
public DebugInfoItem(int size) {
this.size = size;
}
@Override
public void read(DexRandomAccessFile file) throws IOException {
file.getOffsetTracker().getNewOffsettable(file, this);
data = new byte[size];
file.read(data);
}
@Override
public void write(DexRandomAccessFile file) throws IOException {
file.getOffsetTracker().updatePositionOfNextOffsettable(file);
file.write(data);
}
@Override
public void incrementIndex(IndexUpdateKind kind, int insertedIdx) {
// Do nothing.
}
}
|
922ee670c7c5844def6da5a526f7aa1538d66709 | 7,464 | java | Java | potatoes/src/main/java/com/deco2800/potatoes/entities/projectiles/Projectile.java | michaelruigrok/rocketpotatoes | d8d53ccef2849b07fd9082e3b0c35ebf5366d101 | [
"MIT"
] | 1 | 2020-12-28T11:33:52.000Z | 2020-12-28T11:33:52.000Z | potatoes/src/main/java/com/deco2800/potatoes/entities/projectiles/Projectile.java | michaelruigrok/rocketpotatoes | d8d53ccef2849b07fd9082e3b0c35ebf5366d101 | [
"MIT"
] | null | null | null | potatoes/src/main/java/com/deco2800/potatoes/entities/projectiles/Projectile.java | michaelruigrok/rocketpotatoes | d8d53ccef2849b07fd9082e3b0c35ebf5366d101 | [
"MIT"
] | null | null | null | 22.280597 | 104 | 0.669078 | 994,918 | package com.deco2800.potatoes.entities.projectiles;
import java.util.Map;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.deco2800.potatoes.collisions.Circle2D;
import com.deco2800.potatoes.collisions.Shape2D;
import com.deco2800.potatoes.entities.AbstractEntity;
import com.deco2800.potatoes.entities.Tickable;
import com.deco2800.potatoes.entities.effects.Effect;
import com.deco2800.potatoes.entities.enemies.EnemyEntity;
import com.deco2800.potatoes.entities.health.MortalEntity;
import com.deco2800.potatoes.managers.GameManager;
public class Projectile extends AbstractEntity implements Tickable {
protected static final float SPEED = 0.2f;
protected ProjectileTexture projectileTexture;
protected boolean loopAnimation = true;
protected boolean animated = true;
protected Vector3 targetPos = new Vector3();
protected Vector3 change = new Vector3();
protected Vector2 delta = new Vector2();
protected static float shadowRadius = 0.4f;
protected static float xRenderLength = 1.4f;
protected static float yRenderLength = 1.4f;
protected static float xLength = 0.4f;
protected static float yLength = 0.4f;
protected static float zLength = 0.4f;
protected Class<?> targetClass;
protected boolean rangeReached;
protected boolean canRemove = true;
protected float maxRange;
protected float range;
protected float damage;
protected float rotationAngle = 0;
protected Effect startEffect;
protected Effect endEffect;
/**
* A container to hold the textures for easy lookup
*/
public enum ProjectileTexture {
ROCKET {
@Override
public String[] textures() {
return new String[] { "rocket1", "rocket2", "rocket3" };
}
},
CHILLI {
@Override
public String[] textures() {
return new String[] { "chilli1", "chilli2", "chilli3" };
}
},
LEAVES {
@Override
public String[] textures() {
return new String[] { "leaves" };
}
},
ACORN {
@Override
public String[] textures() {
return new String[] { "acorn" };
}
},
ORB {
@Override
public String[] textures() {
return new String[] { "orb1" };
}
},
ARROW {
@Override
public String[] textures() {
return new String[] { "arrow" };
}
},
AXE {
@Override
public String[] textures() {
return new String[] { "axe" };
}
},
WATER {
@Override
public String[] textures() {
return new String[] { "water" };
}
},
ICE {
@Override
public String[] textures() {
return new String[] { "ice" };
}
},
FIRE {
@Override
public String[] textures() {
return new String[] { "fire" };
}
}
;
public String[] textures() {
return new String[] { "default" };
}
}
public Projectile() {
// nothing yet
}
/**
* Creates a new projectile. A projectile is the vehicle used to deliver damage
* to a target over a distance
*
* @param targetClass
* the targets class
* @param startPos
* @param targetPos
* @param range
* @param damage
* damage of projectile
* @param projectileTexture
* the texture set to use for animations. Use ProjectileTexture._
* @param startEffect
* the effect to play at the start of the projectile being fired
* @param endEffect
* the effect to be played if a collision occurs
*/
public Projectile(Class<?> targetClass, Vector3 startPos, Vector3 targetPos, float range, float damage,
ProjectileTexture projectileTexture, Effect startEffect, Effect endEffect) {
super(new Circle2D(startPos.x, startPos.y, getShadowRadius()), xRenderLength, yRenderLength,
projectileTexture.textures()[0]);
if (targetClass != null)
this.targetClass = targetClass;
else
this.targetClass = EnemyEntity.class;
this.projectileTexture = projectileTexture;
this.maxRange = this.range = range;
this.damage = damage;
this.startEffect = startEffect;
this.endEffect = endEffect;
if (startEffect != null)
GameManager.get().getWorld().addEntity(startEffect);
setTargetPosition(targetPos.x, targetPos.y, targetPos.z);
setPosition();
}
/**
* Initialize heading. Used if heading changes
*/
protected void updateHeading() {
delta.set(getPosX() - targetPos.x, getPosY() - targetPos.y);
float angle = (float) Math.atan2(delta.y, delta.x) + (float) Math.PI;
rotationAngle = (float) (angle * 180 / Math.PI + 45 + 90);
change.set((float) (SPEED * Math.cos(angle)), (float) (SPEED * Math.sin(angle)), 0);
}
/**
* Set the location of the target
*
* @param xPos
* target x position
* @param yPos
* target y position
* @param zPos
* target y position
*/
public void setTargetPosition(float xPos, float yPos, float zPos) {
targetPos.set(xPos, yPos, zPos);
updateHeading();
}
/**
* Each frame the position is set/updated
*/
protected void setPosition() {
setPosX(getPosX() + change.x);
setPosY(getPosY() + change.y);
if ((range < SPEED || rangeReached) && canRemove) {
GameManager.get().getWorld().removeEntity(this);
} else {
range -= SPEED;
}
}
@Override
public float rotationAngle() {
return rotationAngle;
}
protected int projectileEffectTimer;
protected int projectileCurrentSpriteIndexCount;
/**
* Loops through texture array and sets sprite every frame. Looking into using
* AnimationFactory as animation controller
*/
protected void animate() {
if (animated) {
projectileEffectTimer++;
if (loopAnimation && projectileEffectTimer % 4 == 0) {
setTexture(projectileTexture.textures()[projectileCurrentSpriteIndexCount]);
if (projectileCurrentSpriteIndexCount == projectileTexture.textures().length - 1)
projectileCurrentSpriteIndexCount = 0;
else {
projectileCurrentSpriteIndexCount++;
}
}
}
}
@Override
public void onTick(long time) {
animate();
setPosition();
Shape2D newPos = getMask();
newPos.setX(this.getPosX());
newPos.setY(this.getPosY());
Map<Integer, AbstractEntity> entities = GameManager.get().getWorld().getEntities();
for (AbstractEntity entity : entities.values()) {
if (!targetClass.isInstance(entity)) {
continue;
}
if (newPos.overlaps(entity.getMask())) {
((EnemyEntity) entity).damage(damage / 10);
if (endEffect != null)
GameManager.get().getWorld().addEntity(endEffect);
rangeReached = true;
setPosition();
}
}
}
/**
* Returns max range
*
* @return maxRange
*/
public float getRange() {
return maxRange;
}
/**
* Returns Damage value
*
* @return damage
*/
public float getDamage() {
return damage;
}
/**
* Return target class
*
* @return targetClass
*/
public Class<?> getTargetClass() {
return targetClass;
}
/**
* Get the start effect
*
* @return startEffect
*/
public Effect getStartEffect() {
return startEffect;
}
/**
* Get the end effect
*
* @return endEffect
*/
public Effect getEndEffect() {
return endEffect;
}
/**
* Returns Target Pos X
*/
public float getTargetPosX() {
return targetPos.x;
}
/**
* Returns Target Pos Y
*/
public float getTargetPosY() {
return targetPos.y;
}
/**
* Set shadow radius
*
* @param radius
*/
public void setShadowRadius(float radius) {
shadowRadius = radius;
}
/**
* Returns shadow radius
*
* @return shadow radius
*/
public static float getShadowRadius() {
return shadowRadius;
}
}
|
922ee69128874b58fb5bfde2e57105216c0c75b0 | 3,908 | java | Java | src/de/mk/environment/PlayingFieldWindow.java | txtData/SnakeAI | 5ff52a1c1d51e2f379f8c8044240490b7eec8b6c | [
"Apache-2.0"
] | null | null | null | src/de/mk/environment/PlayingFieldWindow.java | txtData/SnakeAI | 5ff52a1c1d51e2f379f8c8044240490b7eec8b6c | [
"Apache-2.0"
] | null | null | null | src/de/mk/environment/PlayingFieldWindow.java | txtData/SnakeAI | 5ff52a1c1d51e2f379f8c8044240490b7eec8b6c | [
"Apache-2.0"
] | null | null | null | 35.207207 | 101 | 0.602866 | 994,919 | package de.mk.environment;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PlayingFieldWindow extends JPanel {
private static PlayingFieldWindow MY_INSTANCE;
private static final int HEADER_MARGIN = 10;
private static final int POINT_SIZE = 20;
private static final int POINT_MARGIN = 2;
private static final int FIELD_MARGIN = 10;
private static Snake currentSnake;
private static PlayingField playingField = new PlayingField();
private static int generation = 0;
private static double averageFitness = 0.0;
private static Color[] COLORS = {
new Color(255, 255, 255),
new Color(122, 122, 122),
new Color(250, 0, 0),
new Color(110, 173, 250),
new Color(14, 0, 250)
};
public PlayingFieldWindow(){
PlayingFieldWindow.MY_INSTANCE = this;
}
public void placeSnake(Snake snake, int generation, double averageFitness){
PlayingFieldWindow.currentSnake = snake;
PlayingFieldWindow.generation = generation;
PlayingFieldWindow.averageFitness = averageFitness;
PlayingFieldWindow.playingField = new PlayingField();
PlayingFieldWindow.playingField.setSnake(currentSnake);
}
public void showGame(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
javax.swing.Timer t = new javax.swing.Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
PlayingField pf = PlayingFieldWindow.playingField;
if (pf!=null && pf.snake!=null && pf.snake.alive) {
pf.moveSnake();
}
MY_INSTANCE.revalidate();
MY_INSTANCE.repaint();
}
});
t.start();
}
public boolean isRunning(){
if (currentSnake==null) return false;
else return currentSnake.alive;
}
private void createAndShowGui() {
JFrame jFrame = new JFrame("Snake AI - Playing Field");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.getContentPane().add(MY_INSTANCE);
jFrame.pack();
jFrame.setLocationByPlatform(true);
jFrame.setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int x = 0; x<playingField.getWidth(); x++){
for (int y = 0; y<playingField.getHeight(); y++){
Color color = COLORS[playingField.getAt(x,y)];
if (playingField.snake==null && playingField.getAt(x,y)==2){
color = COLORS[0];
}
g.setColor(color);
g.fillRect(FIELD_MARGIN + x * (POINT_SIZE + POINT_MARGIN),
HEADER_MARGIN + FIELD_MARGIN + y * (POINT_SIZE + POINT_MARGIN),
POINT_SIZE,
POINT_SIZE);
}
}
g.setColor(Color.BLACK);
g.drawString("Generation: "+generation, HEADER_MARGIN, 15);
if (playingField.snake!=null) {
g.drawString(String.format("Avg. Fitness: %.3f",averageFitness), HEADER_MARGIN +100, 15);
g.drawString("Score: " + playingField.snake.body.size(), HEADER_MARGIN + 280, 15);
g.drawString("Moves Alive: " + playingField.snake.timeAlive, HEADER_MARGIN + 350, 15);
g.drawString("Moves Left: " + playingField.snake.life, HEADER_MARGIN + 462, 15);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(FIELD_MARGIN*2 + (POINT_SIZE+POINT_MARGIN)*playingField.getWidth(),
FIELD_MARGIN*2 + (POINT_SIZE+POINT_MARGIN)*playingField.getHeight() + 10);
}
} |
922ee7bbb57d8bd8d129e4212866624d93f336a5 | 1,101 | java | Java | src/main/scala/org/openolat/gatling/setup/voes/RepositoryEntryStatusEnum.java | OpenOLAT/OpenOLAT-gatling | 6cb8f5dfad2d4fb1ec76de2e2bbd571c4ee290ac | [
"Apache-2.0"
] | 1 | 2020-12-07T07:45:31.000Z | 2020-12-07T07:45:31.000Z | src/main/scala/org/openolat/gatling/setup/voes/RepositoryEntryStatusEnum.java | OpenOLAT/OpenOLAT-gatling | 6cb8f5dfad2d4fb1ec76de2e2bbd571c4ee290ac | [
"Apache-2.0"
] | null | null | null | src/main/scala/org/openolat/gatling/setup/voes/RepositoryEntryStatusEnum.java | OpenOLAT/OpenOLAT-gatling | 6cb8f5dfad2d4fb1ec76de2e2bbd571c4ee290ac | [
"Apache-2.0"
] | 1 | 2020-12-07T07:45:32.000Z | 2020-12-07T07:45:32.000Z | 28.461538 | 82 | 0.706306 | 994,920 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.openolat.gatling.setup.voes;
/**
*
* Initial date: 20 juil. 2018<br>
* @author srosse, nnheo@example.com, http://www.frentix.com
*
*/
public enum RepositoryEntryStatusEnum {
preparation,
review,
coachpublished,
published,
closed,
trash,
deleted;
}
|
922ee804a49ab4cf9b9804fbc15f55fd054b8a14 | 4,206 | java | Java | java/refactoring.java/test/qa-functional/src/org/netbeans/modules/test/refactoring/operators/OverflowToolbarOperator.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | java/refactoring.java/test/qa-functional/src/org/netbeans/modules/test/refactoring/operators/OverflowToolbarOperator.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | java/refactoring.java/test/qa-functional/src/org/netbeans/modules/test/refactoring/operators/OverflowToolbarOperator.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 34.47541 | 109 | 0.747504 | 994,921 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.test.refactoring.operators;
import java.awt.Component;
import java.awt.Container;
import java.lang.reflect.Field;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import org.netbeans.jemmy.ComponentChooser;
import org.netbeans.jemmy.ComponentSearcher;
import org.netbeans.jemmy.operators.AbstractButtonOperator;
import org.netbeans.jemmy.operators.ContainerOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.Operator.StringComparator;
import org.openide.awt.ToolbarWithOverflow;
import org.openide.util.Exceptions;
/**
<p>
@author Standa
*/
public class OverflowToolbarOperator extends ContainerOperator{
final private ToolbarWithOverflow overflow;
public OverflowToolbarOperator(ContainerOperator container){
super(container);
Component findSubComponent = container.findSubComponent(new ToolbarWithOverflowChooser());
overflow = (ToolbarWithOverflow) findSubComponent;
}
public AbstractButton getButton(String tooltip) {
AbstractButton findJButton = null;
ComponentSearcher mySearcher= new ComponentSearcher(overflow);
mySearcher.setOutput(getOutput());
Component myComponent = mySearcher.findComponent(new ToolbarButtonChooser(tooltip,getComparator()), 0);
if(myComponent != null){
findJButton = (AbstractButton) myComponent;
}
if(findJButton!=null) return findJButton;
JPopupMenu menu = null;
try {
Field f = ToolbarWithOverflow.class.getDeclaredField("popup");
f.setAccessible(true);
Object get = f.get(overflow);
menu = (JPopupMenu) get;
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
ex.printStackTrace();
return null;
}
menu.setVisible(true);
ComponentSearcher searcher= new ComponentSearcher(menu);
searcher.setOutput(getOutput());
Component c = searcher.findComponent(new ToolbarButtonChooser(tooltip,getComparator()), 0);
return (AbstractButton) c;
}
private static class ToolbarWithOverflowChooser implements ComponentChooser {
@Override
public boolean checkComponent(Component comp){
return comp instanceof ToolbarWithOverflow;
}
@Override
public String getDescription(){
return "Overflow Toolbar.";//To change body of generated methods, choose Tools | Templates.
}
}
/** Chooser which can be used to find a component with given tooltip,
* for example a toolbar button.
*/
private static class ToolbarButtonChooser implements ComponentChooser {
private String buttonTooltip;
private StringComparator comparator;
public ToolbarButtonChooser(String buttonTooltip, StringComparator comparator) {
this.buttonTooltip = buttonTooltip;
this.comparator = comparator;
}
@Override
public boolean checkComponent(Component comp) {
String Str1 = ((JComponent)comp).getToolTipText();
String Str2 = buttonTooltip;
boolean ret = comparator.equals(((JComponent)comp).getToolTipText(), buttonTooltip);
return comparator.equals(((JComponent)comp).getToolTipText(), buttonTooltip);
}
@Override
public String getDescription() {
return "Toolbar button with tooltip \""+buttonTooltip+"\".";
}
}
}
|
922eebf3fc54bea2d42392b3a41c10fa6a52db1d | 165 | java | Java | GraphPathfindingAlgorithmsVisualization/src/com/arthurivanets/graphalgorithmsvisualization/util/CSVConvertable.java | arthur3486/graphpathfindingalgorithmsvisualization | 099913c9a8bbb45c96bcf630efd5991868ed5b2a | [
"Apache-2.0"
] | null | null | null | GraphPathfindingAlgorithmsVisualization/src/com/arthurivanets/graphalgorithmsvisualization/util/CSVConvertable.java | arthur3486/graphpathfindingalgorithmsvisualization | 099913c9a8bbb45c96bcf630efd5991868ed5b2a | [
"Apache-2.0"
] | null | null | null | GraphPathfindingAlgorithmsVisualization/src/com/arthurivanets/graphalgorithmsvisualization/util/CSVConvertable.java | arthur3486/graphpathfindingalgorithmsvisualization | 099913c9a8bbb45c96bcf630efd5991868ed5b2a | [
"Apache-2.0"
] | null | null | null | 16.5 | 60 | 0.781818 | 994,922 | package com.arthurivanets.graphalgorithmsvisualization.util;
public interface CSVConvertable<T> {
public T fromCSV(String csvData);
public String toCSV();
}
|
922eeca03aec74224fd4e45c1b32a0658d4227ff | 2,558 | java | Java | src/resources/ForecastDB/MainTableItem.java | mlldaniel/NewsLetterAutomation | 435f0beb9bb64798c1bcd097af9e6b5a499f5200 | [
"MIT"
] | null | null | null | src/resources/ForecastDB/MainTableItem.java | mlldaniel/NewsLetterAutomation | 435f0beb9bb64798c1bcd097af9e6b5a499f5200 | [
"MIT"
] | null | null | null | src/resources/ForecastDB/MainTableItem.java | mlldaniel/NewsLetterAutomation | 435f0beb9bb64798c1bcd097af9e6b5a499f5200 | [
"MIT"
] | null | null | null | 21.677966 | 80 | 0.612588 | 994,923 | /*
* 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 resources.ForecastDB;
import java.util.List;
/**
*
* @author Daniel
*/
public class MainTableItem {
private int id;
private String title;
private String link;
private String positionType;
private String packageName;
private String subpackageName;
private String csvFilePath;
private String timeFrame;
private String forecastDate;
private String targetDate;
private List<CsvTable> csvTableList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPositionType() {
return positionType;
}
public void setPositionType(String positionType) {
this.positionType = positionType;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getSubpackageName() {
return subpackageName;
}
public void setSubpackageName(String subpackageName) {
this.subpackageName = subpackageName;
}
public String getTimeFrame() {
return timeFrame;
}
public void setTimeFrame(String timeFrame) {
this.timeFrame = timeFrame;
}
public String getForecastDate() {
return forecastDate;
}
public void setForecastDate(String forecastDate) {
this.forecastDate = forecastDate;
}
public String getTargetDate() {
return targetDate;
}
public void setTargetDate(String targetDate) {
this.targetDate = targetDate;
}
public List<CsvTable> getCsvTableList() {
return csvTableList;
}
public void setCsvTableList(List<CsvTable> csvTableList) {
this.csvTableList = csvTableList;
}
public String getCsvFilePath() {
return csvFilePath;
}
public void setCsvFilePath(String csvFilePath) {
this.csvFilePath = csvFilePath;
}
}
|
922eed2be624a395291dce0bf39e7d14514b1c78 | 8,575 | java | Java | ficum-visitor/src/main/java/de/bitgrip/ficum/visitor/MongoDBFilterVisitor.java | bitgrip/ficum | 5f169f641138c187869e4e487dfd915f09a8ed38 | [
"Apache-2.0"
] | 5 | 2019-07-13T20:15:51.000Z | 2022-01-20T14:12:49.000Z | ficum-visitor/src/main/java/de/bitgrip/ficum/visitor/MongoDBFilterVisitor.java | bitgrip/ficum | 5f169f641138c187869e4e487dfd915f09a8ed38 | [
"Apache-2.0"
] | 15 | 2019-07-24T13:08:45.000Z | 2022-03-31T20:00:37.000Z | ficum-visitor/src/main/java/de/bitgrip/ficum/visitor/MongoDBFilterVisitor.java | bitgrip/ficum | 5f169f641138c187869e4e487dfd915f09a8ed38 | [
"Apache-2.0"
] | null | null | null | 34.163347 | 121 | 0.552653 | 994,924 | package de.bitgrip.ficum.visitor;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.geojson.LineString;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Polygon;
import com.mongodb.client.model.geojson.Position;
import de.bitgrip.ficum.node.*;
import org.bson.conversions.Bson;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class MongoDBFilterVisitor extends AbstractVisitor<Bson> {
private List<Bson> filters;
private Bson buildEquals(String fieldName, Comparable<?> argument) {
Bson pred;
if (argument instanceof String) {
final String value = (String) argument;
if (containsWildcard(value) || isAlwaysWildcard()) {
String regex = Wildcards.escapeAndConvertToRegexWildcards(value, isAlwaysWildcard());
pred = Filters.regex(fieldName, regex);
} else {
pred = Filters.eq(fieldName, value);
}
} else {
pred = Filters.eq(fieldName, argument);
}
return pred;
}
private Bson buildNotEquals(String fieldName, Comparable<?> argument) {
Bson pred;
if (argument instanceof String) {
final String value = (String) argument;
if (containsWildcard(value) || isAlwaysWildcard()) {
String regex = Wildcards.escapeAndConvertToRegexWildcards(value, isAlwaysWildcard());
pred = Filters.not(Filters.regex(fieldName, regex));
} else {
pred = Filters.ne(fieldName, value);
}
} else {
pred = Filters.ne(fieldName, argument);
}
return pred;
}
private Bson doBuildPredicate(Comparison comparison, String fieldName, List<Comparable> comparables) {
List<Double> geoargs = sanatizeToDouble(comparables);
switch (comparison) {
case NEAR:
if (geoargs.size() == 3) {
return Filters.nearSphere(fieldName, new Point(new Position(geoargs.get(0), geoargs.get(1))),
geoargs.get(2), null);
} else if (geoargs.size() == 4) {
return Filters.nearSphere(fieldName, new Point(new Position(geoargs.get(0), geoargs.get(1))),
geoargs.get(2), geoargs.get(3));
}
break;
case WITHIN:
switch (geoargs.size()) {
case 0:
case 1:
case 2:
break;
case 3:
return Filters.geoWithinCenterSphere(fieldName, geoargs.get(0), geoargs.get(1), geoargs.get(2));
case 4:
return Filters.geoWithinBox(fieldName, geoargs.get(0), geoargs.get(1), geoargs.get(2),
geoargs.get(3));
default:
@SuppressWarnings("unchecked")
Polygon geometry = new Polygon(toPositions(geoargs, true));
return Filters.geoWithin(fieldName, geometry);
}
break;
case INTERSECT:
switch (geoargs.size()) {
case 0:
case 1:
case 3:
break;
case 2:
return Filters.geoIntersects(fieldName, new Point(new Position(geoargs.get(0), geoargs.get(1))));
case 4:
return Filters.geoIntersects(fieldName, new LineString(toPositions(geoargs, false)));
default:
@SuppressWarnings("unchecked")
Polygon geometry = new Polygon(toPositions(geoargs, true));
return Filters.geoIntersects(fieldName, geometry);
}
break;
case IN:
return Filters.in(fieldName, comparables);
case NIN:
return Filters.nin(fieldName, comparables);
default:
break;
}
return null;
}
private Bson doBuildPredicate(Comparison comparison, String fieldName, Comparable<?> argument) {
switch (comparison) {
case GREATER_THAN:
return Filters.gt(fieldName, argument);
case EQUALS:
return buildEquals(fieldName, argument);
case NOT_EQUALS:
return buildNotEquals(fieldName, argument);
case LESS_THAN:
return Filters.lt(fieldName, argument);
case LESS_EQUALS:
return Filters.lte(fieldName, argument);
case GREATER_EQUALS:
return Filters.gte(fieldName, argument);
case IN:
case NIN:
return doBuildPredicate(comparison, fieldName, Collections.singletonList(argument));
default:
return null;
}
}
public Bson start(Node node) {
filters = new ArrayList<Bson>();
node.accept(this);
if (filters.size() != 1) {
throw new IllegalStateException("single predicate expected, but was: " + filters);
}
return filters.get(0);
}
private List<Position> toPositions(List<Double> arguments, boolean close) {
Iterator<Double> it = arguments.iterator();
List<Position> positions = new ArrayList<Position>();
while (it.hasNext()) {
Double lon = it.next();
if (it.hasNext()) {
Double lat = it.next();
positions.add(new Position(lon, lat));
}
}
if (close && positions.size() >= 3 && !positions.get(0).equals(positions.get(positions.size() - 1))) {
positions.add(positions.get(0));
}
return positions;
}
private List<Double> sanatizeToDouble(List<Comparable> arguments) {
Iterator<Double> value = Iterators.filter(arguments.iterator(), Double.class);
return Lists.newArrayList(value);
}
public void visit(ConstraintNode<?> node) {
Object argument = node.getArgument();
String fieldName = getMappedField(node.getSelector());
Bson pred = null;
if (argument instanceof Comparable<?>) {
Comparable<?> value = (Comparable<?>) argument;
if (value instanceof OffsetDateTime) {
value = ((OffsetDateTime) value).toLocalDateTime();
}
pred = doBuildPredicate(node.getComparison(), fieldName, value);
} else if (argument instanceof List) {
pred = doBuildPredicate(node.getComparison(), fieldName, sanatizeToComparable((List) argument));
} else if (argument == null) {
pred = doBuildPredicate(node.getComparison(), fieldName, (Comparable<?>) null);
} else {
throw new IllegalArgumentException("Unable to handle argument of type " + argument.getClass().getName());
}
if (pred != null) {
filters.add(pred);
} else {
throw new IllegalArgumentException("Constraint: " + node + " does not resolve to a predicate");
}
}
public void visit(OperationNode node) {
node.getLeft().accept(this);
node.getRight().accept(this);
Bson pred = null;
Bson leftHandSide = filters.get(filters.size() - 2);
Bson rightHandSide = filters.get(filters.size() - 1);
switch (node.getOperator()) {
case AND:
pred = Filters.and(leftHandSide, rightHandSide);
break;
case OR:
pred = Filters.or(leftHandSide, rightHandSide);
break;
case NAND:
pred = Filters.or(Filters.not(leftHandSide), Filters.not(rightHandSide));
break;
case NOR:
pred = Filters.and(Filters.not(leftHandSide), Filters.not(rightHandSide));
break;
default:
throw new IllegalArgumentException("OperationNode: " + node + " does not resolve to a operation");
}
filters.remove(leftHandSide);
filters.remove(rightHandSide);
filters.add(pred);
}
}
|
922eed81b2814167444d19bd0c169480e5946cd9 | 29,594 | java | Java | src/java/test/org/opentdc/rates/RateTest.java | opentdc/test-solution | 1ddceff8d3f9bf8cce596dd5b0a57277b293bf42 | [
"MIT"
] | null | null | null | src/java/test/org/opentdc/rates/RateTest.java | opentdc/test-solution | 1ddceff8d3f9bf8cce596dd5b0a57277b293bf42 | [
"MIT"
] | 4 | 2015-08-09T15:38:03.000Z | 2015-08-16T22:03:46.000Z | src/java/test/org/opentdc/rates/RateTest.java | opentdc/test-solution | 1ddceff8d3f9bf8cce596dd5b0a57277b293bf42 | [
"MIT"
] | null | null | null | 44.636501 | 141 | 0.73525 | 994,925 | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Arbalo AG
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package test.org.opentdc.rates;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opentdc.rates.Currency;
import org.opentdc.rates.RateType;
import org.opentdc.rates.RateModel;
import org.opentdc.rates.RatesService;
import org.opentdc.service.ServiceUtil;
import test.org.opentdc.AbstractTestClient;
/**
* Testing RatesService.
* @author Bruno Kaiser
*
*/
public class RateTest extends AbstractTestClient {
private WebClient wc = null;
@Before
public void initializeTest() {
wc = initializeTest(ServiceUtil.RATES_API_URL, RatesService.class);
}
@After
public void cleanupTest() {
wc.close();
}
/********************************** rates attributes tests *********************************/
@Test
public void testEmptyConstructor() {
RateModel _model = new RateModel();
assertNull("id should not be set by empty constructor", _model.getId());
assertNull("title should not be set by empty constructor", _model.getTitle());
assertEquals("rate should be initialized to 0 by empty constructor", 0, _model.getRate());
assertNull("currency should not be set by empty constructor", _model.getCurrency());
assertNull("description should not be set by empty constructor", _model.getDescription());
}
@Test
public void testConstructor() {
RateModel _model = new RateModel("testConstructor", 100, "testConstructor");
assertNull("id should not be set by constructor", _model.getId());
assertEquals("title should be set by constructor", "testConstructor", _model.getTitle());
assertEquals("rate should be set by constructor", 100, _model.getRate());
assertEquals("currency should be set to default value by constructor",
Currency.getDefaultCurrency(), _model.getCurrency());
assertEquals("description should not set by constructor", "testConstructor", _model.getDescription());
}
@Test
public void testId() {
RateModel _model = new RateModel();
assertNull("id should not be set by constructor", _model.getId());
_model.setId("testId");
assertEquals("id should have changed", "testId", _model.getId());
}
@Test
public void testTitle() {
RateModel _model = new RateModel();
assertNull("title should not be set by empty constructor", _model.getTitle());
_model.setTitle("testTitle");
assertEquals("title should have changed", "testTitle", _model.getTitle());
}
@Test
public void testRate() {
RateModel _model = new RateModel();
assertEquals("rate should initialized to 0 by empty constructor", 0, _model.getRate());
_model.setRate(100);
assertEquals("rate should have changed", 100, _model.getRate());
}
@Test
public void testCreatedBy() {
RateModel _model = new RateModel();
assertNull("createdBy should not be set by empty constructor", _model.getCreatedBy());
_model.setCreatedBy("testCreatedBy");
assertEquals("createdBy should have changed", "testCreatedBy", _model.getCreatedBy());
}
@Test
public void testCreatedAt() {
RateModel _model = new RateModel();
assertNull("createdAt should not be set by empty constructor", _model.getCreatedAt());
_model.setCreatedAt(new Date());
assertNotNull("createdAt should have changed", _model.getCreatedAt());
}
@Test
public void testModifiedBy() {
RateModel _model = new RateModel();
assertNull("modifiedBy should not be set by empty constructor", _model.getModifiedBy());
_model.setModifiedBy("testModifiedBy");
assertEquals("modifiedBy should have changed", "testModifiedBy", _model.getModifiedBy());
}
@Test
public void testModifiedAt() {
RateModel _model = new RateModel();
assertNull("modifiedAt should not be set by empty constructor", _model.getModifiedAt());
_model.setModifiedAt(new Date());
assertNotNull("modifiedAt should have changed", _model.getModifiedAt());
}
@Test
public void testCurrency() {
RateModel _model = new RateModel();
assertNull("currency should not be set by empty constructor", _model.getCurrency());
_model.setCurrency(Currency.getDefaultCurrency());
assertEquals("currency should have changed to default currency", Currency.getDefaultCurrency(), _model.getCurrency());
assertEquals("default currency should be correct", Currency.CHF, Currency.getDefaultCurrency());
_model.setCurrency(Currency.EUR);
assertEquals("currency should be correct", Currency.EUR, _model.getCurrency());
assertEquals("label should be correct", Currency.EUR.getLabel(), _model.getCurrency().getLabel());
assertEquals("label should be correct", "Euro", Currency.EUR.getLabel());
assertEquals("stringified value should be correct", Currency.EUR.toString(), _model.getCurrency().toString());
_model.setCurrency(Currency.CHF);
assertEquals("currency should be correct", Currency.CHF, _model.getCurrency());
assertEquals("label should be correct", Currency.CHF.getLabel(), _model.getCurrency().getLabel());
assertEquals("label should be correct", "Swiss Franc", Currency.CHF.getLabel());
assertEquals("stringified value should be correct", Currency.CHF.toString(), _model.getCurrency().toString());
_model.setCurrency(Currency.USD);
assertEquals("currency should be correct", Currency.USD, _model.getCurrency());
assertEquals("label should be correct", Currency.USD.getLabel(), _model.getCurrency().getLabel());
assertEquals("label should be correct", "US Dollar", Currency.USD.getLabel());
assertEquals("stringified value should be correct", Currency.USD.toString(), _model.getCurrency().toString());
}
@Test
public void testDescription() {
RateModel _model = new RateModel();
assertNull("description should not be set by empty constructor", _model.getDescription());
_model.setDescription("testDescription");
assertEquals("description should have changed", "testDescription", _model.getDescription());
}
/********************************* REST service tests *********************************/
@Test
public void testCreateReadDeleteWithEmptyConstructor() {
RateModel _model1 = new RateModel();
assertNull("id should not be set by empty constructor", _model1.getId());
assertNull("title should not be set by empty constructor", _model1.getTitle());
assertEquals("rate should initialized to 0 by empty constructor", 0, _model1.getRate());
assertNull("currency should not be set by empty constructor", _model1.getCurrency());
assertNull("description should not be set by empty constructor", _model1.getDescription());
post(_model1, Status.BAD_REQUEST);
_model1.setTitle("testCreateReadDeleteWithEmptyConstructor");
_model1.setRate(-1); // negative rates are not allowed
post(_model1, Status.BAD_REQUEST);
int _rate = 100;
_model1.setRate(_rate);
RateModel _model2 = post(_model1, Status.OK);
assertNull("create() should not change the id of the local object", _model1.getId());
assertEquals("create() should not change the title of the local object", "testCreateReadDeleteWithEmptyConstructor", _model1.getTitle());
assertEquals("create() should not change the rate of the local object", _rate, _model1.getRate());
assertNull("create() should not change the currency of the local object", _model1.getCurrency());
assertNull("create() should not change the description of the local object", _model1.getDescription());
assertNotNull("create() should set a valid id on the remote object returned", _model2.getId());
assertEquals("create() should not change the title", "testCreateReadDeleteWithEmptyConstructor", _model2.getTitle());
assertEquals("create() should not change the rate", _rate, _model2.getRate());
assertEquals("create() should set the default currency", Currency.getDefaultCurrency().getLabel(), _model2.getCurrency().getLabel());
assertEquals("create() should set the default type", RateType.getDefaultRateType(), _model2.getType());
assertNull("create() should not change the description", _model2.getDescription());
RateModel _model3 = get(_model2.getId(), Status.OK);
assertEquals("id of returned object should be the same", _model2.getId(), _model3.getId());
assertEquals("title of returned object should be unchanged", _model2.getTitle(), _model3.getTitle());
assertEquals("rate of returned object should be unchanged", _model2.getRate(), _model3.getRate());
assertEquals("currency of returned object should be unchanged", _model2.getCurrency(), _model3.getCurrency());
assertEquals("description of returned object should be unchanged", _model2.getDescription(), _model3.getDescription());
delete(_model3.getId(), Status.NO_CONTENT);
}
@Test
public void testCreateReadDelete() {
int _rate = 100;
RateModel _model1 = new RateModel("testCreateReadDelete", _rate, "testCreateReadDelete");
assertNull("id should not be set by constructor", _model1.getId());
assertEquals("title should be set by constructor", "testCreateReadDelete", _model1.getTitle());
assertEquals("description should be set by constructor", "testCreateReadDelete", _model1.getDescription());
assertEquals("type should be set to the default", RateType.getDefaultRateType(), _model1.getType());
assertEquals("currency should be set to the default", Currency.getDefaultCurrency(), _model1.getCurrency());
RateModel _model2 = post(_model1, Status.OK);
assertNull("id should be still null after remote create", _model1.getId());
assertEquals("title should be unchanged after remote create", "testCreateReadDelete", _model1.getTitle());
assertEquals("rate should be unchanged after remote create", _rate, _model1.getRate());
assertEquals("currency should be unchanged after remote create", Currency.getDefaultCurrency(), _model1.getCurrency());
assertEquals("type should be unchanged after remote create", RateType.getDefaultRateType(), _model1.getType());
assertEquals("description should be unchanged after remote create", "testCreateReadDelete", _model1.getDescription());
assertNotNull("id of returned object should be set", _model2.getId());
assertEquals("title of returned object should be unchanged after remote create", "testCreateReadDelete", _model2.getTitle());
assertEquals("rate should be unchanged after remote create", _rate, _model2.getRate());
assertEquals("currency should be unchanged after remote create", Currency.getDefaultCurrency(), _model2.getCurrency());
assertEquals("type should be unchanged after remote create", RateType.getDefaultRateType(), _model2.getType());
assertEquals("description of returned object should be unchanged after remote create", "testCreateReadDelete", _model2.getDescription());
RateModel _model3 = get(_model2.getId(), Status.OK);
assertEquals("id of returned object should be the same", _model2.getId(), _model3.getId());
assertEquals("title of returned object should be unchanged after remote create", _model2.getTitle(), _model3.getTitle());
assertEquals("rate should be unchanged after remote create", _model2.getRate(), _model3.getRate());
assertEquals("currency should be unchanged after remote create", _model2.getCurrency(), _model3.getCurrency());
assertEquals("type should be unchanged after remote create", _model2.getType(), _model3.getType());
assertEquals("description of returned object should be unchanged after remote create", _model2.getDescription(), _model3.getDescription());
delete(_model3.getId(), Status.NO_CONTENT);
}
@Test
public void testCreateWithClientSideId() {
RateModel _model = new RateModel("testCreateWithClientSideId", 100, "testCreateWithClientSideId");
_model.setId("LOCAL_ID");
assertEquals("id should have changed", "LOCAL_ID", _model.getId());
post(_model, Status.BAD_REQUEST);
}
@Test
public void testCreateWithDuplicateId() {
RateModel _model1 = post(new RateModel("testCreateWithDuplicateId", 100, "MY_DESC"), Status.OK);
RateModel _model2 = new RateModel("DuplicateRateModel", 100, "MY_DESC");
_model2.setId(_model1.getId()); // wrongly create a 2nd RateModel object with the same ID
post(_model2, Status.CONFLICT);
delete(_model1.getId(), Status.NO_CONTENT);
}
@Test
public void testList(
) {
ArrayList<RateModel> _localList = new ArrayList<RateModel>();
for (int i = 0; i < LIMIT; i++) {
_localList.add(post(new RateModel("testList" + i, 100+i, "MY_DESC"), Status.OK));
}
List<RateModel> _remoteList = list(null, Status.OK);
ArrayList<String> _remoteListIds = new ArrayList<String>();
for (RateModel _model : _remoteList) {
_remoteListIds.add(_model.getId());
}
for (RateModel _model : _localList) {
assertTrue("rate <" + _model.getId() + "> should be listed", _remoteListIds.contains(_model.getId()));
}
for (RateModel _model : _localList) {
get(_model.getId(), Status.OK);
}
for (RateModel _model : _localList) {
delete(_model.getId(), Status.NO_CONTENT);
}
}
@Test
public void testCreate() {
RateModel _model1 = post(new RateModel("testCreate1", 100, "MY_DESC1"), Status.OK);
RateModel _model2 = post(new RateModel("testCreate2", 200, "MY_DESC2"), Status.OK);
assertNotNull("ID should be set", _model1.getId());
assertNotNull("ID should be set", _model2.getId());
assertThat(_model2.getId(), not(equalTo(_model1.getId())));
assertEquals("title should be set correctly", "testCreate1", _model1.getTitle());
assertEquals("description should be set correctly", "MY_DESC1", _model1.getDescription());
assertEquals("rate should be set by constructor", 100, _model1.getRate());
assertEquals("currency should be set to default value by constructor", Currency.getDefaultCurrency(), _model1.getCurrency());
assertEquals("type should be set to default value by constructor", RateType.getDefaultRateType(), _model1.getType());
assertEquals("title should be set correctly", "testCreate2", _model2.getTitle());
assertEquals("description should be set correctly", "MY_DESC2", _model2.getDescription());
assertEquals("rate should be set by constructor", 200, _model2.getRate());
assertEquals("currency should be set to default value by constructor", Currency.getDefaultCurrency(), _model2.getCurrency());
assertEquals("type should be set to default value by constructor", RateType.getDefaultRateType(), _model2.getType());
delete(_model1.getId(), Status.NO_CONTENT);
delete(_model2.getId(), Status.NO_CONTENT);
}
@Test
public void testDoubleCreate()
{
RateModel _model = post(new RateModel("testDoubleCreate", 100, "MY_DESC"), Status.OK);
assertNotNull("ID should be set:", _model.getId());
post(_model, Status.CONFLICT);
delete(_model.getId(), Status.NO_CONTENT);
}
@Test
public void testRead() {
ArrayList<RateModel> _localList = new ArrayList<RateModel>();
for (int i = 0; i < LIMIT; i++) {
_localList.add(post(new RateModel("testRead" + i, 100 + i, "MY_DESC"), Status.OK));
}
// test read on each local element
for (RateModel _model : _localList) {
get(_model.getId(), Status.OK);
}
// test read on each listed element
for (RateModel _model : list(null, Status.OK)) {
assertEquals("ID should be unchanged when reading a rate", _model.getId(), get(_model.getId(), Status.OK).getId());
}
for (RateModel _model : _localList) {
delete(_model.getId(), Status.NO_CONTENT);
}
}
@Test
public void testMultiRead()
{
RateModel _model1 = post(new RateModel("testMultiRead", 100, "MY_DESC"), Status.OK);
RateModel _model2 = get(_model1.getId(), Status.OK);
assertEquals("ID should be unchanged after read:", _model1.getId(), _model2.getId());
RateModel _model3 = get(_model1.getId(), Status.OK);
assertEquals("ID should be the same:", _model2.getId(), _model3.getId());
assertEquals("title should be the same:", _model2.getTitle(), _model3.getTitle());
assertEquals("description should be the same:", _model2.getDescription(), _model3.getDescription());
assertEquals("currency should be the same:", _model2.getCurrency(), _model3.getCurrency());
assertEquals("type should be the same:", _model2.getType(), _model3.getType());
assertEquals("ID should be the same:", _model1.getId(), _model3.getId());
assertEquals("title should be the same:", _model2.getTitle(), _model3.getTitle());
assertEquals("description should be the same:", _model1.getDescription(), _model3.getDescription());
assertEquals("currency should be the same:", _model1.getCurrency(), _model3.getCurrency());
assertEquals("type should be the same:", _model1.getType(), _model3.getType());
delete(_model1.getId(), Status.NO_CONTENT);
}
@Test
public void testUpdate()
{
RateModel _model1 = post(new RateModel("testUpdate", 100, "MY_DESC"), Status.OK);
_model1.setTitle("testUpdate1");
_model1.setRate(300);
_model1.setCurrency(Currency.USD);
_model1.setType(RateType.STANDARD_EXTERNAL_ON_SITE);
_model1.setDescription("testUpdate1");
RateModel _model2 = put(_model1, Status.OK);
assertNotNull("ID should be set", _model2.getId());
assertEquals("ID should be unchanged", _model1.getId(), _model2.getId());
assertEquals("title should have changed", "testUpdate1", _model2.getTitle());
assertEquals("rate should have changed", 300, _model2.getRate());
assertEquals("currency should have changed", Currency.USD, _model2.getCurrency());
assertEquals("type should have changed", RateType.STANDARD_EXTERNAL_ON_SITE, _model2.getType());
assertEquals("description should have changed", "testUpdate1", _model2.getDescription());
_model1.setTitle("testUpdate2");
_model1.setRate(400);
_model1.setCurrency(Currency.EUR);
_model1.setType(RateType.STANDARD_EXTERNAL_OFF_SITE);
_model1.setDescription("testUpdate2");
RateModel _model3 = put(_model1, Status.OK);
assertNotNull("ID should be set", _model3.getId());
assertEquals("ID should be unchanged", _model1.getId(), _model3.getId());
assertEquals("title should have changed", "testUpdate2", _model3.getTitle());
assertEquals("rate should have changed", 400, _model3.getRate());
assertEquals("currency should have changed", Currency.EUR, _model3.getCurrency());
assertEquals("type should have changed", RateType.STANDARD_EXTERNAL_OFF_SITE, _model3.getType());
assertEquals("description should have changed", "testUpdate2", _model3.getDescription());
delete(_model1.getId(), Status.NO_CONTENT);
}
@Test
public void testDelete() {
RateModel _model = post(new RateModel("testDelete", 100, "MY_DESC"), Status.OK);
RateModel _tmpObj = get(_model.getId(), Status.OK);
assertEquals("ID should be unchanged when reading a rate (remote):", _model.getId(), _tmpObj.getId());
delete(_model.getId(), Status.NO_CONTENT);
get(_model.getId(), Status.NOT_FOUND);
get(_model.getId(), Status.NOT_FOUND);
}
@Test
public void testDoubleDelete() {
RateModel _model = post(new RateModel("testDoubleDelete", 100, "MY_DESC"), Status.OK);
get(_model.getId(), Status.OK);
delete(_model.getId(), Status.NO_CONTENT);
get(_model.getId(), Status.NOT_FOUND);
delete(_model.getId(), Status.NOT_FOUND);
get(_model.getId(), Status.NOT_FOUND);
}
@Test
public void testModifications() {
RateModel _model1 = post(new RateModel("testModifications", 100, "MY_DESC"), Status.OK);
assertNotNull("create() should set createdAt", _model1.getCreatedAt());
assertNotNull("create() should set createdBy", _model1.getCreatedBy());
assertNotNull("create() should set modifiedAt", _model1.getModifiedAt());
assertNotNull("create() should set modifiedBy", _model1.getModifiedBy());
assertEquals("createdAt and modifiedAt should be identical after create()", _model1.getCreatedAt(), _model1.getModifiedAt());
assertEquals("createdBy and modifiedBy should be identical after create()", _model1.getCreatedBy(), _model1.getModifiedBy());
_model1.setTitle("testModifications1");
RateModel _model2 = put(_model1, Status.OK);
assertEquals("update() should not change createdAt", _model1.getCreatedAt(), _model2.getCreatedAt());
assertEquals("update() should not change createdBy", _model1.getCreatedBy(), _model2.getCreatedBy());
// timing issue: in order to test the following, we needed to introduce a sleep, what we do not want to do
//assertThat(_model2.getModifiedAt().toString(), not(equalTo(_model2.getCreatedAt().toString())));
// TODO: in our case, the modifying user will be the same; how can we test, that modifiedBy really changed ?
// assertThat(_rm2.getModifiedBy(), not(equalTo(_rm2.getCreatedBy())));
// client-side generated createdBy, createdAt, modifiedBy, modifiedAt should be ignored
String _createdBy = _model1.getCreatedBy();
Date _createdAt = _model1.getCreatedAt();
String _modifiedBy = _model1.getModifiedBy();
Date _modifiedAt = _model1.getModifiedAt();
_model1.setCreatedBy("testModifications2");
_model1.setCreatedAt(new Date(1000));
_model1.setModifiedBy("BLA");
_model1.setModifiedAt(new Date(2000));
// client-side generated createdBy should be ignored -> no Validation errors expected
RateModel _model3 = put(_model1, Status.OK);
assertEquals("client-side generated createdBy should be ignored", _createdBy, _model3.getCreatedBy());
assertEquals("client-side generated createdAt should be ignored", _createdAt, _model3.getCreatedAt());
// assertThat(_model1.getModifiedAt(), not(equalTo(_model3.getModifiedAt()))); timing issue, too short, don't want to introduce sleeps
assertThat(_model1.getModifiedBy(), not(equalTo(_model3.getModifiedBy())));
// reset
_model1.setCreatedBy(_createdBy);
_model1.setCreatedAt(_createdAt);
_model1.setModifiedAt(_modifiedAt);
_model1.setModifiedBy(_modifiedBy);
delete(_model1.getId(), Status.NO_CONTENT);
}
/********************************* helper methods *********************************/
/**
* Retrieve a list of all RateModel elements from RatesService by executing a HTTP GET request.
* @param query the URL query to use
* @param expectedStatus the expected HTTP status to test on
* @return a list of RateModel with all rates
*/
public List<RateModel> list(
String query,
Status expectedStatus)
{
return list(wc, query, -1, Integer.MAX_VALUE, expectedStatus);
}
/**
* Retrieve a list of RateModel from RatesService by executing a HTTP GET request.
* @param webClient the WebClient for the RatesService
* @param query the URL query to use
* @param position the position to start a batch with
* @param size the size of a batch
* @param expectedStatus the expected HTTP status to test on
* @return a List of RateModel objects in JSON format
*/
public static List<RateModel> list(
WebClient webClient,
String query,
int position,
int size,
Status expectedStatus) {
webClient.resetQuery();
webClient.replacePath("/");
Response _response = executeListQuery(webClient, query, position, size);
List<RateModel> _list = null;
if (expectedStatus != null) {
assertEquals("list() should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
_list = new ArrayList<RateModel>(webClient.getCollection(RateModel.class));
System.out.println("list(webClient, " + query + ", " + position + ", " + size + ", " + expectedStatus.toString() + ") ->" + _list.size());
}
return _list;
}
/**
* Create a new RateModel on the server by executing a HTTP POST request.
* @param model the data to post to the server
* @param exceptedStatus the expected HTTP status to test on
* @return the created data object
*/
public RateModel post(
RateModel model,
Status expectedStatus) {
return post(wc, model, expectedStatus);
}
/**
* Create a new RateModel on the server by executing a HTTP POST request.
* @param webClient the WebClient representing the service
* @param model the data to create on the server
* @param expectedStatus the expected HTTP status to test on
* @return the created data
*/
public static RateModel post(
WebClient webClient,
RateModel model,
Status expectedStatus) {
Response _response = webClient.replacePath("/").post(model);
if (expectedStatus != null) {
assertEquals("POST should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(RateModel.class);
} else {
return null;
}
}
/**
* Create a new RateModel on the server by executing a HTTP POST request.
* @param webClient the WebClient representing the RatesService
* @param title the title of the rate
* @param rate the rate amount
* @param currency the currency of the rate
* @param description a description
* @return
*/
public static RateModel create(
WebClient webClient,
String title,
int rate,
Currency currency,
String description)
{
RateModel _model = new RateModel();
_model.setTitle(title);
_model.setRate(rate);
_model.setCurrency(currency);
_model.setDescription(description);
return post(webClient, _model, Status.OK);
}
/**
* Read the RateModel with id from RatesService by executing a HTTP GET method.
* @param id the id of the RateModel to retrieve
* @param expectedStatus the expected HTTP status to test on
* @return the retrieved RateModel object in JSON format
*/
public RateModel get(String id, Status expectedStatus) {
return get(wc, id, expectedStatus);
}
/**
* Read the RateModel with id from RatesService by executing a HTTP GET method.
* @param rateWC the webclient of the RatesService
* @param id the id of the RateModel to retrieve
* @param expectedStatus the expected HTTP status to test on
* @return the retrieved RateModel object in JSON format
*/
public static RateModel get(WebClient rateWC, String id, Status expectedStatus) {
Response _response = rateWC.replacePath("/").path(id).get();
assertEquals("read() should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(RateModel.class);
} else {
return null;
}
}
/**
* Update the RateModel with id with new values.
* @param model the new data
* @param expectedStatus the expected HTTP status to test on
* @return the newly updated RateModel object in JSON format
*/
private RateModel put(
RateModel model,
Status expectedStatus) {
return put(wc, model, expectedStatus);
}
/**
* Update the RateModel with id with new values.
* @param webClient the webclient of the RatesService
* @param model the new data
* @param expectedStatus the expected HTTP status to test on
* @return the newly updated RateModel object in JSON format
*/
public static RateModel put(
WebClient webClient,
RateModel model,
Status expectedStatus) {
webClient.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
Response _response = webClient.replacePath("/").path(model.getId()).put(model);
assertEquals("update() should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(RateModel.class);
}
else {
return null;
}
}
/**
* Delete the RateModel with id on the RatesService by executing a HTTP DELETE method.
* @param id the id of the RateModel object to delete
* @param expectedStatus the expected HTTP status to test on
*/
public void delete(String rateId, Status expectedStatus) {
delete(wc, rateId, expectedStatus);
}
/**
* Delete the RateModel on the RatesService by executing a HTTP DELETE method.
* @param webClient the WebClient for the RatesService
* @param rateId the id of the RateModel object to delete
* @param expectedStatus the expected HTTP status to test on
*/
public static void delete(
WebClient webClient,
String rateId,
Status expectedStatus) {
Response _response = webClient.replacePath("/").path(rateId).delete();
assertEquals("DELETE should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
protected int calculateMembers() {
return 0;
}
}
|
922eef227597f8f85128d0cab2dfc27bc1a95b11 | 4,029 | java | Java | babycino/Method.java | farishanna/Babycino-Compiler | c0bd6d48993a42dc21c213055f1115a2e6a82118 | [
"MIT"
] | 1 | 2021-08-05T20:40:59.000Z | 2021-08-05T20:40:59.000Z | babycino/Method.java | farishanna/Babycino-Compiler | c0bd6d48993a42dc21c213055f1115a2e6a82118 | [
"MIT"
] | null | null | null | babycino/Method.java | farishanna/Babycino-Compiler | c0bd6d48993a42dc21c213055f1115a2e6a82118 | [
"MIT"
] | 1 | 2022-03-08T20:56:05.000Z | 2022-03-08T20:56:05.000Z | 32.232 | 101 | 0.620253 | 994,926 | package babycino;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
// A MiniJava method.
public class Method {
// The name of the method.
private String name;
// The return type of the method.
private Type ret;
// The parent class of the method.
private Class parent;
// The point in the parse tree where the class is defined.
private MiniJavaParser.MethodDeclarationContext ctx;
// A map of the method's local variable names and types.
private LinkedHashMap<String, Type> vars;
// A corresponding map of the method's local variable names and indices.
private HashMap<String, Integer> varidx;
// A map of the method's parameter names and types.
private LinkedHashMap<String, Type> params;
// At construction time, we need to know the name, return type, parent class
// and source location of the method.
public Method(String name, Type ret, Class parent, MiniJavaParser.MethodDeclarationContext ctx) {
// Save the passed parameters.
this.name = name;
this.ret = ret;
this.parent = parent;
this.ctx = ctx;
// Initialise the hashtables.
this.vars = new LinkedHashMap<String, Type>();
this.varidx = new HashMap<String, Integer>();
this.params = new LinkedHashMap<String, Type>();
// Add "this" as 1st variable, as it works as an implicit parameter,
// stored in vl0. Don't put it in params, or it would have to be
// passed in explicitly to method calls.
this.addVar("this", new Type(parent));
}
// Simple accessors:
// Return the name of the method.
public String getName() {
return this.name;
}
// Return the parse tree Context of this class.
public MiniJavaParser.MethodDeclarationContext getCtx() {
return this.ctx;
}
// Return the qualified name of the method (including class name).
public String getQualifiedName() {
return this.parent.getName() + "." + this.name;
}
// Return the return type of the method.
public Type getReturnType() {
return this.ret;
}
// Add and retrieve variables:
// Add a variable of a specific type to the method.
public void addVar(String name, Type type) {
this.varidx.put(name, this.vars.size());
this.vars.put(name, type);
}
// Check whether the method has a variable with a given name.
public boolean hasVar(String name) {
return this.vars.containsKey(name);
}
// Get the type of a named variable.
public Type getVarType(String name) {
// Note: During semantic analysis, this could be null if the variable
// had an invalid type. Use hasVar() to check existence of variables.
return this.vars.get(name);
}
// Get the index of a named variable.
public int getVarIndex(String name) {
return this.varidx.get(name);
}
// Add and retrieve parameters, which are also stored as variables:
// Add a parameter of a specific type to the method.
public void addParam(String name, Type type) {
this.params.put(name, type);
// Parameters are treated as local variables within the method body.
this.addVar(name, type);
}
// Get the EntrySet view of the parameters.
public Set<Map.Entry<String, Type>> getParams() {
return this.params.entrySet();
}
// Return the method signature as a string.
// Mainly used for debug info.
public String signature() {
String sig = " public " + this.ret.toString() + " " + this.name + "(";
boolean first = true;
for (Map.Entry e : this.params.entrySet()) {
if (first) {
first = false;
}
else {
sig += ", ";
}
sig += e.getValue().toString() + " " + e.getKey().toString();
}
sig += ");\n";
return sig;
}
}
|
922eef4fca980742a1f6d1f87da8fbfe02e92f43 | 285 | java | Java | src/main/java/ru/majordomo/hms/rc/user/api/DTO/stat/BaseResourceIdCount.java | 6d6a/hms-rc-user | f17c44376ba36a0b3ff8a8fa2db98b80971c3c89 | [
"Apache-2.0"
] | null | null | null | src/main/java/ru/majordomo/hms/rc/user/api/DTO/stat/BaseResourceIdCount.java | 6d6a/hms-rc-user | f17c44376ba36a0b3ff8a8fa2db98b80971c3c89 | [
"Apache-2.0"
] | null | null | null | src/main/java/ru/majordomo/hms/rc/user/api/DTO/stat/BaseResourceIdCount.java | 6d6a/hms-rc-user | f17c44376ba36a0b3ff8a8fa2db98b80971c3c89 | [
"Apache-2.0"
] | null | null | null | 20.357143 | 52 | 0.778947 | 994,927 | package ru.majordomo.hms.rc.user.api.DTO.stat;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class BaseResourceIdCount extends BaseCount {
private String resourceId;
private boolean active;
private String name;
}
|
922ef0c662026c855cb13466b36cc062a6c20e76 | 2,237 | java | Java | blade-service/blade-doc/src/main/java/org/springblade/doc/biaozhunhuamuban/mapper/BiaozhunhuawenjianMapper.java | huangyaping9455/SafetyStandards | 72e579db948a9f87026f415f20046a49b729b16c | [
"Apache-2.0"
] | null | null | null | blade-service/blade-doc/src/main/java/org/springblade/doc/biaozhunhuamuban/mapper/BiaozhunhuawenjianMapper.java | huangyaping9455/SafetyStandards | 72e579db948a9f87026f415f20046a49b729b16c | [
"Apache-2.0"
] | null | null | null | blade-service/blade-doc/src/main/java/org/springblade/doc/biaozhunhuamuban/mapper/BiaozhunhuawenjianMapper.java | huangyaping9455/SafetyStandards | 72e579db948a9f87026f415f20046a49b729b16c | [
"Apache-2.0"
] | 1 | 2021-07-05T09:14:57.000Z | 2021-07-05T09:14:57.000Z | 27.292683 | 144 | 0.737265 | 994,928 | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (ychag@example.com).
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springblade.doc.biaozhunhuamuban.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import feign.Param;
import org.springblade.doc.biaozhunhuamuban.entity.Biaozhunhuawenjian;
import org.springblade.doc.biaozhunhuamuban.vo.BiaozhunhuawenjianVO;
import java.util.List;
/**
* Mapper 接口
*
* @author th
* @since 2019-05-10
*/
public interface BiaozhunhuawenjianMapper extends BaseMapper<Biaozhunhuawenjian> {
/**
* 自定义分页
*
* @param page
* @param biaozhunhuawenjian
* @return
*/
List<BiaozhunhuawenjianVO> selectBiaozhunhuawenjianPage(IPage page, BiaozhunhuawenjianVO biaozhunhuawenjian);
BiaozhunhuawenjianVO selectPicPath(Integer biaozhunhuamubanId, Integer fileType);
/**
*逻辑删除文件
* @author: hyp
* @CreateDate2021-05-15 21:12
* @param mubanId
* @return: int
*/
int removeByMubanId(Integer mubanId);
/**
*根据模板id获取文件
* @author: hyp
* @CreateDate2021-05-15 21:18
* @param mubanId
* @return: java.util.List<org.springblade.anbiao.Biaozhunhuawenjian>
*/
List<Biaozhunhuawenjian> getByMubanId(Integer mubanId);
/**
*根据文件所属人查询文件路径
* @author: hyp
* @date: 2019/5/19 14:41
* @param fileProperty
* @param fileSuoshurenId
* @return: org.springblade.anbiao.BiaozhunhuawenjianVO
*/
BiaozhunhuawenjianVO selectPicPathBySuoshurenId(@Param("fileProperty") String fileProperty, @Param("fileSuoshurenId") Integer fileSuoshurenId);
/**
*更新记录
* @author: hyp
* @date: 2019/8/13 11:05
* @param id
* @return: int
*/
int updatePreviewRecordById(Integer id);
}
|
922ef171bd93033b882c6fdc0fbca1f6ea37acd1 | 1,929 | java | Java | src/test/java/fi/aalto/cs/apluscourses/presentation/ReplConfigurationFormModelTest.java | superseacat/intellij-plugin | 323cd9e89c3fc8fd62855f5673fbd9d5dfa4acd0 | [
"MIT"
] | null | null | null | src/test/java/fi/aalto/cs/apluscourses/presentation/ReplConfigurationFormModelTest.java | superseacat/intellij-plugin | 323cd9e89c3fc8fd62855f5673fbd9d5dfa4acd0 | [
"MIT"
] | null | null | null | src/test/java/fi/aalto/cs/apluscourses/presentation/ReplConfigurationFormModelTest.java | superseacat/intellij-plugin | 323cd9e89c3fc8fd62855f5673fbd9d5dfa4acd0 | [
"MIT"
] | 1 | 2021-02-26T07:45:06.000Z | 2021-02-26T07:45:06.000Z | 32.15 | 96 | 0.744946 | 994,929 | package fi.aalto.cs.apluscourses.presentation;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.fixtures.BasePlatformTestCase;
import fi.aalto.cs.apluscourses.TestHelper;
import java.util.List;
import org.junit.Test;
public class ReplConfigurationFormModelTest extends BasePlatformTestCase implements TestHelper {
@Test
public void testGetScalaModuleNamesWithNonJavaModuleReturnsEmpty() {
// given
Project project = getProject();
Module[] modules = ModuleManager.getInstance(project).getModules();
// when
List<String> moduleNames = ReplConfigurationFormModel.getScalaModuleNames(modules);
// then
assertEmpty(moduleNames);
}
@Test
public void testGetScalaModuleNamesWithJavaModuleReturnsModule() {
// given
Project project = getProject();
// Default project has only one module called:
String moduleName = "light_idea_test_case";
Module[] modules = ModuleManager.getInstance(project).getModules();
TestHelper.makeFirstPluginScalaModule(modules);
// when
List<String> moduleNames = ReplConfigurationFormModel.getScalaModuleNames(modules);
// then
assertEquals("Resulting filtered list contains the name of the module passed.",
moduleName, moduleNames.get(0));
}
@Test
public void testGetScalaModuleNamesWithNullTypedModuleReturnEmpty() {
// given
Project project = getProject();
Module[] modules = ModuleManager.getInstance(project).getModules();
Module module = modules[0];
// well, @NotNull is not always safe :D
String nullString = "nullString";
module.setModuleType(nullString);
nullString = null; // NOSONAR
// when
List<String> moduleNames = ReplConfigurationFormModel.getScalaModuleNames(modules);
// then
assertEmpty(moduleNames);
}
} |
922ef20845081334bd7362148f81b7fc282024ea | 1,204 | java | Java | geode-junit/src/main/java/org/apache/geode/cache/query/data/PhoneNo.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 1,475 | 2016-12-06T06:10:53.000Z | 2022-03-30T09:55:23.000Z | geode-junit/src/main/java/org/apache/geode/cache/query/data/PhoneNo.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 2,809 | 2016-12-06T19:24:26.000Z | 2022-03-31T22:02:20.000Z | geode-junit/src/main/java/org/apache/geode/cache/query/data/PhoneNo.java | Krishnan-Raghavan/geode | 708588659751c1213c467f5b200b2c36952af563 | [
"Apache-2.0",
"BSD-3-Clause"
] | 531 | 2016-12-06T05:48:47.000Z | 2022-03-31T23:06:37.000Z | 35.411765 | 100 | 0.738372 | 994,930 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.data;
import java.io.Serializable;
public class PhoneNo implements Serializable {
public int phoneNo1;
public int phoneNo2;
public int phoneNo3;
public int mobile;
/** Creates a new instance of PhoneNo */
public PhoneNo(int i, int j, int k, int m) {
this.phoneNo1 = i;
this.phoneNo2 = j;
this.phoneNo3 = k;
this.mobile = m;
}
}// end of class
|
922ef32988c3a07ba1ae71e07a60587561a1002c | 741 | java | Java | src/nl/natuurmonumenten/activiteiten/Provincie.java | mmbase/natmm | e87fc70ddb29519478edc0829d29758582827629 | [
"DOC",
"Unlicense"
] | null | null | null | src/nl/natuurmonumenten/activiteiten/Provincie.java | mmbase/natmm | e87fc70ddb29519478edc0829d29758582827629 | [
"DOC",
"Unlicense"
] | null | null | null | src/nl/natuurmonumenten/activiteiten/Provincie.java | mmbase/natmm | e87fc70ddb29519478edc0829d29758582827629 | [
"DOC",
"Unlicense"
] | null | null | null | 17.642857 | 54 | 0.614035 | 994,931 | package nl.natuurmonumenten.activiteiten;
import java.io.Serializable;
public class Provincie implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String naam;
private String omschrijving;
public Provincie() {
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
public String getOmschrijving() {
return omschrijving;
}
}
|
922ef3742c8abc0494e466b0ccf3c1ee73d506ab | 814 | java | Java | src/main/java/me/frosty/client/util/Logger.java | RubyCodesYT/SpectrumClient | b17cb2a9a8298d8bba66193b3806cc101d9c9617 | [
"MIT"
] | 10 | 2021-07-30T22:01:28.000Z | 2022-02-21T21:37:55.000Z | src/main/java/me/frosty/client/util/Logger.java | RubyCodesYT/SpectrumClient | b17cb2a9a8298d8bba66193b3806cc101d9c9617 | [
"MIT"
] | 2 | 2021-08-29T16:25:00.000Z | 2021-09-15T18:57:41.000Z | src/main/java/me/frosty/client/util/Logger.java | RubyCodesYT/SpectrumClient | b17cb2a9a8298d8bba66193b3806cc101d9c9617 | [
"MIT"
] | 6 | 2021-11-06T15:45:34.000Z | 2022-02-09T11:07:45.000Z | 23.257143 | 52 | 0.550369 | 994,932 | package me.frosty.client.util;
public class Logger {
/**
* Prints anything out with a tag.
*
* @param message The object you wish to print.
* @author frosty
*/
public static void info(Object message) {
System.out.println("[CLIENT] " + message);
}
/**
* Prints anything out with a tag.
*
* @param message The object you wish to print.
* @author frosty
*/
public static void warning(Object message) {
System.out.println("[CLIENT] " + message);
}
/**
* Prints anything out with a tag.
*
* @param message The object you wish to print.
* @author frosty
*/
public static void error(Object message) {
System.err.println("[CLIENT] " + message);
}
}
|
922ef3a89afc225852e7dbc8760340e4e970d994 | 1,201 | java | Java | kie-dmn/kie-dmn-model/src/main/java/org/kie/dmn/model/api/AssociationDirection.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 3,631 | 2017-03-14T08:54:05.000Z | 2022-03-31T19:59:10.000Z | kie-dmn/kie-dmn-model/src/main/java/org/kie/dmn/model/api/AssociationDirection.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 2,274 | 2017-03-13T14:02:17.000Z | 2022-03-28T17:23:17.000Z | kie-dmn/kie-dmn-model/src/main/java/org/kie/dmn/model/api/AssociationDirection.java | cuijulian/drools | 31b4dacd07ad962592dfb5ae6eee5cb825acce14 | [
"Apache-2.0"
] | 1,490 | 2017-03-14T11:37:37.000Z | 2022-03-31T08:50:22.000Z | 27.295455 | 75 | 0.648626 | 994,933 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.dmn.model.api;
public enum AssociationDirection {
NONE( "None" ),
ONE( "One" ),
BOTH( "Both" );
private final String value;
AssociationDirection( final String v ) {
value = v;
}
public String value() {
return value;
}
public static AssociationDirection fromValue( final String v ) {
for ( AssociationDirection c : AssociationDirection.values() ) {
if ( c.value.equals( v ) ) {
return c;
}
}
throw new IllegalArgumentException( v );
}
}
|
922ef45e61c7718f18c74bfaf781f2e078f79912 | 1,149 | java | Java | gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillEntity.java | zhifei-BF/guli-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | null | null | null | gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillEntity.java | zhifei-BF/guli-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | 3 | 2021-03-19T20:25:01.000Z | 2021-09-20T21:00:52.000Z | gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillEntity.java | zhifei-BF/guli-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | null | null | null | 14.185185 | 58 | 0.654482 | 994,934 | package com.atguigu.gmall.wms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 库存工作单
*
* @author helin
* @email envkt@example.com
* @date 2020-07-23 00:53:45
*/
@Data
@TableName("wms_ware_order_bill")
public class WareOrderBillEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* order_id
*/
private Long orderId;
/**
* order_sn
*/
private String orderSn;
/**
* 收货人
*/
private String consignee;
/**
* 收货人电话
*/
private String consigneeTel;
/**
* 配送地址
*/
private String deliveryAddress;
/**
* 订单备注
*/
private String orderComment;
/**
* 付款方式【 1:在线付款 2:货到付款】
*/
private Integer paymentWay;
/**
* 任务状态
*/
private Integer taskStatus;
/**
* 订单描述
*/
private String orderBody;
/**
* 物流单号
*/
private String trackingNo;
/**
* create_time
*/
private Date createTime;
/**
* 仓库id
*/
private Long wareId;
/**
* 工作单备注
*/
private String taskComment;
}
|
922ef4fbe8eaf0487968d1f5da0faddb2783b076 | 977 | java | Java | src/java/io/compgen/ngsutils/bam/filter/PairingSanityFilter.java | ngsutils/ngsutilsj | 628fa7e71d0a7ca3fc9da05a76b55d20689b4c10 | [
"BSD-3-Clause"
] | 4 | 2015-06-13T12:07:28.000Z | 2020-06-24T07:58:38.000Z | src/java/io/compgen/ngsutils/bam/filter/PairingSanityFilter.java | ngsutils/ngsutilsj | 628fa7e71d0a7ca3fc9da05a76b55d20689b4c10 | [
"BSD-3-Clause"
] | 5 | 2018-05-07T20:16:13.000Z | 2020-08-07T19:49:29.000Z | src/java/io/compgen/ngsutils/bam/filter/PairingSanityFilter.java | ngsutils/ngsutilsj | 628fa7e71d0a7ca3fc9da05a76b55d20689b4c10 | [
"BSD-3-Clause"
] | 1 | 2016-01-07T06:58:54.000Z | 2016-01-07T06:58:54.000Z | 26.405405 | 85 | 0.610031 | 994,935 |
package io.compgen.ngsutils.bam.filter;
import htsjdk.samtools.SAMRecord;
/**
* Makes sure reads are in reversed orientations and on the same chromosome.
*/
public class PairingSanityFilter extends AbstractBamFilter {
protected int flags = 0;
public PairingSanityFilter(BamFilter parent, boolean verbose) {
super(parent, verbose);
}
@Override
public boolean keepRead(SAMRecord read) {
if (read.getReadUnmappedFlag()) {
return false;
}
if (read.getMateUnmappedFlag()) {
return false;
}
if (!read.getReferenceName().equals(read.getMateReferenceName())) {
return false;
}
if (read.getReadNegativeStrandFlag() && read.getMateNegativeStrandFlag()) {
return false;
}
if (!read.getReadNegativeStrandFlag() && !read.getMateNegativeStrandFlag()) {
return false;
}
return true;
}
}
|
922ef541658de94131f416ef9fb2c28f5674fdcd | 278 | java | Java | src/java/ru/ifmo/genetics/distributed/io/writable/LongArrayWritable.java | ivartb/itmo-assembler | c3f12ed1a2da69daa8fcdfa501b1cec16aa8cc91 | [
"MIT"
] | 3 | 2019-05-14T14:34:22.000Z | 2022-01-14T07:34:40.000Z | src/java/ru/ifmo/genetics/distributed/io/writable/LongArrayWritable.java | ivartb/itmo-assembler | c3f12ed1a2da69daa8fcdfa501b1cec16aa8cc91 | [
"MIT"
] | 1 | 2019-09-09T07:37:06.000Z | 2019-09-09T07:37:06.000Z | src/java/ru/ifmo/genetics/distributed/io/writable/LongArrayWritable.java | ivartb/itmo-assembler | c3f12ed1a2da69daa8fcdfa501b1cec16aa8cc91 | [
"MIT"
] | 1 | 2019-09-06T14:52:09.000Z | 2019-09-06T14:52:09.000Z | 25.272727 | 55 | 0.741007 | 994,936 | package ru.ifmo.genetics.distributed.io.writable;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.LongWritable;
public class LongArrayWritable extends ArrayWritable {
public LongArrayWritable() {
super(LongWritable.class);
}
}
|
922ef5f5df62e9dc4969b4c2978fb41a82129624 | 1,754 | java | Java | Samples/cc-sample/app/src/main/java/tv/ouya/sample/cc/ButtonLegendView.java | razerofficial/java-razer-sdk | 382904d4fb7bd2b256fdd306b9e0541a48657a65 | [
"Apache-2.0"
] | 3 | 2016-10-17T02:20:43.000Z | 2018-09-23T23:53:52.000Z | Samples/cc-sample/app/src/main/java/tv/ouya/sample/cc/ButtonLegendView.java | razerofficial/java-razer-sdk | 382904d4fb7bd2b256fdd306b9e0541a48657a65 | [
"Apache-2.0"
] | null | null | null | Samples/cc-sample/app/src/main/java/tv/ouya/sample/cc/ButtonLegendView.java | razerofficial/java-razer-sdk | 382904d4fb7bd2b256fdd306b9e0541a48657a65 | [
"Apache-2.0"
] | null | null | null | 31.321429 | 102 | 0.663056 | 994,937 | package tv.ouya.sample.cc;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ButtonLegendView extends FrameLayout {
public ButtonLegendView(Context context) {
super(context);
init();
}
public ButtonLegendView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ButtonLegendView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
addView(View.inflate(getContext(), R.layout.button_legend, null));
LinearLayout list = (LinearLayout) findViewById(R.id.control_list);
for(Control c : Control.values()) {
final View v = View.inflate(getContext(), R.layout.item_control, null);
((TextView)v.findViewById(R.id.name)).setText(c.stringRes);
((ImageView)v.findViewById(R.id.icon)).setImageResource(c.buttonRes);
list.addView(v);
}
}
// Our OuyaController ButtonData doesn't currently include icons for generic L/R analog sticks.
// Once it does, you could alternatively use `OuyaController.getButtonData(button).buttonDrawable`
private enum Control {
MOVE(R.drawable.ic_dpad, R.string.move),
SCALE(R.drawable.ic_ls, R.string.scale),
ROTATE(R.drawable.ic_rs, R.string.rotate),
;
final public int buttonRes, stringRes;
Control(int button, int stringRes) {
this.buttonRes = button;
this.stringRes = stringRes;
}
}
}
|
922ef634a8f4cc36f48363f87aaf16043ea294b1 | 4,228 | java | Java | chapter_101/src/main/java/ru/alazarev/list/NodeList.java | AlekseyLazarev/job4j | c8579f469b79d43df15e542a5c7ce893dd322f66 | [
"Apache-2.0"
] | null | null | null | chapter_101/src/main/java/ru/alazarev/list/NodeList.java | AlekseyLazarev/job4j | c8579f469b79d43df15e542a5c7ce893dd322f66 | [
"Apache-2.0"
] | 6 | 2020-06-15T21:00:19.000Z | 2021-12-14T21:18:38.000Z | chapter_101/src/main/java/ru/alazarev/list/NodeList.java | AlekseyLazarev/job4j | c8579f469b79d43df15e542a5c7ce893dd322f66 | [
"Apache-2.0"
] | 1 | 2020-09-23T06:52:06.000Z | 2020-09-23T06:52:06.000Z | 24.439306 | 108 | 0.491958 | 994,938 | package ru.alazarev.list;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Class ContainerList решение задачи части 001. 5.3.2. Создать контейнер на базе связанного списка [#159].
*
* @author Aleksey Lazarev
* @since 07.12.2018
*/
public class NodeList<E> implements Iterable<E> {
private Node<E> first;
private int size = 0;
private int modCount = 0;
/**
* Check empty list.
*
* @return Result of check.
*/
public boolean checkEmpty() {
return this.first == null;
}
/**
* Get method for size.
*
* @return Size.
*/
public int getSize() {
return this.size;
}
/**
* Check array overflow.
*
* @param index Index for check.
* @throws IndexOutOfBoundsException
*/
public void checkOverflow(int index) throws IndexOutOfBoundsException {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException();
}
}
/**
* Method add value in list.
*
* @param value Value for add.
*/
public void add(E value) {
Node<E> newLink = new Node<>(value);
newLink.next = this.first;
this.first = newLink;
this.size++;
this.modCount++;
}
public Node<E> findNode(int position) {
Node<E> result = null;
if (!checkEmpty()) {
result = this.first;
for (int index = 0; index < position; index++) {
if (result.next != null) {
result = result.next;
}
}
}
return result;
}
/**
* Method delete upper element and return that.
*
* @return Deleted element.
*/
public E delete(int position) {
checkOverflow(position);
Node<E> previous, find;
E result = null;
if (!checkEmpty()) {
if (position == 0) {
result = first.data;
first = first.next;
} else {
previous = findNode(position - 1);
find = previous.next;
result = find.data;
previous.next = find.next;
}
this.size--;
this.modCount++;
}
return result;
}
/**
* Get element from list.
*
* @param position Element position.
* @return Element by this position.
*/
public E get(int position) {
E resultData = null;
checkOverflow(position);
if (!checkEmpty()) {
resultData = findNode(position).data;
}
return resultData;
}
/**
* Method create iterator.
*
* @return Iterator of E.
*/
public Iterator<E> iterator() {
return new Iterator<E>() {
private int expectedModCount = modCount;
private int size = getSize();
private int position = 0;
private Node<E> current = first;
/**
* Check has next element in list or not.
*
* @return true if has next element in list.
* @throws ConcurrentModificationException
*/
public boolean hasNext() {
if (expectedModCount != modCount) {
throw new ConcurrentModificationException();
}
return this.position < this.size;
}
/**
* Return next element in array.
*
* @return next element.
* @throws NoSuchElementException
*/
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E result = current.data;
current = current.next;
position++;
return result;
}
};
}
/**
* Storage date class.
*
* @param <E> Type element for storage.
*/
private static class Node<E> {
E data;
Node<E> next;
public Node(E data) {
this.data = data;
}
}
}
|
922ef6fd99346eef6a14ede3995438c72c6aa219 | 689 | java | Java | src/main/java/com/lielamar/lielsutils/hash/HashUtils.java | SadGhostYT/LielsUtils | 0abb2c8a06702de9656e47c591728eb9429ae2ea | [
"MIT"
] | 8 | 2020-10-25T12:56:15.000Z | 2021-11-10T19:45:28.000Z | src/main/java/com/lielamar/lielsutils/hash/HashUtils.java | SadGhostYT/LielsUtils | 0abb2c8a06702de9656e47c591728eb9429ae2ea | [
"MIT"
] | 2 | 2021-06-24T13:54:51.000Z | 2021-10-02T10:07:08.000Z | src/main/java/com/lielamar/lielsutils/hash/HashUtils.java | SadGhostYT/LielsUtils | 0abb2c8a06702de9656e47c591728eb9429ae2ea | [
"MIT"
] | 2 | 2021-06-24T13:37:13.000Z | 2021-09-30T11:38:58.000Z | 49.214286 | 163 | 0.809869 | 994,939 | package com.lielamar.lielsutils.hash;
import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
public class HashUtils {
public static String hashSHA256(String plain) throws NoSuchAlgorithmException { return Hashing.sha256().hashString(plain, StandardCharsets.UTF_8).toString(); }
public static String hashSHA384(String plain) throws NoSuchAlgorithmException { return Hashing.sha384().hashString(plain, StandardCharsets.UTF_8).toString(); }
public static String hashSHA512(String plain) throws NoSuchAlgorithmException { return Hashing.sha512().hashString(plain, StandardCharsets.UTF_8).toString(); }
}
|
922ef70a15162e0a4db261f7386297e4a77fd259 | 2,552 | java | Java | sandbox-providers/azurequeue/src/test/java/org/jclouds/azurequeue/options/GetOptionsTest.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | 1 | 2019-09-11T01:13:03.000Z | 2019-09-11T01:13:03.000Z | sandbox-providers/azurequeue/src/test/java/org/jclouds/azurequeue/options/GetOptionsTest.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | null | null | null | sandbox-providers/azurequeue/src/test/java/org/jclouds/azurequeue/options/GetOptionsTest.java | bosschaert/jclouds | f7576dfc697e54a68baf09967bccc8f708735992 | [
"Apache-2.0"
] | null | null | null | 33.220779 | 99 | 0.688819 | 994,940 | /**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <ychag@example.com>
*
* ====================================================================
* 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 org.jclouds.azurequeue.options;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
/**
* Tests behavior of {@code GetOptions}
*
* @author Adrian Cole
*/
@Test(groups = "unit")
public class GetOptionsTest {
public void testMaxMessages() {
GetOptions options = new GetOptions().maxMessages(1);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("numofmessages"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMaxMessagesTooSmall() {
new GetOptions().maxMessages(0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testMaxMessagesTooBig() {
new GetOptions().maxMessages(33);
}
public void testMaxMessagesStatic() {
GetOptions options = GetOptions.Builder.maxMessages(1);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("numofmessages"));
}
public void testVisibilityTimeout() {
GetOptions options = new GetOptions().visibilityTimeout(1);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("visibilitytimeout"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testVisibilityTimeoutTooSmall() {
new GetOptions().visibilityTimeout(0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testVisibilityTimeoutTooBig() {
new GetOptions().visibilityTimeout((2 * 60 * 60) + 1);
}
public void testVisibilityTimeoutStatic() {
GetOptions options = GetOptions.Builder.visibilityTimeout(1);
assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("visibilitytimeout"));
}
}
|
922ef78b89c0e36ee329a10ce472ed357d912077 | 2,148 | java | Java | Swing-ChatRooms2/src/com/company/contorller/RegisterController.java | 1122pcd1122/TheChatRoom | a317a5843548da763f63cfb2d8e8932d7b7ce814 | [
"Apache-2.0"
] | null | null | null | Swing-ChatRooms2/src/com/company/contorller/RegisterController.java | 1122pcd1122/TheChatRoom | a317a5843548da763f63cfb2d8e8932d7b7ce814 | [
"Apache-2.0"
] | null | null | null | Swing-ChatRooms2/src/com/company/contorller/RegisterController.java | 1122pcd1122/TheChatRoom | a317a5843548da763f63cfb2d8e8932d7b7ce814 | [
"Apache-2.0"
] | null | null | null | 32.059701 | 118 | 0.623836 | 994,941 | package com.company.contorller;
import com.company.server.RegisterServerImpl;
import com.company.server.server.RegisterServer;
import com.company.utils.FriendInfoUtil;
import com.company.views.RegisterFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author peichendong
*/
public class RegisterController {
private final RegisterFrame registerFrame;
private final RegisterServer registerServer;
public static void getRegisterController(){
new RegisterController();
}
public RegisterController() {
registerFrame = new RegisterFrame();
registerServer = new RegisterServerImpl();
registerFrame.registerButton.addActionListener(new RegisterListener());
}
/**
* 注册监听器
*/
class RegisterListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if (!registerFrame.passWordTextFiled.getText().equals(registerFrame.confirmPassWordTextFiled.getText())){
//说明注册信息
registerFrame.proInfoString("两次密码错误");
return;
}
FriendInfoUtil.getUser().setNickName(registerFrame.nickNameTextFiled.getText());
FriendInfoUtil.getUser().setPassWord(registerFrame.passWordTextFiled.getText());
FriendInfoUtil.getUser().setPhoneNumber(registerFrame.phoneTextFiled.getText());
if (registerFrame.buttonGroup.isSelected(registerFrame.boy.getModel())){
FriendInfoUtil.getUser().setSex("男");
}else {
FriendInfoUtil.getUser().setSex("女");
}
FriendInfoUtil.getUser().setEmail(registerFrame.emailTextFiled.getText());
boolean b = registerServer.registerIng(FriendInfoUtil.getUser());
System.out.println(b);
if (b){
//说明注册信息
registerFrame.proInfoString("注册成功");
}else{
//说明注册信息
registerFrame.proInfoString("注册失败");
}
}
}
}
|
922ef7a29713be2ab8f9a8bef3c8580a3b8c3826 | 1,718 | java | Java | chapter_001/src/main/java/ru/job4j/calculator/Calculator.java | IvanBelyaev/ibelyaev | 19825d9af098dca4aa73720efebe770f36314211 | [
"Apache-2.0"
] | null | null | null | chapter_001/src/main/java/ru/job4j/calculator/Calculator.java | IvanBelyaev/ibelyaev | 19825d9af098dca4aa73720efebe770f36314211 | [
"Apache-2.0"
] | 7 | 2020-07-01T19:09:48.000Z | 2022-03-31T21:12:31.000Z | chapter_001/src/main/java/ru/job4j/calculator/Calculator.java | IvanBelyaev/ibelyaev | 19825d9af098dca4aa73720efebe770f36314211 | [
"Apache-2.0"
] | null | null | null | 21.209877 | 61 | 0.673458 | 994,942 | package ru.job4j.calculator;
/**
* Calculator.
* @author Ivan Belyaev
* @since 17.06.2017
* @version 1.0
*/
public class Calculator {
/** Field stores the result of the calculation. */
private double result;
/**
* The method adds two numbers.
* @param first - first summand
* @param second - second summand
*/
public void add(double first, double second) {
this.result = first + second;
}
/**
* The method calculates the difference between two numbers.
* @param minuend - minuend
* @param subtrahend - subtrahend
*/
public void substruct(double minuend, double subtrahend) {
this.result = minuend - subtrahend;
}
/**
* The method calculates division of two numbers.
* @param dividend - dividend
* @param divisor - divisor
*/
public void div(double dividend, double divisor) {
this.result = dividend / divisor;
}
/**
* The method multiplies two numbers.
* @param first - first multiplicand
* @param second - second multiplicand
*/
public void multiple(double first, double second) {
this.result = first * second;
}
/**
* The method calculates the sine of a number.
* @param argument number
*/
public void sin(double argument) {
this.result = Math.sin(argument);
}
/**
* The method calculates the cosine of a number.
* @param argument number
*/
public void cos(double argument) {
this.result = Math.cos(argument);
}
/**
* The method calculates the tangent of a number.
* @param argument number
*/
public void tan(double argument) {
this.result = Math.tan(argument);
}
/**
* The method returns the result.
* @return returns the result of the calculation
*/
public double getResult() {
return this.result;
}
}
|
922ef9056569e8d048780d32170c0271f62a64f0 | 3,140 | java | Java | library/src/main/java/com/chiahaolu/library/LayoutUtil.java | chiahaolu/SettingItem | a333b8ca521ee2a8c5d5efca9838335349227511 | [
"Apache-2.0"
] | 1 | 2017-02-07T06:06:34.000Z | 2017-02-07T06:06:34.000Z | library/src/main/java/com/chiahaolu/library/LayoutUtil.java | chiahaolu/SettingItem | a333b8ca521ee2a8c5d5efca9838335349227511 | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/chiahaolu/library/LayoutUtil.java | chiahaolu/SettingItem | a333b8ca521ee2a8c5d5efca9838335349227511 | [
"Apache-2.0"
] | null | null | null | 33.404255 | 125 | 0.676115 | 994,943 | package com.chiahaolu.library;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.util.DisplayMetrics;
import android.view.Display;
import java.lang.reflect.Field;
/**
* Created by lujiahao
* Created at 2016/5/26 15:53
*/
public final class LayoutUtil {
private static int sWidthPixels;
private static int sHeightPixels;
/**
* Return real pixels represented by DIP
*
* @param context
* @param dp
* @return real pixels represented by DIP
*/
public static int getPixelByDIP(Context context, int dp) {
return (int) (context.getResources().getDisplayMetrics().density * dp + 0.5f);
}
public static int getDIPByPixel(Context context, int pixel) {
return (int) (pixel / context.getResources().getDisplayMetrics().density + 0.5f);
}
public static int getPixelBySP(Context context, int sp) {
//return (int) (context.getResources().getDisplayMetrics().scaledDensity * sp);
return (int) (context.getResources().getDisplayMetrics().scaledDensity * sp + 0.5f);
}
public static int getSpByPixel(Context context, int pixel){
return (int) (pixel / context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
}
public static void unLockScreenRotation(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
public static void setScreenRotation(Activity activity, boolean isLand) {
if (isLand)
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static void lockScreenRotaion(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
activity.setRequestedOrientation(display.getWidth() > display.getHeight() ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static int getStatusBarHeight(Context context) {
Class<?> c;
Object obj;
Field field;
int x;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
return context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
return -1;
}
}
public static int getScreenWidth(Context context) {
getResolution(context);
return Math.min(sWidthPixels, sHeightPixels);
}
private static void getResolution(Context context) {
DisplayMetrics display = context.getResources().getDisplayMetrics();
sWidthPixels = display.widthPixels;
sHeightPixels = display.heightPixels;
}
public static int getScreenHeight(Context context) {
getResolution(context);
return Math.max(sWidthPixels, sHeightPixels);
}
}
|
922ef90f0edc929cdfea43e039875bd2701e9949 | 305 | java | Java | IntelliJ/src/com/rrvrafael/cursojava/aula11/VariaveisChar.java | rrv-rafael/curso-java-basico | 5e32088e854ae21d8446b4600034071e476cef84 | [
"MIT"
] | null | null | null | IntelliJ/src/com/rrvrafael/cursojava/aula11/VariaveisChar.java | rrv-rafael/curso-java-basico | 5e32088e854ae21d8446b4600034071e476cef84 | [
"MIT"
] | null | null | null | IntelliJ/src/com/rrvrafael/cursojava/aula11/VariaveisChar.java | rrv-rafael/curso-java-basico | 5e32088e854ae21d8446b4600034071e476cef84 | [
"MIT"
] | null | null | null | 19.0625 | 54 | 0.537705 | 994,944 | package com.rrvrafael.cursojava.aula11;
public class VariaveisChar {
public static void main(String[] args) {
//char o = 'o';
//char i = 'i';
char o = 111;
char i = 105;
char interrogacao = 63;
System.out.println("" + o + i + interrogacao);
}
} |
922ef91a1ab3df47bcef08995d18af7a284b27a8 | 6,760 | java | Java | thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/anomaly/alert/v2/AlertJobRunnerV2.java | hufman/incubator-pinot | 8a231a636dd3c3a12740a4082ae04d67730171d2 | [
"Apache-2.0"
] | 2 | 2019-03-25T23:42:42.000Z | 2019-04-01T23:07:01.000Z | thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/anomaly/alert/v2/AlertJobRunnerV2.java | hufman/incubator-pinot | 8a231a636dd3c3a12740a4082ae04d67730171d2 | [
"Apache-2.0"
] | 23 | 2019-04-01T23:23:33.000Z | 2019-07-21T13:16:31.000Z | thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/anomaly/alert/v2/AlertJobRunnerV2.java | hufman/incubator-pinot | 8a231a636dd3c3a12740a4082ae04d67730171d2 | [
"Apache-2.0"
] | null | null | null | 42.78481 | 117 | 0.756361 | 994,945 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pinot.thirdeye.anomaly.alert.v2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.pinot.thirdeye.anomaly.alert.AlertJobContext;
import org.apache.pinot.thirdeye.anomaly.alert.AlertTaskInfo;
import org.apache.pinot.thirdeye.anomaly.job.JobConstants;
import org.apache.pinot.thirdeye.anomaly.task.TaskConstants;
import org.apache.pinot.thirdeye.anomaly.task.TaskGenerator;
import org.apache.pinot.thirdeye.datalayer.bao.AlertConfigManager;
import org.apache.pinot.thirdeye.datalayer.bao.JobManager;
import org.apache.pinot.thirdeye.datalayer.bao.TaskManager;
import org.apache.pinot.thirdeye.datalayer.dto.AlertConfigDTO;
import org.apache.pinot.thirdeye.datalayer.dto.JobDTO;
import org.apache.pinot.thirdeye.datalayer.dto.TaskDTO;
import org.apache.pinot.thirdeye.datasource.DAORegistry;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AlertJobRunnerV2 implements Job {
private static final Logger LOG = LoggerFactory.getLogger(AlertJobRunnerV2.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final String ALERT_JOB_CONTEXT_V2 = "ALERT_JOB_CONTEXT_V2";
public static final String ALERT_JOB_MONITORING_WINDOW_START_TIME = "ALERT_JOB_MONITORING_WINDOW_START_TIME";
public static final String ALERT_JOB_MONITORING_WINDOW_END_TIME = "ALERT_JOB_MONITORING_WINDOW_END_TIME";
private JobManager jobDAO = DAORegistry.getInstance().getJobDAO();
private TaskManager taskDAO = DAORegistry.getInstance().getTaskDAO();
private AlertConfigManager alertConfigDAO = DAORegistry.getInstance().getAlertConfigDAO();
private TaskGenerator taskGenerator;
private AlertJobContext alertJobContext;
public AlertJobRunnerV2() {
taskGenerator = new TaskGenerator();
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
LOG.info("Running " + jobExecutionContext.getJobDetail().getKey().toString());
alertJobContext = (AlertJobContext) jobExecutionContext.getJobDetail().getJobDataMap().get(ALERT_JOB_CONTEXT_V2);
long alertConfigId = alertJobContext.getAlertConfigId();
AlertConfigDTO alertConfig = alertConfigDAO.findById(alertConfigId);
if (alertConfig == null) {
LOG.error("Alert config with id {} does not exist", alertConfigId);
} else {
alertJobContext.setAlertConfigDTO(alertConfig);
DateTime monitoringWindowStartTime =
(DateTime) jobExecutionContext.getJobDetail().getJobDataMap().get(ALERT_JOB_MONITORING_WINDOW_START_TIME);
DateTime monitoringWindowEndTime =
(DateTime) jobExecutionContext.getJobDetail().getJobDataMap().get(ALERT_JOB_MONITORING_WINDOW_END_TIME);
// TODO :remove this monitoring window logic; alert v2 is not based on monitoring window.
// Compute window end
if (monitoringWindowEndTime == null) {
Date scheduledFireTime = jobExecutionContext.getScheduledFireTime();
monitoringWindowEndTime = new DateTime(scheduledFireTime);
}
// Compute window start according to window end
if (monitoringWindowStartTime == null) {
monitoringWindowStartTime = monitoringWindowEndTime;
}
// write to alert_jobs
Long jobExecutionId = createJob(monitoringWindowStartTime, monitoringWindowEndTime);
alertJobContext.setJobExecutionId(jobExecutionId);
// write to alert_tasks
List<Long> taskIds = createTasks(monitoringWindowStartTime, monitoringWindowEndTime);
LOG.info("Alert V2 tasks created : {}", taskIds);
}
}
private long createJob(DateTime monitoringWindowStartTime, DateTime monitoringWindowEndTime) {
Long jobExecutionId = null;
try {
JobDTO jobSpec = new JobDTO();
jobSpec.setJobName(alertJobContext.getJobName());
jobSpec.setConfigId(alertJobContext.getAlertConfigId());
jobSpec.setWindowStartTime(monitoringWindowStartTime.getMillis());
jobSpec.setWindowEndTime(monitoringWindowEndTime.getMillis());
jobSpec.setScheduleStartTime(System.currentTimeMillis());
jobSpec.setStatus(JobConstants.JobStatus.SCHEDULED);
jobSpec.setTaskType(TaskConstants.TaskType.ALERT2);
jobExecutionId = jobDAO.save(jobSpec);
LOG.info("Created alert job {} with jobExecutionId {}", jobSpec, jobExecutionId);
} catch (Exception e) {
LOG.error("Exception in creating alert job", e);
}
return jobExecutionId;
}
private List<Long> createTasks(DateTime monitoringWindowStartTime, DateTime monitoringWindowEndTime) {
List<Long> taskIds = new ArrayList<>();
try {
List<AlertTaskInfo> tasks = taskGenerator
.createAlertTasksV2(alertJobContext, monitoringWindowStartTime, monitoringWindowEndTime);
for (AlertTaskInfo taskInfo : tasks) {
String taskInfoJson = null;
try {
taskInfoJson = OBJECT_MAPPER.writeValueAsString(taskInfo);
} catch (JsonProcessingException e) {
LOG.error("Exception when converting AlertTaskInfo {} to jsonString", taskInfo, e);
}
TaskDTO taskSpec = new TaskDTO();
taskSpec.setTaskType(TaskConstants.TaskType.ALERT2);
taskSpec.setJobName(alertJobContext.getJobName());
taskSpec.setStatus(TaskConstants.TaskStatus.WAITING);
taskSpec.setTaskInfo(taskInfoJson);
taskSpec.setJobId(alertJobContext.getJobExecutionId());
long taskId = taskDAO.save(taskSpec);
taskIds.add(taskId);
LOG.info("Created alert task {} with taskId {}", taskSpec, taskId);
}
} catch (Exception e) {
LOG.error("Exception in creating alert tasks", e);
}
return taskIds;
}
}
|
922ef95cb7957ff276e86cb51f91261b65a8a942 | 363 | java | Java | src/main/java/com/fcefyn/boardgameframework/components/tile/TileModel.java | nicolaspapp/BoardGameFramework | 0a81978632033e12c822ed886a6afe88966efaec | [
"MIT"
] | null | null | null | src/main/java/com/fcefyn/boardgameframework/components/tile/TileModel.java | nicolaspapp/BoardGameFramework | 0a81978632033e12c822ed886a6afe88966efaec | [
"MIT"
] | null | null | null | src/main/java/com/fcefyn/boardgameframework/components/tile/TileModel.java | nicolaspapp/BoardGameFramework | 0a81978632033e12c822ed886a6afe88966efaec | [
"MIT"
] | null | null | null | 24.266667 | 63 | 0.763736 | 994,946 | package com.fcefyn.boardgameframework.components.tile;
import com.almasb.fxgl.entity.components.ObjectComponent;
import com.fcefyn.boardgameframework.components.tile.TileValue;
/**
* @author Almas Baimagambetov (hzdkv@example.com)
*/
public class TileModel extends ObjectComponent<TileValue> {
public TileModel() {
super(TileValue.NONE);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.