hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
ebbc568fd7b8acd37da0465de6d21dcb2a4c8f9a
17,704
package com.theyapps.ccstreamviewer.entity; import com.theyapps.ccstreamviewer.views.VideoPanel; import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import uk.co.caprica.vlcj.player.MediaPlayerFactory; import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer; import uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface; import java.awt.*; /** * Models the monitor object from zoneminder */ public class ZMMonitor { Logger log = Logger.getLogger(ZMMonitor.class); private int id; private String name; private int serverId; private String type; private String function; private int enabled; private String linkedMonitors; private String triggers; private String device; private int channel; private int format; private boolean V4LMultiBuffer; private int V4LCapturePerFrame; private String protocol; private String method; private String host; private String port; private String subPath; private String path; private String options; private String user; private String pass; private int width; private int height; private int colours; private int palette; private int orientation; private int deinterlacing; private boolean rtspDescribe; private int brightness; private int contrast; private int hue; private int color; private String eventPrefix; private String labelFormat; private int labelX; private int labelY; private int labelSize; private int imageBufferCount; private int warmupCount; private int preEventCount; private int postEventCount; private int streamReplayBuffer; private int alarmFrameCount; private int sectionLength; private int frameSkip; private int motionFrameSkip; private float analysisFPS; private int analysisUpdateDelay; private float maxFPS; private float alarmMaxFPS; private int FPSReportInterval; private int refBlendPerc; private int alarmRefBlendPerc; private int controllable; private int controlID; private String controlDevice; private String controlAddress; private int autoStopTimeout; private int trackMotion; private int trackDelay; private int returnLocation; private int returnDelay; private String defaultView; private int defaultRate; private int defaultScale; private String signalCheckColour; private String webColour; private boolean exif; private int sequence; public ZMMonitor(JSONObject jo) { try { setId(jo.getInt("Id")); setName(jo.getString("Name")); setServerId(jo.getInt("ServerId")); setType(jo.getString("Type")); setFunction(jo.getString("Function")); setEnabled(jo.getInt("Enabled")); setLinkedMonitors(jo.getString("LinkedMonitors")); setTriggers(jo.getString("Triggers")); setDevice(jo.getString("Device")); setChannel(jo.getInt("Channel")); setFormat(jo.getInt("Format")); setV4LMultiBuffer(jo.getBoolean("V4LMultiBuffer")); setV4LCapturePerFrame(jo.getInt("V4LCapturesPerFrame")); setProtocol(jo.getString("Protocol")); setMethod(jo.getString("Method")); setHost(jo.getString("Host")); setPort(jo.getString("Port")); setSubPath(jo.getString("SubPath")); setPath(jo.getString("Path")); setOptions(jo.getString("Options")); setUser(jo.getString("User")); setPass(jo.getString("Pass")); setWidth(jo.getInt("Width")); setHeight(jo.getInt("Height")); setColours(jo.getInt("Colours")); setPalette(jo.getInt("Palette")); setOrientation(jo.getInt("Orientation")); setDeinterlacing(jo.getInt("Deinterlacing")); setRtspDescribe(jo.getBoolean("RTSPDescribe")); setBrightness(jo.getInt("Brightness")); setContrast(jo.getInt("Contrast")); setHue(jo.getInt("Hue")); setColor(jo.getInt("Colour")); setEventPrefix(jo.getString("EventPrefix")); setLabelFormat(jo.getString("LabelFormat")); setLabelX(jo.getInt("LabelX")); setLabelY(jo.getInt("LabelY")); setLabelSize(jo.getInt("LabelSize")); setImageBufferCount(jo.getInt("ImageBufferCount")); setWarmupCount(jo.getInt("WarmupCount")); setPreEventCount(jo.getInt("PreEventCount")); setPostEventCount(jo.getInt("PostEventCount")); setStreamReplayBuffer(jo.getInt("StreamReplayBuffer")); setAlarmFrameCount(jo.getInt("AlarmFrameCount")); setSectionLength(jo.getInt("SectionLength")); setFrameSkip(jo.getInt("FrameSkip")); setMotionFrameSkip(jo.getInt("MotionFrameSkip")); setAnalysisFPS(jo.getFloat("AnalysisFPS")); setAnalysisUpdateDelay(jo.getInt("AnalysisUpdateDelay")); setMaxFPS(jo.getFloat("MaxFPS")); setAlarmMaxFPS(jo.getFloat("AlarmMaxFPS")); setFPSReportInterval(jo.getInt("FPSReportInterval")); setRefBlendPerc(jo.getInt("RefBlendPerc")); setAlarmRefBlendPerc(jo.getInt("AlarmRefBlendPerc")); setControllable(jo.getInt("Controllable")); setControlID(jo.getInt("ControlId")); setControlDevice(String.valueOf(jo.get("ControlDevice"))); setControlAddress(String.valueOf(jo.get("ControlAddress"))); setTrackMotion(Integer.valueOf(String.valueOf(jo.get("TrackMotion")))); setTrackDelay(jo.getInt("TrackDelay")); setReturnLocation(jo.getInt("ReturnLocation")); setReturnDelay(jo.getInt("ReturnDelay")); setDefaultView(jo.getString("DefaultView")); setDefaultRate(jo.getInt("DefaultRate")); setDefaultScale(jo.getInt("DefaultScale")); setSignalCheckColour(jo.getString("SignalCheckColour")); setWebColour(jo.getString("WebColour")); setExif(jo.getBoolean("Exif")); setSequence(jo.getInt("Sequence")); } catch (JSONException e) { log.error("Some properties may have failed to load from JSON."); e.printStackTrace(); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getServerId() { return serverId; } public void setServerId(int serverId) { this.serverId = serverId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getFunction() { return function; } public void setFunction(String function) { this.function = function; } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { this.enabled = enabled; } public String getLinkedMonitors() { return linkedMonitors; } public void setLinkedMonitors(String linkedMonitors) { this.linkedMonitors = linkedMonitors; } public String getTriggers() { return triggers; } public void setTriggers(String triggers) { this.triggers = triggers; } public int getChannel() { return channel; } public void setChannel(int channel) { this.channel = channel; } public int getFormat() { return format; } public void setFormat(int format) { this.format = format; } public boolean isV4LMultiBuffer() { return V4LMultiBuffer; } public void setV4LMultiBuffer(boolean v4LMultiBuffer) { V4LMultiBuffer = v4LMultiBuffer; } public int getV4LCapturePerFrame() { return V4LCapturePerFrame; } public void setV4LCapturePerFrame(int v4LCapturePerFrame) { V4LCapturePerFrame = v4LCapturePerFrame; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getSubPath() { return subPath; } public void setSubPath(String subPath) { this.subPath = subPath; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getOptions() { return options; } public void setOptions(String options) { this.options = options; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getColours() { return colours; } public void setColours(int colours) { this.colours = colours; } public int getPalette() { return palette; } public void setPalette(int palette) { this.palette = palette; } public int getOrientation() { return orientation; } public void setOrientation(int orientation) { this.orientation = orientation; } public int getDeinterlacing() { return deinterlacing; } public void setDeinterlacing(int deinterlacing) { this.deinterlacing = deinterlacing; } public boolean isRtspDescribe() { return rtspDescribe; } public void setRtspDescribe(boolean rtspDescribe) { this.rtspDescribe = rtspDescribe; } public int getBrightness() { return brightness; } public void setBrightness(int brightness) { this.brightness = brightness; } public int getContrast() { return contrast; } public void setContrast(int contrast) { this.contrast = contrast; } public int getHue() { return hue; } public void setHue(int hue) { this.hue = hue; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getEventPrefix() { return eventPrefix; } public void setEventPrefix(String eventPrefix) { this.eventPrefix = eventPrefix; } public String getLabelFormat() { return labelFormat; } public void setLabelFormat(String labelFormat) { this.labelFormat = labelFormat; } public int getLabelX() { return labelX; } public void setLabelX(int labelX) { this.labelX = labelX; } public int getLabelY() { return labelY; } public void setLabelY(int labelY) { this.labelY = labelY; } public int getLabelSize() { return labelSize; } public void setLabelSize(int labelSize) { this.labelSize = labelSize; } public int getImageBufferCount() { return imageBufferCount; } public void setImageBufferCount(int imageBufferCount) { this.imageBufferCount = imageBufferCount; } public int getWarmupCount() { return warmupCount; } public void setWarmupCount(int warmupCount) { this.warmupCount = warmupCount; } public int getPreEventCount() { return preEventCount; } public void setPreEventCount(int preEventCount) { this.preEventCount = preEventCount; } public int getPostEventCount() { return postEventCount; } public void setPostEventCount(int postEventCount) { this.postEventCount = postEventCount; } public int getStreamReplayBuffer() { return streamReplayBuffer; } public void setStreamReplayBuffer(int streamReplayBuffer) { this.streamReplayBuffer = streamReplayBuffer; } public int getAlarmFrameCount() { return alarmFrameCount; } public void setAlarmFrameCount(int alarmFrameCount) { this.alarmFrameCount = alarmFrameCount; } public int getSectionLength() { return sectionLength; } public void setSectionLength(int sectionLength) { this.sectionLength = sectionLength; } public int getFrameSkip() { return frameSkip; } public void setFrameSkip(int frameSkip) { this.frameSkip = frameSkip; } public int getMotionFrameSkip() { return motionFrameSkip; } public void setMotionFrameSkip(int motionFrameSkip) { this.motionFrameSkip = motionFrameSkip; } public float getAnalysisFPS() { return analysisFPS; } public void setAnalysisFPS(float analysisFPS) { this.analysisFPS = analysisFPS; } public int getAnalysisUpdateDelay() { return analysisUpdateDelay; } public void setAnalysisUpdateDelay(int analysisUpdateDelay) { this.analysisUpdateDelay = analysisUpdateDelay; } public float getMaxFPS() { return maxFPS; } public void setMaxFPS(float maxFPS) { this.maxFPS = maxFPS; } public float getAlarmMaxFPS() { return alarmMaxFPS; } public void setAlarmMaxFPS(float alarmMaxFPS) { this.alarmMaxFPS = alarmMaxFPS; } public int getFPSReportInterval() { return FPSReportInterval; } public void setFPSReportInterval(int FPSReportInterval) { this.FPSReportInterval = FPSReportInterval; } public int getRefBlendPerc() { return refBlendPerc; } public void setRefBlendPerc(int refBlendPerc) { this.refBlendPerc = refBlendPerc; } public int getAlarmRefBlendPerc() { return alarmRefBlendPerc; } public void setAlarmRefBlendPerc(int alarmRefBlendPerc) { this.alarmRefBlendPerc = alarmRefBlendPerc; } public int getControllable() { return controllable; } public void setControllable(int controllable) { this.controllable = controllable; } public int getControlID() { return controlID; } public void setControlID(int controlID) { this.controlID = controlID; } public String getControlDevice() { return controlDevice; } public void setControlDevice(String controlDevice) { this.controlDevice = controlDevice; } public String getControlAddress() { return controlAddress; } public void setControlAddress(String controllAddress) { this.controlAddress = controllAddress; } public int getAutoStopTimeout() { return autoStopTimeout; } public void setAutoStopTimeout(int autoStopTimeout) { this.autoStopTimeout = autoStopTimeout; } public int getTrackMotion() { return trackMotion; } public void setTrackMotion(int trackMotion) { this.trackMotion = trackMotion; } public int getReturnLocation() { return returnLocation; } public void setReturnLocation(int returnLocation) { this.returnLocation = returnLocation; } public int getReturnDelay() { return returnDelay; } public void setReturnDelay(int returnDelay) { this.returnDelay = returnDelay; } public String getDefaultView() { return defaultView; } public void setDefaultView(String defaultView) { this.defaultView = defaultView; } public int getDefaultRate() { return defaultRate; } public void setDefaultRate(int defaultRate) { this.defaultRate = defaultRate; } public int getDefaultScale() { return defaultScale; } public void setDefaultScale(int defaultScale) { this.defaultScale = defaultScale; } public String getSignalCheckColour() { return signalCheckColour; } public void setSignalCheckColour(String signalCheckColour) { this.signalCheckColour = signalCheckColour; } public String getWebColour() { return webColour; } public void setWebColour(String webColour) { this.webColour = webColour; } public boolean isExif() { return exif; } public void setExif(boolean exif) { this.exif = exif; } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public int getTrackDelay() { return trackDelay; } public void setTrackDelay(int trackDelay) { this.trackDelay = trackDelay; } }
24.285322
83
0.629123
8ef973506055ce15291c4d98e062e129638dbf8e
3,183
/* * Copyright 2009 Inspire-Software.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.yes.cart.bulkcommon.service.support.common.impl; import org.apache.commons.lang.StringEscapeUtils; import org.yes.cart.bulkcommon.model.ImpExDescriptor; import org.yes.cart.bulkcommon.model.ImpExTuple; import org.yes.cart.bulkcommon.service.support.query.LookUpQuery; import org.yes.cart.bulkcommon.service.support.query.LookUpQueryParameterStrategy; import org.yes.cart.bulkcommon.service.support.query.impl.NativeSQLQuery; import java.util.ArrayList; import java.util.List; /** * Generates a native sql string with all parameter placeholders replaced. * No parameter object is available, just plain sql string. * * User: denispavlov * Date: 12-08-08 * Time: 9:22 AM */ public class ImpExDescriptorNativeInsertStrategy extends AbstractByParameterByColumnNameStrategy<ImpExDescriptor, ImpExTuple, Object> implements LookUpQueryParameterStrategy<ImpExDescriptor, ImpExTuple, Object> { @Override protected boolean addParameter(final int index, final boolean wrappedInQuotes, final Object param, final StringBuilder query, final List<Object> params) { if (param == null) { if (!wrappedInQuotes && query.charAt(query.length() - 1) != '#') { query.append("NULL"); } else if (wrappedInQuotes) { query.append("''"); } // else part of I18N so just leave empty } else { if (!wrappedInQuotes) { query.append(StringEscapeUtils.escapeSql(String.valueOf(param))); } else { // String values must be sent as parameters as they may include special characters query.append('?').append(index); params.add(param); return true; } } return false; } /** {@inheritDoc} */ @Override public LookUpQuery getQuery(final ImpExDescriptor descriptor, final Object masterObject, final ImpExTuple tuple, final Object adapter, final String queryTemplate) { final StringBuilder sql = new StringBuilder(); final List params = new ArrayList(); replaceColumnNamesInTemplate(queryTemplate, sql, params, descriptor, masterObject, tuple, adapter); return new NativeSQLQuery(sql.toString(), params.toArray()); } }
40.291139
133
0.633051
6a0b89e784c08584f7aa553300dc6416b378219b
2,637
package com.example.mywiki.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.mywiki.domain.Category; import com.example.mywiki.mapper.CategoryMapper; import com.example.mywiki.request.CategoryQueryReq; import com.example.mywiki.request.CategorySaveReq; import com.example.mywiki.response.CategoryQueryResp; import com.example.mywiki.response.PageResp; import com.example.mywiki.utils.CopyUtil; import com.example.mywiki.utils.SnowFlake; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; /** * Category服务:查询、新增、保存 * Created by [email protected] on 2021/06/04 */ @Service public class CategoryService { @Resource private CategoryMapper categoryMapper; @Resource private SnowFlake snowFlake; /** * Category查询方法 * @param req * @return */ public PageResp<CategoryQueryResp> search(CategoryQueryReq req) { List<Category> categories = new ArrayList<>(); QueryWrapper<Category> queryWrapper = new QueryWrapper<>(); Page<Category> categoryPage = new Page<>(req.getPage(), req.getSize()); categories = categoryMapper.selectList(null); //将List<Category>转换为List<CategoryResp> List<CategoryQueryResp> respList = CopyUtil.copyList(categories, CategoryQueryResp.class); //获取分页信息,将total和List给pageResp PageResp<CategoryQueryResp> pageResp = new PageResp<>(); pageResp.setTotal(categoryPage.getTotal()); pageResp.setList(respList); return pageResp; } /** * Category保存save,传入的id无值是新增,id有值是更新 * @param saveReq */ public void save(CategorySaveReq saveReq){ Category category = CopyUtil.copy(saveReq, Category.class); if (ObjectUtils.isEmpty(saveReq.getId())){ category.setId(snowFlake.nextId()); categoryMapper.insert(category); }else { categoryMapper.updateById(category); } } /** * Category删除 * @param id */ public void delete(Long id){ categoryMapper.deleteById(id); } /** * Category一次查全部分类 * @param * @return */ public List<CategoryQueryResp> all() { List<Category> categoryList = categoryMapper.selectList(null); //将List<Category>转换为List<CategoryResp> List<CategoryQueryResp> respList = CopyUtil.copyList(categoryList, CategoryQueryResp.class); return respList; } }
28.354839
100
0.69397
096546cd375bb9c9f343253ecab971a5ab5d7a60
4,702
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.media; import android.os.Bundle; import android.support.v4.os.ResultReceiver; import android.util.Log; // Referenced classes of package android.support.v4.media: // MediaBrowserCompat private static class MediaBrowserCompat$CustomActionResultReceiver extends ResultReceiver { protected void a(int i, Bundle bundle) { if(f == null) //* 0 0:aload_0 //* 1 1:getfield #17 <Field MediaBrowserCompat$c f> //* 2 4:ifnonnull 8 return; // 3 7:return switch(i) //* 4 8:iload_1 { //* 5 9:tableswitch -1 1: default 36 // -1 138 // 0 121 // 1 104 default: StringBuilder stringbuilder = new StringBuilder(); // 6 36:new #19 <Class StringBuilder> // 7 39:dup // 8 40:invokespecial #23 <Method void StringBuilder()> // 9 43:astore_3 stringbuilder.append("Unknown result code: "); // 10 44:aload_3 // 11 45:ldc1 #25 <String "Unknown result code: "> // 12 47:invokevirtual #29 <Method StringBuilder StringBuilder.append(String)> // 13 50:pop stringbuilder.append(i); // 14 51:aload_3 // 15 52:iload_1 // 16 53:invokevirtual #32 <Method StringBuilder StringBuilder.append(int)> // 17 56:pop stringbuilder.append(" (extras="); // 18 57:aload_3 // 19 58:ldc1 #34 <String " (extras="> // 20 60:invokevirtual #29 <Method StringBuilder StringBuilder.append(String)> // 21 63:pop stringbuilder.append(((Object) (e))); // 22 64:aload_3 // 23 65:aload_0 // 24 66:getfield #36 <Field Bundle e> // 25 69:invokevirtual #39 <Method StringBuilder StringBuilder.append(Object)> // 26 72:pop stringbuilder.append(", resultData="); // 27 73:aload_3 // 28 74:ldc1 #41 <String ", resultData="> // 29 76:invokevirtual #29 <Method StringBuilder StringBuilder.append(String)> // 30 79:pop stringbuilder.append(((Object) (bundle))); // 31 80:aload_3 // 32 81:aload_2 // 33 82:invokevirtual #39 <Method StringBuilder StringBuilder.append(Object)> // 34 85:pop stringbuilder.append(")"); // 35 86:aload_3 // 36 87:ldc1 #43 <String ")"> // 37 89:invokevirtual #29 <Method StringBuilder StringBuilder.append(String)> // 38 92:pop Log.w("MediaBrowserCompat", stringbuilder.toString()); // 39 93:ldc1 #45 <String "MediaBrowserCompat"> // 40 95:aload_3 // 41 96:invokevirtual #49 <Method String StringBuilder.toString()> // 42 99:invokestatic #55 <Method int Log.w(String, String)> // 43 102:pop return; // 44 103:return case 1: // '\001' f.a(d, e, bundle); // 45 104:aload_0 // 46 105:getfield #17 <Field MediaBrowserCompat$c f> // 47 108:aload_0 // 48 109:getfield #57 <Field String d> // 49 112:aload_0 // 50 113:getfield #36 <Field Bundle e> // 51 116:aload_2 // 52 117:invokevirtual #62 <Method void MediaBrowserCompat$c.a(String, Bundle, Bundle)> return; // 53 120:return case 0: // '\0' f.b(d, e, bundle); // 54 121:aload_0 // 55 122:getfield #17 <Field MediaBrowserCompat$c f> // 56 125:aload_0 // 57 126:getfield #57 <Field String d> // 58 129:aload_0 // 59 130:getfield #36 <Field Bundle e> // 60 133:aload_2 // 61 134:invokevirtual #65 <Method void MediaBrowserCompat$c.b(String, Bundle, Bundle)> return; // 62 137:return case -1: f.c(d, e, bundle); // 63 138:aload_0 // 64 139:getfield #17 <Field MediaBrowserCompat$c f> // 65 142:aload_0 // 66 143:getfield #57 <Field String d> // 67 146:aload_0 // 68 147:getfield #36 <Field Bundle e> // 69 150:aload_2 // 70 151:invokevirtual #68 <Method void MediaBrowserCompat$c.c(String, Bundle, Bundle)> return; // 71 154:return } } private final String d; private final Bundle e; private final MediaBrowserCompat.c f; }
36.734375
95
0.549766
c85bf629398b448b562d2263f9503b37f581e29b
1,900
package cn.ac.yhao.algorithm.leetcode; import org.junit.jupiter.api.Test; import java.util.Arrays; /** * @description: * 图像渲染 * 有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。 * 给你一个坐标(sr, sc)表示图像渲染开始的像素值(行 ,列)和一个新的颜色值newColor,让你重新上色这幅图像。 * 为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。 * 最后返回经过上色渲染后的图像。 * * 示例 1: * 输入: * image = [[1,1,1],[1,1,0],[1,0,1]] * sr = 1, sc = 1, newColor = 2 * 输出: [[2,2,2],[2,2,0],[2,0,1]] * 解析: * 在图像的正中间,(坐标(sr,sc)=(1,1)), * 在路径上所有符合条件的像素点的颜色都被更改成2。 * 注意,右下角的像素没有更改为2, * 因为它不是在上下左右四个方向上与初始点相连的像素点。 * 注意: * image 和image[0]的长度在范围[1, 50] 内。 * 给出的初始点将满足0 <= sr < image.length 和0 <= sc < image[0].length。 * image[i][j] 和newColor表示的颜色值在范围[0, 65535]内。 * */ public class LeetCode733 { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; dfs(image, sr, sc, newColor, oldColor); return image; } /** * 深度遍历 * @param image * @param x * @param y * @param newColor * @param oldColor */ private void dfs(int[][] image, int x, int y, int newColor,int oldColor){ if (x < 0 || x >= image.length || y < 0 || y >= image[0].length ) { return; } if (image[x][y] != oldColor || image[x][y] == newColor) { return; } image[x][y] = newColor; dfs(image, x - 1, y, newColor, oldColor); dfs(image, x + 1, y, newColor, oldColor); dfs(image, x, y - 1, newColor, oldColor); dfs(image, x, y + 1, newColor, oldColor); } @Test public void test(){ int[][] im = {{1,1,1},{1,1,0},{1,0,1}}; Arrays.stream(floodFill(im, 1, 1, 2)).forEach(i-> {Arrays.stream(i).forEach(j-> System.out.print(j+",")); System.out.println("");}); } }
27.941176
130
0.572105
d19f2fc86d485039e600afd6f6cb9fb8677beb54
1,438
package com.socotech.wf4j; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.StringUtils; public class DatePropertyEditor extends PropertyEditorSupport { private boolean allowEmpty; /** * Default constructor */ public DatePropertyEditor() { this.allowEmpty = true; } /** * Constructor specifying whether empty is allowed * * @param allowEmpty if true, empty does not cause exception to be thrown */ public DatePropertyEditor(boolean allowEmpty) { this.allowEmpty = allowEmpty; } public String getAsText() { return DateManager.dateToHumanString((Date) getValue()); } public void setAsText(String text) throws IllegalArgumentException { if (this.allowEmpty && StringUtils.isEmpty(text)) { super.setValue(null); } else { for (String pattern : patterns) { try { super.setValue(new SimpleDateFormat(pattern).parse(text)); return; } catch (ParseException e) { // keep trying } } // give up throw new IllegalArgumentException("Invalid format: " + text); } } private static String[] patterns = {"MM/yy", "MM/yyyy", "MM/dd/yyyy"}; }
28.196078
78
0.606398
119bcd30cc9e705f84a6da4abcfcf158b0796579
8,482
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.execution.engine.join; import com.carrotsearch.randomizedtesting.RandomizedRunner; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; import io.crate.breaker.RowAccounting; import io.crate.data.BatchIterator; import io.crate.data.Row; import io.crate.data.join.CombinedRow; import io.crate.testing.BatchIteratorTester; import io.crate.testing.BatchSimulatingIterator; import io.crate.testing.TestingBatchIterators; import org.elasticsearch.common.breaker.CircuitBreaker; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.ToIntFunction; import static com.carrotsearch.randomizedtesting.RandomizedTest.$; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(RandomizedRunner.class) @ThreadLeakScope(ThreadLeakScope.Scope.NONE) public class HashInnerJoinBatchIteratorTest { private final CircuitBreaker circuitBreaker = mock(CircuitBreaker.class); private final List<Object[]> expectedResult; private final Supplier<BatchIterator<Row>> leftIterator; private final Supplier<BatchIterator<Row>> rightIterator; private static Predicate<Row> getCol0EqCol1JoinCondition() { return row -> Objects.equals(row.get(0), row.get(1)); } private static ToIntFunction<Row> getHashForLeft() { return row -> Objects.hash(row.get(0)); } private static ToIntFunction<Row> getHashForRight() { return row -> Objects.hash(row.get(0)); } private static ToIntFunction<Row> getHashWithCollisions() { return row -> (Integer) row.get(0) % 3; } public HashInnerJoinBatchIteratorTest(@SuppressWarnings("unused") @Name("dataSetName") String testName, @Name("dataForLeft") Supplier<BatchIterator<Row>> leftIterator, @Name("dataForRight") Supplier<BatchIterator<Row>> rightIterator, @Name("expectedResult") List<Object[]> expectedResult) { this.leftIterator = leftIterator; this.rightIterator = rightIterator; this.expectedResult = expectedResult; when(circuitBreaker.getLimit()).thenReturn(110L); when(circuitBreaker.getUsed()).thenReturn(10L); } @ParametersFactory public static Iterable<Object[]> testParameters() { List<Object[]> resultForUniqueValues = Arrays.asList( new Object[] { 2, 2 }, new Object[] { 3, 3 }, new Object[] { 4, 4 }); List<Object[]> resultForDuplicateValues = Arrays.asList( new Object[] { 1, 1 }, new Object[] { 1, 1 }, new Object[] { 2, 2 }, new Object[] { 2, 2 }, new Object[] { 3, 3 }, new Object[] { 4, 4 }, new Object[] { 4, 4 }, new Object[] { 4, 4 }, new Object[] { 4, 4 } ); return Arrays.asList( $("UniqueValues-plain", (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.range(0, 5), (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.range(2, 6), resultForUniqueValues), $("UniqueValues-batchedSource", (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>(TestingBatchIterators.range(0, 5), 2, 2, null), (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>(TestingBatchIterators.range(2, 6), 2, 2, null), resultForUniqueValues), $("DuplicateValues-plain", (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)), (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)), resultForDuplicateValues), $("DuplicateValues-batchedSource", (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>( TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)), 2, 4, null), (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>( TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)), 2, 4, null), resultForDuplicateValues), $("DuplicateValues-leftLoadedRightBatched", (Supplier<BatchIterator<Row>>) () -> TestingBatchIterators.ofValues(Arrays.asList(0, 0, 1, 2, 2, 3, 4, 4)), (Supplier<BatchIterator<Row>>) () -> new BatchSimulatingIterator<>( TestingBatchIterators.ofValues(Arrays.asList(1, 1, 2, 3, 4, 4, 5, 5, 6)), 2, 4, null), resultForDuplicateValues)); } @Test public void testInnerHashJoin() throws Exception { Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator( leftIterator.get(), rightIterator.get(), mock(RowAccounting.class), new CombinedRow(1, 1), getCol0EqCol1JoinCondition(), getHashForLeft(), getHashForRight(), () -> 5 ); BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier); tester.verifyResultAndEdgeCaseBehaviour(expectedResult); } @Test public void testInnerHashJoinWithHashCollisions() throws Exception { Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator( leftIterator.get(), rightIterator.get(), mock(RowAccounting.class), new CombinedRow(1, 1), getCol0EqCol1JoinCondition(), getHashWithCollisions(), getHashWithCollisions(), () -> 5 ); BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier); tester.verifyResultAndEdgeCaseBehaviour(expectedResult); } @Test public void testInnerHashJoinWithBlockSizeSmallerThanDataSet() throws Exception { Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator( leftIterator.get(), rightIterator.get(), mock(RowAccounting.class), new CombinedRow(1, 1), getCol0EqCol1JoinCondition(), getHashForLeft(), getHashForRight(), () -> 1 ); BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier); tester.verifyResultAndEdgeCaseBehaviour(expectedResult); } @Test public void testInnerHashJoinWithBlockSizeBiggerThanIteratorBatchSize() throws Exception { Supplier<BatchIterator<Row>> batchIteratorSupplier = () -> new HashInnerJoinBatchIterator( leftIterator.get(), rightIterator.get(), mock(RowAccounting.class), new CombinedRow(1, 1), getCol0EqCol1JoinCondition(), getHashForLeft(), getHashForRight(), () -> 3 ); BatchIteratorTester tester = new BatchIteratorTester(batchIteratorSupplier); tester.verifyResultAndEdgeCaseBehaviour(expectedResult); } }
44.177083
121
0.654916
af23c3203b2106c1f2687dbebdb546f8dc0fc4a5
3,239
package strlet.experiments; import com.novemser.HHAR; import strlet.auxiliary.ThreadPool; import strlet.transferLearning.inductive.SingleSourceTransfer; import weka.core.Instance; import weka.core.Instances; import weka.core.Utils; import weka.core.converters.ArffSaver; import weka.core.converters.CSVLoader; import weka.core.converters.ConverterUtils.DataSource; import java.io.File; public class HHARExperiment extends AbstractExperiment { @Override public void runExperiment(SingleSourceTransfer[] models) throws Exception { DataSource ds = new DataSource( "/home/novemser/data/ActivityRecognitionExp/Phones_accelerometer_shuffle_del_10w.csv"); Instances data = ds.getDataSet(); data.setClassIndex(data.attribute("gt").index()); // data.deleteAttributeAt(data.attribute("Model").index()); int attIndex = data.attribute("Model").index(); Instances s3 = new Instances(data, data.numInstances()); Instances samsungold = new Instances(data, data.numInstances()); Instances s3mini = new Instances(data, data.numInstances()); Instances nexus4 = new Instances(data, data.numInstances()); for (int index = 0; index < data.numInstances(); ++index) { Instance instance = data.instance(index); // System.out.println("instance.classValue():" + instance.classValue()); //s3,samsungold,s3mini,nexus4 double val = instance.value(attIndex); if (Utils.eq(0, val)) { s3.add(instance); } else if (Utils.eq(1, val)) { samsungold.add(instance); } else if (Utils.eq(2, val)) { s3mini.add(instance); } else if (Utils.eq(3, val)) { nexus4.add(instance); } } nexus4.deleteAttributeAt(attIndex); s3.deleteAttributeAt(attIndex); s3mini.deleteAttributeAt(attIndex); samsungold.deleteAttributeAt(attIndex); for (SingleSourceTransfer classifier : models) { Instances dup = new Instances(data); double err = runExperiment(classifier, nexus4, new Instances(s3)); System.out.println("Error:" + err); } } private double runExperiment(SingleSourceTransfer classifier, Instances source, Instances target) throws Exception { target = new Instances(target); double total = 0; SingleSourceTransfer dup = classifier.makeDuplicate(); dup.buildModel(source, target); total += err(dup, target); return total; } public static void main(String[] args) throws Exception { HHARExperiment experiment = new HHARExperiment(); ThreadPool.initialize(16); try { experiment.runExperiment(); } finally { ThreadPool.shutdown(); } // args = new String[]{ // "/home/novemser/data/ActivityRecognitionExp/Phones_accelerometer_shuffle_del_1w.csv", // "/home/novemser/data/ActivityRecognitionExp/Phones_accelerometer_shuffle_del_1w.arff" // }; // CSVLoader loader = new CSVLoader(); // loader.setSource(new File(args[0])); // Instances data = loader.getDataSet(); // // // save ARFF // ArffSaver saver = new ArffSaver(); // saver.setInstances(data); // saver.setFile(new File(args[1])); // saver.setDestination(new File(args[1])); // saver.writeBatch(); } }
33.739583
95
0.686632
12ffb8d23bbe094b2ee90e72575186178d6d6327
4,943
package agenda; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Dewes */ public class DAO extends Model { public Connection conn; public boolean save (Model p) { final String INSERT = "INSERT INTO contato (nome, fone) VALUES (?, ?); "; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(INSERT); stmt.setString(1, Util.ArrayToString(p.getNome())); stmt.setString(2, Util.ArrayToStringComma(p.getFone())); stmt.executeUpdate(); conn.close(); System.out.println(" Salvou => "+ p.toString()); return true; } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean update (Model p) { final String UPDATE = "UPDATE contato SET nome=?, fone=? WHERE id=?; "; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(UPDATE); stmt.setString(1, Util.ArrayToString(p.getNome())); stmt.setString(2, Util.ArrayToStringComma(p.getFone())); stmt.setInt(3, p.getId()); stmt.executeUpdate(); conn.close(); System.out.println(" Alterou => "+ p.toString()); return true; } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean delete (int id) { final String DELETE = "DELETE FROM contato WHERE id = ?;"; Model p = get(id); if (p != null) { try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(DELETE); stmt.setInt(1, id); stmt.executeUpdate(); conn.close(); System.out.println(" Apagou => "+ p.toString()); return true; } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } } return false; } public Model get (int id) { final String GET = "SELECT * FROM contato WHERE id = ?;"; ResultSet rs = null; Model p = null; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(GET); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { int id_p = rs.getInt("id"); ArrayList nomes = Util.StringToArray( rs.getString("nome") ); ArrayList fones = Util.StringToArray( rs.getString("fone") ); p = new Model(id_p, nomes, fones); System.out.println(" Pegou => "+ p.toString()); } } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } return p; } public ResultSet list () { final String GET = "SELECT * FROM contato ORDER BY nome ASC;"; ResultSet rs = null; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(GET); rs = stmt.executeQuery(); } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); System.out.println( ex.getMessage() ); } return rs; } public ResultSet listLike (String nome) { final String GET_LIKE = "SELECT * FROM contato WHERE nome LIKE '%' ? '%' ORDER BY nome ASC;"; System.out.println(" Buscar => "+ nome); ResultSet rs = null; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(GET_LIKE); stmt.setString(1, nome); rs = stmt.executeQuery(); return rs; } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); System.out.println( ex.getMessage() ); } return rs; } public boolean exists (String nome) { final String SELECT = "SELECT * FROM contato WHERE nome = ?; "; ResultSet rs=null; try { conn = DBHelper.getConn(); PreparedStatement stmt = conn.prepareStatement(SELECT); stmt.setString(1, nome); rs = stmt.executeQuery(); if (rs.next()) return true; } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } return false; } }
34.089655
101
0.538337
bc7cacac59b2b1fa57d0a4143271339274854b32
855
/** * Created by Jacob Xie on 2/22/2022. */ package com.github.jacobbishopxy.ubiquitousassetmanagement; import static org.junit.jupiter.api.Assertions.assertThrows; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.github.jacobbishopxy.ubiquitousassetmanagement.promotion.dto.DateRange; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DateRangeTests { @Test void contextLoads() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date start = sdf.parse("2021-01-01"); Date end = sdf.parse("2020-01-01"); assertThrows(IllegalArgumentException.class, () -> new DateRange(start, end)); assertThrows(NullPointerException.class, () -> new DateRange(null, end)); } }
23.75
82
0.756725
3685efac9bad86f89fc778cebab5a8754e6324c2
978
package com.scaleunlimited.flink; import java.nio.charset.StandardCharsets; import org.apache.flink.api.common.io.OutputFormat; import org.apache.flink.api.java.io.TextOutputFormat; import org.apache.flink.core.fs.FileSystem.WriteMode; import org.apache.flink.core.fs.Path; @SuppressWarnings("serial") public class TextOutputFormatFactory<T> implements OutputFormatFactory<T> { private Path _basePath; private String _pattern; private WriteMode _mode; public TextOutputFormatFactory(Path basePath, String pattern, WriteMode mode) { _basePath = basePath; _pattern = pattern; _mode = mode; } @Override public OutputFormat<T> makeOutputFormat(String bucket) { String extension = _pattern.replaceAll("%s", bucket); TextOutputFormat<T> result = new TextOutputFormat<T>(new Path(_basePath, extension), StandardCharsets.UTF_8.name()); result.setWriteMode(_mode); return result; } }
30.5625
124
0.723926
6ae08459790efbf2074e11f0076a50635d34aca7
1,747
package com.jeffdisher.cacophony.utils; /** * Utility class to make common assertion statement idioms more meaningful (and not something which can be disabled). */ public class Assert { /** * Called when an exception was not expected. This should be for cases where the assertion is statically known to * be not something which could happen. * * @param e The unexpected exception. * @return Does not return - this is only here so the caller can throw this to satisfy the compiler. */ public static AssertionError unexpected(Throwable e) { throw new AssertionError("Unexpected exception", e); } /** * A traditional assertion: States that something must be true, failing if it isn't. * * @param flag The statement which must be true. */ public static void assertTrue(boolean flag) { if (!flag) { throw new AssertionError("Expected true"); } } /** * Called when code which is statically never expected to be reachable is somehow executed. * * @return Does not return - this is only here so the caller can throw this to satisfy the compiler. */ public static AssertionError unreachable() { throw new AssertionError("Unreachable code path hit"); } /** * Called when a feature which is only basically specced out for structure is used, even though it is not expected * to be available in the current version of the system. * * @param version The version of the software where this feature is expected to become available. * @return Does not return - this is only here so the caller can throw this to satisfy the compiler. */ public static AssertionError unimplemented(int version) { throw new AssertionError("Unimplemented feature planned for version " + version); } }
31.196429
117
0.727533
115a45969a16b23c594983694ba6b07be46f86f2
497
class Test { public <T> void varargs(int i, String... p1) { } public <T> void usage(String p1) { } { varargs<error descr="Cannot resolve method 'varargs()'">()</error>; varargs(1); varargs(1, ""); varargs(1, "", ""); usage<error descr="'usage(java.lang.String)' in 'Test' cannot be applied to '()'">()</error>; usage(""); usage<error descr="'usage(java.lang.String)' in 'Test' cannot be applied to '(java.lang.String, java.lang.String)'">("", "")</error>; } }
35.5
137
0.587525
92bdcf9fdedb46311b792bfdc3d9af6007350eb5
1,804
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.hardware.CRServo; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.Servo; public class HardwareRobot { // Public OpMode members. public DcMotor frontleft; public DcMotor backleft; public DcMotor frontright; public DcMotor backright; public DcMotor rightlift; public DcMotor leftlift; public DcMotor extensionlift; public DcMotor extension; public Servo servomarker; public CRServo servointake; // Converting encoder count to inches HardwareMap hwMap = null; static final double COUNTS_PER_MOTOR_REV = 1120; public static final double WHEEL_DIAMETER_INCHES = 4.0; public static final double COUNTS_PER_INCH_REV = (COUNTS_PER_MOTOR_REV) / (WHEEL_DIAMETER_INCHES * 3.1415); public static double DRIVE_SPEED = 0.3; // Constructor public HardwareRobot(){ } // Initialize standard Hardware interfaces public void init(HardwareMap ahwMap) { // Save reference to Hardware map hwMap = ahwMap; // Define and Initialize Motors frontleft = hwMap.get(DcMotor.class, "frontleft"); backleft = hwMap.get(DcMotor.class, "backleft"); frontright = hwMap.get(DcMotor.class, "frontright"); backright = hwMap.get(DcMotor.class, "backright"); rightlift = hwMap.get(DcMotor.class, "rightlift"); leftlift = hwMap.get(DcMotor.class, "leftlift"); extensionlift = hwMap.get(DcMotor.class, "extensionlift"); extension = hwMap.get(DcMotor.class, "extension"); servomarker = hwMap.get(Servo.class, "servomarker"); servointake = hwMap.get(CRServo.class, "servointake"); } }
36.816327
111
0.706763
7f7bac97e9cffb8ded4932d262eeb2d3a7773e70
750
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: SimplePrivilige.java package system.security; // Referenced classes of package system.security: // Privilige public class SimplePrivilige implements Privilige { public SimplePrivilige() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } private int id; private String value; }
17.44186
63
0.577333
249fafc42f18bb04fbc13930c66c07a29265b63d
267
package com.pacgame.provider.color; import com.pacgame.provider.Proxy; import javafx.scene.paint.Paint; public abstract class PaintProxy extends Proxy { protected Paint proxyObject; public Paint getProxyObject() { return proxyObject; } }
16.6875
48
0.726592
7d29015f9201edf8906d0a8626d5979dba6855db
1,745
/* * Copyright © 2021 Mark Raynsford <[email protected]> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jwheatsheaf.examples; import com.io7m.jwheatsheaf.api.JWFileChooserStringOverridesAbstract; import java.util.Optional; /** * A set of weird strings. */ public final class ExampleWeirdStrings extends JWFileChooserStringOverridesAbstract { /** * Construct a set of strings. */ public ExampleWeirdStrings() { } @Override public Optional<String> buttonOpen() { return Optional.of("Vigilate"); } @Override public Optional<String> buttonSave() { return Optional.of("Manticulate"); } @Override public Optional<String> confirmReplaceMessage( final String file) { return Optional.of(String.format("Defloccate velleity '%s'?", file)); } @Override public Optional<String> confirmReplaceButton() { return Optional.of("Defloccate"); } @Override public Optional<String> confirmTitleMessage() { return Optional.of("Defloccate velleity?"); } }
24.928571
78
0.730086
af61ee0a7220c41fd31446b29fe78dd13ae6c221
1,221
import java.util.ArrayList; import java.util.List; public class ShortestDistantFromCharacter { public int[] shortestToChar(String s, char c) { int[] result = new int[s.length()]; List<Integer> set = new ArrayList<>(); for (int i =0; i<s.length(); i++){ if (s.charAt(i)==c){ set.add(i); } } int b = set.get(0); int e = set.get(0); for (int i =0; i<s.length(); i++){ if (set.contains(i)){ b = i; int secondIdx = set.indexOf(i)+1; if (secondIdx>=set.size()) e = set.get(set.indexOf(i)); else e = set.get(secondIdx); } else { int minDistance = Math.min(Math.abs(i-b), Math.abs(i-e)); result[i] = minDistance; } } return result; } public static void main(String[] args) { // 3 5 6 11 String str = "aaab"; char c = 'a'; int res[] = new ShortestDistantFromCharacter().shortestToChar(str, c); for (int i =0; i < res.length; i++){ System.out.print(" "+res[i]); } } }
29.071429
78
0.452088
80217728b759553229f21095834f045a9faf9c33
15,259
package org.mockserver.examples.mockserver; import org.mockserver.client.MockServerClient; import org.mockserver.file.FileReader; import org.mockserver.matchers.TimeToLive; import org.mockserver.matchers.Times; import org.mockserver.mock.Expectation; import org.mockserver.model.OpenAPIDefinition; import java.util.concurrent.TimeUnit; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.model.OpenAPIDefinition.openAPI; /** * @author jamesdbloom */ public class OpenAPIRequestMatcherExamples { public void matchRequestByOpenAPILoadedByHttpUrl() { new MockServerClient("localhost", 1080) .when( openAPI( "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/mock/openapi_petstore_example.json" ) ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPIOperation() { new MockServerClient("localhost", 1080) .when( openAPI( "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/mock/openapi_petstore_example.json", "showPetById" ) ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPILoadedByFileUrl() { new MockServerClient("localhost", 1080) .when( openAPI( "file:/Users/jamesbloom/git/mockserver/mockserver/mockserver-core/target/test-classes/org/mockserver/mock/openapi_petstore_example.json" ) ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPILoadedByClasspathLocation() { new MockServerClient("localhost", 1080) .when( openAPI("org/mockserver/mock/openapi_petstore_example.json") ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPILoadedByJsonStringLiteral() { new MockServerClient("localhost", 1080) .when( new OpenAPIDefinition() .withSpecUrlOrPayload( FileReader.readFileFromClassPathOrPath("/Users/jamesbloom/git/mockserver/mockserver/mockserver-core/target/test-classes/org/mockserver/mock/openapi_petstore_example.json") ) .withOperationId("listPets") ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPILoadedByYamlStringLiteral() { new MockServerClient("localhost", 1080) .when( new OpenAPIDefinition() .withSpecUrlOrPayload( "---\n" + "openapi: 3.0.0\n" + "info:\n" + " version: 1.0.0\n" + " title: Swagger Petstore\n" + " license:\n" + " name: MIT\n" + "servers:\n" + " - url: http://petstore.swagger.io/v1\n" + "paths:\n" + " /pets:\n" + " get:\n" + " summary: List all pets\n" + " operationId: listPets\n" + " tags:\n" + " - pets\n" + " parameters:\n" + " - name: limit\n" + " in: query\n" + " description: How many items to return at one time (max 100)\n" + " required: false\n" + " schema:\n" + " type: integer\n" + " format: int32\n" + " responses:\n" + " '200':\n" + " description: A paged array of pets\n" + " headers:\n" + " x-next:\n" + " description: A link to the next page of responses\n" + " schema:\n" + " type: string\n" + " examples:\n" + " two:\n" + " value: \"/pets?query=752cd724e0d7&page=2\"\n" + " end:\n" + " value: \"\"\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Pets'\n" + " '500':\n" + " description: unexpected error\n" + " headers:\n" + " x-code:\n" + " description: The error code\n" + " schema:\n" + " type: integer\n" + " format: int32\n" + " example: 90\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " default:\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " post:\n" + " summary: Create a pet\n" + " operationId: createPets\n" + " tags:\n" + " - pets\n" + " requestBody:\n" + " description: a pet\n" + " required: true\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Pet'\n" + " '*/*':\n" + " schema:\n" + " $ref: '#/components/schemas/Pet'\n" + " responses:\n" + " '201':\n" + " description: Null response\n" + " '400':\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " '500':\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " default:\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " /pets/{petId}:\n" + " get:\n" + " summary: Info for a specific pet\n" + " operationId: showPetById\n" + " tags:\n" + " - pets\n" + " parameters:\n" + " - name: petId\n" + " in: path\n" + " required: true\n" + " description: The id of the pet to retrieve\n" + " schema:\n" + " type: string\n" + " - in: header\n" + " name: X-Request-ID\n" + " schema:\n" + " type: string\n" + " format: uuid\n" + " required: true\n" + " responses:\n" + " '200':\n" + " description: Expected response to a valid request\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Pet'\n" + " examples:\n" + " Crumble:\n" + " value:\n" + " id: 2\n" + " name: Crumble\n" + " tag: dog\n" + " Boots:\n" + " value:\n" + " id: 3\n" + " name: Boots\n" + " tag: cat\n" + " '500':\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + " default:\n" + " description: unexpected error\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: '#/components/schemas/Error'\n" + "components:\n" + " schemas:\n" + " Pet:\n" + " type: object\n" + " required:\n" + " - id\n" + " - name\n" + " properties:\n" + " id:\n" + " type: integer\n" + " format: int64\n" + " name:\n" + " type: string\n" + " tag:\n" + " type: string\n" + " example:\n" + " id: 1\n" + " name: Scruffles\n" + " tag: dog\n" + " Pets:\n" + " type: array\n" + " items:\n" + " $ref: '#/components/schemas/Pet'\n" + " Error:\n" + " type: object\n" + " required:\n" + " - code\n" + " - message\n" + " properties:\n" + " code:\n" + " type: integer\n" + " format: int32\n" + " message:\n" + " type: string\n" ) .withOperationId("listPets") ) .respond( response() .withBody("some_response_body") ); } public void matchRequestByOpenAPIOperationTwice() { new MockServerClient("localhost", 1080) .when( new OpenAPIDefinition() .withSpecUrlOrPayload( FileReader.readFileFromClassPathOrPath("/Users/jamesbloom/git/mockserver/mockserver/mockserver-core/target/test-classes/org/mockserver/mock/openapi_petstore_example.json") ) .withOperationId("listPets"), Times.exactly(2) ) .respond( response() .withBody("some_response_body") ); } public void updateExpectationById() { new MockServerClient("localhost", 1080) .upsert( new Expectation( openAPI( "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/mock/openapi_petstore_example.json", "showPetById" ), Times.once(), TimeToLive.exactly(TimeUnit.SECONDS, 60L), 100 ) .withId("630a6e5b-9d61-4668-a18f-a0d3df558583") .thenRespond(response().withBody("some_response_body")) ); } }
48.907051
195
0.318501
269576f661f10ba933ed38b5f20893c0997c3721
314
package egovframework.knia.foreign.exchange.cmm.code; public enum ConstCode { loginVO("loginVO"); private String code; public void ConstCode(String code) { this.code = code; } public String getCode() { return code; } private ConstCode(String code) { this.code = code; } }
14.952381
54
0.649682
ce0ef9f19642487fe8421f413f4c8520b78d8084
766
package vip.efactory.modules.system.service.dto; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.io.Serializable; import java.time.LocalDateTime; import java.util.List; @Data public class MenuDto implements Serializable { private Long id; private Integer type; private String permission; private String name; private Long sort; private String path; private String component; private Long pid; private Boolean iFrame; private Boolean cache; private Boolean hidden; private String componentName; private String icon; private List<MenuDto> children; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createTime; }
17.409091
68
0.724543
6de0cdd34b9033a457eb9297969e355a7240957b
6,387
package com.courierx.courierx.Track; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.courierx.courierx.Delivery.DeliveryListViewHolder; import com.courierx.courierx.Delivery.DeliveryLocationListViewHolder; import com.courierx.courierx.Models.PackageDetails; import com.courierx.courierx.Models.TrackInfo; import com.courierx.courierx.Models.UserDetailsSingleton; import com.courierx.courierx.R; import com.courierx.courierx.UpdateLocationDetails; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Location extends Fragment { String st; TextView locationStatus; TextView packageId; UserDetailsSingleton userDetailsSingleton ; Bundle data; Button btn; FirebaseRecyclerOptions<TrackInfo> deliveryLocationListOptions; FirebaseRecyclerAdapter<TrackInfo, DeliveryLocationListViewHolder> deliveryLocationListAdapter; DatabaseReference ref; private RecyclerView deliveryLocationListRecycler; TextView deliveryManName2; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); userDetailsSingleton= UserDetailsSingleton.getInstance(); Log.d("test" , "value " + userDetailsSingleton.getCourierXUser().getFirstName()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_location, container, false); locationStatus = view.findViewById(R.id.locationStatus); packageId = view.findViewById(R.id.location_packageId); btn = view.findViewById(R.id.update_location_btn); data = this.getArguments(); if(data != null){ st = data.getString("packageID"); packageId.setText(st); } Log.d("test","your package is tracked "+ st); DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("packages"); Query query=mDatabase.orderByChild("packageId").equalTo(st); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // Log.d("data" , "value : " + snapshot.getValue(PackageDetails.class).getStatus()); for(DataSnapshot ds : snapshot.getChildren()) { packageId.setText(ds.getValue(PackageDetails.class).getPackageId()); locationStatus.setText(ds.getValue(PackageDetails.class).getStatus()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); ref = FirebaseDatabase.getInstance().getReference("packages").child(st).child("trackInfo"); deliveryLocationListRecycler = view.findViewById(R.id.last_loction_list_recyclerview); deliveryLocationListRecycler.setHasFixedSize(true); deliveryLocationListRecycler.setLayoutManager(new LinearLayoutManager(getContext())); // deliveryManName2 = view.findViewById(R.id.deliverymanName); // deliveryManName2.setText(userDetailsSingleton.getCourierXUser().getFirstName()); deliveryLocationListOptions = new FirebaseRecyclerOptions.Builder<TrackInfo>().setQuery(ref , TrackInfo.class).build(); deliveryLocationListAdapter = new FirebaseRecyclerAdapter<TrackInfo, DeliveryLocationListViewHolder>(deliveryLocationListOptions) { @NonNull @Override public DeliveryLocationListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View recyclerview = LayoutInflater.from(parent.getContext()).inflate(R.layout.package_location_list_card , parent , false); return new DeliveryLocationListViewHolder(recyclerview); } @Override protected void onBindViewHolder(@NonNull DeliveryLocationListViewHolder holder, final int position, @NonNull TrackInfo model) { holder.location.setText(model.getLocation()); Date date = new Date(model.getDate()); SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()); String text = sfd.format(date); holder.time.setText(text); holder.delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TrackInfo trackInfo = deliveryLocationListAdapter.getItem(position); ref.child(trackInfo.getTrackInfoId()).removeValue(); } }); } }; btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { detailedViewFragment(); } }); deliveryLocationListAdapter.startListening(); deliveryLocationListRecycler.setAdapter(deliveryLocationListAdapter); return view; } public void detailedViewFragment(){ UpdateLocationDetails updateLocationDetails = new UpdateLocationDetails(); updateLocationDetails.setArguments(data); FragmentTransaction ft = getParentFragmentManager().beginTransaction(); ft.replace(R.id.bottom_nav_fragment_delivery, updateLocationDetails); ft.commit(); } }
39.425926
139
0.700642
c47888568753ea01f06179f88f1251b038af3a6b
2,904
// SPDX-License-Identifier: MIT package com.daimler.sechub.sereco.importer; import java.io.IOException; import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.springframework.stereotype.Component; import com.daimler.sechub.sereco.metadata.Classification; import com.daimler.sechub.sereco.metadata.MetaData; import com.daimler.sechub.sereco.metadata.Vulnerability; @Component public class NetsparkerV1XMLImporter extends AbstractProductResultImporter { public MetaData importResult(String xml) throws IOException{ MetaData metaData = new MetaData(); if (xml==null) { xml=""; } Document document; try { document = DocumentHelper.parseText(xml); } catch (DocumentException e) { throw new IOException("Import cannot parse xml",e); } Element netsparkerCloudElement = document.getRootElement(); Element vulnerabilitiesElement = netsparkerCloudElement.element("vulnerabilities"); if (vulnerabilitiesElement==null) { throw new IllegalStateException("no vulnerabilities element found!"); } @SuppressWarnings("unchecked") Iterator<Element> it = vulnerabilitiesElement.elementIterator(); while (it.hasNext()) { Element vulnerabilityElement = it.next(); Vulnerability vulnerability = new Vulnerability(); metaData.getVulnerabilities().add(vulnerability); vulnerability.setSeverity(NetsparkerServerityConverter.convert(vulnerabilityElement.elementText("severity"))); vulnerability.setUrl(vulnerabilityElement.elementText("url")); vulnerability.setType(vulnerabilityElement.elementText("type")); vulnerability.setDescription(vulnerabilityElement.elementText("description")); Element classificationElement = vulnerabilityElement.element("classification"); if (classificationElement==null) { throw new IllegalStateException("no classificaton element found!"); } Classification classification = vulnerability.getClassification(); classification.setOwasp(classificationElement.elementText("owasp")); classification.setWasc(classificationElement.elementText("wasc")); classification.setCwe(classificationElement.elementText("cwe")); classification.setCapec(classificationElement.elementText("capec")); classification.setPci31(classificationElement.elementText("pci31")); classification.setPci32(classificationElement.elementText("pci32")); classification.setHipaa(classificationElement.elementText("hipaa")); classification.setOwaspProactiveControls(classificationElement.elementText("owasppc")); } return metaData; } @Override protected ImportSupport createImportSupport() { /* @formatter:off */ return ImportSupport. builder(). productId("Netsparker"). mustBeXML(). contentIdentifiedBy("<netsparker-cloud"). build(); /* @formatter:on */ } }
35.414634
113
0.774449
aad42d35dc14ff52ffc293f31f6fa2d8df89c297
1,554
package BabyBaby.data; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import BabyBaby.Command.commands.Public.MuteCMD; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.User; public class GetUnmute implements Runnable { public User muted; public Guild guild; public Role stfu; public GetUnmute(User user, Guild tempG, Role muteRole) { muted = user; guild = tempG; stfu = muteRole; } public void run() { guild.removeRoleFromMember(guild.retrieveMember(muted).complete(), stfu).queue(); MuteCMD.variables.remove(MuteCMD.userMuted.get(guild.getMember(muted))); MuteCMD.userMuted.remove(guild.getMember(muted)); Connection c = null; PreparedStatement stmt = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection(Data.db); stmt = c.prepareStatement("DELETE FROM USERS WHERE ID = ? AND GUILDID = ?;"); stmt.setString(1, muted.getId()); stmt.setString(2, guild.getId()); stmt.execute(); stmt.close(); c.close(); } catch ( Exception e ) { e.printStackTrace(); return; } muted.openPrivateChannel().queue((channel) -> { channel.sendMessage("You shall be unmuted! Hope this worked...").queue(); }); } }
29.884615
89
0.602317
3d2ce8808db26280faa1eceee25935d34bca34e6
1,144
package com.madzera.happytree.core.atp; import java.util.Map; import java.util.Set; import com.madzera.happytree.core.ATPPhase; import com.madzera.happytree.exception.TreeException; abstract class ATPGenericPhase<T> extends ATPPhase<T> { /* * Protects this constructor. The API Client must not initialization no one * ATP Phase. This constructor should be protected into the children classes. */ protected ATPGenericPhase() {} protected IllegalArgumentException throwIllegalArgumentException( final ATPRepositoryMessage error) { return ATPFactory.exceptionFactory(). createIllegalArgumentException(this.getMessageError(error)); } protected TreeException throwTreeException( final ATPRepositoryMessage error) { return ATPFactory.exceptionFactory().createTreeException( this.getMessageError(error)); } protected <K,V> Map<K,V> createHashMap() { return ATPFactory.mapFactory().createHashMap(); } protected <E> Set<E> createHashSet() { return ATPFactory.collectionFactory().createHashSet(); } private String getMessageError(ATPRepositoryMessage error) { return error.getMessageError(); } }
27.238095
78
0.774476
ee0c6790a9b875afbabd34b2d34db9548b7281e4
1,261
package net.minecraft.entity.ai.attributes; import javax.annotation.Nullable; import net.minecraft.util.math.MathHelper; public class RangedAttribute extends BaseAttribute { private final double field_111120_a; public double field_111118_b; // Spigot private String field_111119_c; public RangedAttribute(@Nullable IAttribute iattribute, String s, double d0, double d1, double d2) { super(iattribute, s, d0); this.field_111120_a = d1; this.field_111118_b = d2; if (d1 > d2) { throw new IllegalArgumentException("Minimum value cannot be bigger than maximum value!"); } else if (d0 < d1) { throw new IllegalArgumentException("Default value cannot be lower than minimum value!"); } else if (d0 > d2) { throw new IllegalArgumentException("Default value cannot be bigger than maximum value!"); } } public RangedAttribute func_111117_a(String s) { this.field_111119_c = s; return this; } public String func_111116_f() { return this.field_111119_c; } public double func_111109_a(double d0) { d0 = MathHelper.func_151237_a(d0, this.field_111120_a, this.field_111118_b); return d0; } }
31.525
104
0.671689
76890fc247dcb09a1de0c5dcee2751f9bcf7167b
390
package mb.statix.scopegraph.diff; public class Edge<S, L> { public final S source; public final L label; public final S target; public Edge(S source, L label, S target) { this.source = source; this.label = label; this.target = target; } @Override public String toString() { return source + " -" + label + "-> " + target; } }
20.526316
54
0.579487
6e74ac178bb0d04202d848af8490153e26c1e92d
1,134
package com.aerhard.oxygen.plugin.dbtagger; import static org.mockito.Mockito.mock; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace; @RunWith(MockitoJUnitRunner.class) public class SearchDialogTest { @BeforeClass public static void initClass() { Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.ERROR); rootLogger.addAppender(new ConsoleAppender(new PatternLayout( "%-6r [%p] %c - %m%n"))); } private StandalonePluginWorkspace workspace; @Before public void initTC() { workspace = mock(StandalonePluginWorkspace.class); } /** * Test Initialization of the search dialog. */ @Test public void testSearchDialog() { new SearchDialog(workspace, "", "", "", "", "", ""); } }
25.2
71
0.701058
7a96efe5220004904499c5e72c323925dd09566a
638
package org.blab.mde.ee.dal; import java.util.List; import org.blab.mde.core.annotation.Mixin; @Mixin public interface RepositoryMixin<Entity, Key, Criteria> { Entity load(Key id); Entity load(QueryMixin<Criteria> query); <V> PageList<V> loadAll(QueryMixin<Criteria> query); boolean remove(Key id); boolean remove(QueryMixin<Criteria> query); int removeAll(List<Key> idList); int removeAll(QueryMixin<Criteria> query); boolean removeEntity(Entity entity); Entity save(Entity entity); List<Entity> saveAll(List<Entity> entities); boolean update(Entity entity); int updateAll(List<Entity> entities); }
19.333333
57
0.739812
e9e8739e5f2ac4120b1f6bcbfbb7bde61dce9643
4,140
package io.ei.jsontoxls.resources; import io.ei.jsontoxls.AllConstants; import io.ei.jsontoxls.Messages; import io.ei.jsontoxls.repository.TemplateRepository; import io.ei.jsontoxls.util.ExcelUtils; import io.ei.jsontoxls.util.ResponseFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import java.io.IOException; import java.io.OutputStream; import java.text.MessageFormat; import static io.ei.jsontoxls.AllConstants.MEDIA_TYPE_MS_EXCEL; import static io.ei.jsontoxls.AllConstants.TOKEN_PATH_PARAM; import static io.ei.jsontoxls.util.UUIDUtils.newUUID; import static java.text.MessageFormat.format; import static org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace; @Path("/templates") public class TemplateResource { Logger logger = LoggerFactory.getLogger(TemplateResource.class); private TemplateRepository templateRepository; private ExcelUtils excelUtils; public TemplateResource(TemplateRepository templateRepository, ExcelUtils excelUtils) { this.templateRepository = templateRepository; this.excelUtils = excelUtils; } @POST @Consumes(MediaType.APPLICATION_OCTET_STREAM) @Produces(MediaType.TEXT_PLAIN) public Response save(byte[] templateData) { try { if (!excelUtils.isExcel(templateData)) { return ResponseFactory.badRequest(Messages.INVALID_TEMPLATE); } String token = newUUID(); templateRepository.add(token, templateData); logger.info(format("Saved template with {0} number of bytes. Token: {1}", templateData.length, token)); return ResponseFactory.created(token); } catch (Exception e) { logger.error(format("Unable to save template. Exception Message: {0}. Stack trace: {1}.", e.getMessage(), getStackTrace(e))); return ResponseFactory.internalServerError(Messages.UNABLE_TO_SAVE_TEMPLATE); } } @PUT @Path("/{" + TOKEN_PATH_PARAM + "}") @Consumes(MediaType.APPLICATION_OCTET_STREAM) @Produces(MediaType.TEXT_PLAIN) public Response update(@PathParam(TOKEN_PATH_PARAM) String templateToken, byte[] templateData) { try { if (templateRepository.findByToken(templateToken) == null) { return ResponseFactory.notFound(MessageFormat.format(Messages.INVALID_TEMPLATE_TOKEN, templateToken)); } if (!excelUtils.isExcel(templateData)) { return ResponseFactory.badRequest(Messages.INVALID_TEMPLATE); } templateRepository.update(templateToken, templateData); logger.info(format("Updated template with {0} number of bytes for token: {1}", templateData.length, templateToken)); return ResponseFactory.ok(templateToken); } catch (Exception e) { logger.error(format("Unable to update template. Exception Message: {0}. Stack trace: {1}.", e.getMessage(), getStackTrace(e))); return ResponseFactory.internalServerError(Messages.UNABLE_TO_UPDATE_TEMPLATE); } } @GET @Path("/{" + TOKEN_PATH_PARAM + "}") @Produces(MEDIA_TYPE_MS_EXCEL) public Response get(@PathParam(TOKEN_PATH_PARAM) String token) { byte[] generatedExcel = templateRepository.findByToken(token); if (generatedExcel == null) { return ResponseFactory.notFound(MessageFormat.format(Messages.INVALID_TEMPLATE_TOKEN, token)); } String filename = token + "." + AllConstants.DEFAULT_EXTENSION; return ResponseFactory.excel(getExcelAsOutputStream(generatedExcel), filename); } private StreamingOutput getExcelAsOutputStream(final byte[] excelBytes) { return new StreamingOutput() { @Override public void write(OutputStream out) throws IOException, WebApplicationException { out.write(excelBytes); } }; } }
39.428571
128
0.687681
0a9cac00db078d5684f812f3f3bc31a1a712c655
6,484
package com.ymt.framework.hybrid.model.params; /** * Created by xujian on 2016/2/1. */ public class JChatOrder { private int ActuallyPrice; private Object AddTime; private String Catalog; private int DistributionType; private String DistributionTypeText; private int Earnest; private boolean FreeShipping; private int Freight; private boolean IsActivityProduct; private boolean IsMultiProduct; private Object LeaveWord; private Object LogisticsNewStatus; private String OrderId; private Object OrderTime; private int OrderTotalPrice; private int PaidAmount; private boolean PaidInFull; private int Platform; private int Price; private int PriceType; private int ProductCount; private String ProductDes; private Object ProductId; private String ProductPic; private int ProductsNum; private Object Remarks; private String SellerId; private int TailAmount; private int TariffType; private int TotalPrice; private int TradingStatus; private String TradingStatusText; public void setActuallyPrice(int ActuallyPrice) { this.ActuallyPrice = ActuallyPrice; } public void setAddTime(Object AddTime) { this.AddTime = AddTime; } public void setCatalog(String Catalog) { this.Catalog = Catalog; } public void setDistributionType(int DistributionType) { this.DistributionType = DistributionType; } public void setDistributionTypeText(String DistributionTypeText) { this.DistributionTypeText = DistributionTypeText; } public void setEarnest(int Earnest) { this.Earnest = Earnest; } public void setFreeShipping(boolean FreeShipping) { this.FreeShipping = FreeShipping; } public void setFreight(int Freight) { this.Freight = Freight; } public void setIsActivityProduct(boolean IsActivityProduct) { this.IsActivityProduct = IsActivityProduct; } public void setIsMultiProduct(boolean IsMultiProduct) { this.IsMultiProduct = IsMultiProduct; } public void setLeaveWord(Object LeaveWord) { this.LeaveWord = LeaveWord; } public void setLogisticsNewStatus(Object LogisticsNewStatus) { this.LogisticsNewStatus = LogisticsNewStatus; } public void setOrderId(String OrderId) { this.OrderId = OrderId; } public void setOrderTime(Object OrderTime) { this.OrderTime = OrderTime; } public void setOrderTotalPrice(int OrderTotalPrice) { this.OrderTotalPrice = OrderTotalPrice; } public void setPaidAmount(int PaidAmount) { this.PaidAmount = PaidAmount; } public void setPaidInFull(boolean PaidInFull) { this.PaidInFull = PaidInFull; } public void setPlatform(int Platform) { this.Platform = Platform; } public void setPrice(int Price) { this.Price = Price; } public void setPriceType(int PriceType) { this.PriceType = PriceType; } public void setProductCount(int ProductCount) { this.ProductCount = ProductCount; } public void setProductDes(String ProductDes) { this.ProductDes = ProductDes; } public void setProductId(Object ProductId) { this.ProductId = ProductId; } public void setProductPic(String ProductPic) { this.ProductPic = ProductPic; } public void setProductsNum(int ProductsNum) { this.ProductsNum = ProductsNum; } public void setRemarks(Object Remarks) { this.Remarks = Remarks; } public void setSellerId(String SellerId) { this.SellerId = SellerId; } public void setTailAmount(int TailAmount) { this.TailAmount = TailAmount; } public void setTariffType(int TariffType) { this.TariffType = TariffType; } public void setTotalPrice(int TotalPrice) { this.TotalPrice = TotalPrice; } public void setTradingStatus(int TradingStatus) { this.TradingStatus = TradingStatus; } public void setTradingStatusText(String TradingStatusText) { this.TradingStatusText = TradingStatusText; } public int getActuallyPrice() { return ActuallyPrice; } public Object getAddTime() { return AddTime; } public String getCatalog() { return Catalog; } public int getDistributionType() { return DistributionType; } public String getDistributionTypeText() { return DistributionTypeText; } public int getEarnest() { return Earnest; } public boolean isFreeShipping() { return FreeShipping; } public int getFreight() { return Freight; } public boolean isIsActivityProduct() { return IsActivityProduct; } public boolean isIsMultiProduct() { return IsMultiProduct; } public Object getLeaveWord() { return LeaveWord; } public Object getLogisticsNewStatus() { return LogisticsNewStatus; } public String getOrderId() { return OrderId; } public Object getOrderTime() { return OrderTime; } public int getOrderTotalPrice() { return OrderTotalPrice; } public int getPaidAmount() { return PaidAmount; } public boolean isPaidInFull() { return PaidInFull; } public int getPlatform() { return Platform; } public int getPrice() { return Price; } public int getPriceType() { return PriceType; } public int getProductCount() { return ProductCount; } public String getProductDes() { return ProductDes; } public Object getProductId() { return ProductId; } public String getProductPic() { return ProductPic; } public int getProductsNum() { return ProductsNum; } public Object getRemarks() { return Remarks; } public String getSellerId() { return SellerId; } public int getTailAmount() { return TailAmount; } public int getTariffType() { return TariffType; } public int getTotalPrice() { return TotalPrice; } public int getTradingStatus() { return TradingStatus; } public String getTradingStatusText() { return TradingStatusText; } }
21.905405
70
0.649136
8306aad59f862d01115cdebd230329cf10f2a257
1,270
package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; import java.util.Arrays; import java.util.Objects; import org.apache.olingo.commons.api.edm.provider.CsdlAction; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Action extends CsdlAction { @Override @JacksonXmlProperty(localName = "Name") public CsdlAction setName(final String name) { Objects.requireNonNull(name, "Name is a required attribute of actions"); return super.setName(name); } @Override @JacksonXmlProperty(localName = "IsBound") public CsdlAction setBound(final boolean isBound) { return super.setBound(isBound); } @Override @JacksonXmlProperty(localName = "EntitySetPath") public CsdlAction setEntitySetPath(String entitySetPath) { return super.setEntitySetPath(entitySetPath); } @JacksonXmlProperty(localName = "Parameter") public void setParameters(final Parameter[] parameters) { this.parameters.addAll(Arrays.asList(parameters)); } @JacksonXmlProperty(localName = "ReturnType") public void setReturnType(final ReturnType returnType) { super.setReturnType(returnType); } }
28.863636
76
0.774016
0dda4e4cc729066462855e594e23d6dd3845431f
7,083
package ru.courses.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import ru.courses.addressbook.model.ContactData; import ru.courses.addressbook.model.Contacts; import ru.courses.addressbook.model.GroupData; import ru.courses.addressbook.model.Groups; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; public class ContactHelper extends HelperBase { public ContactHelper(WebDriver wd) { super(wd); } public void saveContact() { click(By.xpath("//div[@id='content']/form/input[21]")); } public void fillContact(ContactData contactData, boolean creation) { type(By.name("firstname"), contactData.getName()); type(By.name("lastname"), contactData.getLastname()); type(By.name("address"), contactData.getAddress()); type(By.name("home"), contactData.getPhoneHome()); type(By.name("email"), contactData.getEmail()); if (creation) { attache(By.name("photo"), contactData.getPhoto()); if (contactData.getGroups().size() > 0) { Assert.assertTrue(contactData.getGroups().size() == 1); new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroups().iterator().next().getName()); } } else { Assert.assertFalse(isElementPresent(By.name("new_group"))); } } public void addNew() { click(By.linkText("add new")); } public void editContact(int index) { wd.findElements(By.xpath("//img[@alt='Edit']")).get(index).click(); } public void editContactById(int id) { wd.findElement(By.xpath("//a[@href='edit.php?id=" + id + "']")).click(); } public void saveEditContact() { click(By.xpath("//div[@id='content']/form/input[22]")); } public void deleteEditContact() throws InterruptedException { click(By.xpath("//div[@id='content']/form[2]/input[2]")); TimeUnit.SECONDS.sleep(1); } public void checkContact(int id) { wd.findElement(By.cssSelector("input[value='" + id + "']")).click(); } public int count() { return wd.findElements(By.name("selected[]")).size(); } public void deleteContact() { click(By.xpath("//input[@value='Delete']")); } public void delete(ContactData contact) throws InterruptedException { editContactById(contact.getId()); deleteEditContact(); } public void deleteCheckedContact(ContactData contact) { checkContact(contact.getId()); deleteContact(); confirmDeleteContact(); } public void confirmDeleteContact() { alertAccept(); } public void checkAllContact() { click(By.id("MassCB")); } public void createContact(ContactData contactData) { addNew(); fillContact(contactData, true); saveContact(); } public void createContact() { addNew(); fillContact(new ContactData() .withName("testname") .withLastname("testlname") .withAddress("testaddress") .withPhoneHome("123454321") .withEmail("[email protected]") .withPhoto(new File("src/test/resources/photo.png")), true); saveContact(); } public void modify(ContactData contact) { editContactById(contact.getId()); fillContact(contact, false); saveEditContact(); } public void addGroupToContact(ContactData contact, GroupData group) throws InterruptedException { checkContact(contact.getId()); addToGroup(group); } private void addToGroup(GroupData group) { new Select(wd.findElement(By.name("to_group"))).selectByValue(String.valueOf(group.getId())); click(By.name("add")); } public boolean isThereAContact() { return isElementPresent(By.name("selected[]")); } public boolean isGroupFind(ContactData contactData) { String xpath = "//select[@name='new_group']/option[contains(text(),'" + contactData.getGroups() + "')]"; return isElementPresent(By.xpath(xpath)); } public Contacts all() { Contacts contacts = new Contacts(); List<WebElement> rows = wd.findElements(By.xpath("//tr[@name='entry']")); for (WebElement column : rows) { String name = column.findElements(By.tagName("td")).get(2).getText(); String lastname = column.findElements(By.tagName("td")).get(1).getText(); String address = column.findElements(By.tagName("td")).get(3).getText(); String allEmails = column.findElements(By.tagName("td")).get(4).getText(); String allPhones = column.findElements(By.tagName("td")).get(5).getText(); int id = Integer.parseInt(column.findElement(By.xpath("td/input")).getAttribute("id")); contacts.add(new ContactData() .withId(id) .withName(name) .withLastname(lastname) .withAllPhones(allPhones) .withAddress(address) .withAllEmails(allEmails)); } return contacts; } public ContactData infoFromEditForm(ContactData contact) { editContactById(contact.getId()); String firstname = wd.findElement(By.name("firstname")).getAttribute("value"); String lastname = wd.findElement(By.name("lastname")).getAttribute("value"); String home = wd.findElement(By.name("home")).getAttribute("value"); String mobile = wd.findElement(By.name("mobile")).getAttribute("value"); String work = wd.findElement(By.name("work")).getAttribute("value"); String phone2 = wd.findElement(By.name("phone2")).getAttribute("value"); String address = wd.findElement(By.name("address")).getAttribute("value"); String address2 = wd.findElement(By.name("address2")).getAttribute("value"); String email = wd.findElement(By.name("email")).getAttribute("value"); String email2 = wd.findElement(By.name("email2")).getAttribute("value"); String email3 = wd.findElement(By.name("email3")).getAttribute("value"); wd.navigate().back(); return new ContactData() .withId(contact.getId()) .withName(firstname) .withLastname(lastname) .withPhoneHome(home) .withPhoneMobile(mobile) .withPhoneWork(work) .withPhone2(phone2) .withAddress(address) .withAddress2(address2) .withEmail(email) .withEmail2(email2) .withEmail3(email3); } public boolean isContactGroupFind(ContactData contact, Groups groups) { for (GroupData g : groups) if (contact.getGroups().iterator().next().getId() == g.getId()) { return true; } return false; } }
35.415
138
0.616123
24c9743d2b4d8749fa644c1e8960701020d57493
4,476
package net.glowstone.util; import net.glowstone.GlowServer; import javax.net.ssl.HttpsURLConnection; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Level; /** * Simple library manager which downloads external dependencies. */ public final class LibraryManager { /** * The Maven repository to download from. */ private final String repository; /** * The directory to store downloads in. */ private final File directory; private final ExecutorService downloaderService = Executors.newCachedThreadPool(); public LibraryManager(GlowServer server) { // todo: allow configuration of repository, libraries, and directory repository = "https://repo.glowstone.net/service/local/repositories/central/content/"; directory = new File("lib"); } public void run() { if (!directory.isDirectory() && !directory.mkdirs()) { GlowServer.logger.log(Level.SEVERE, "Could not create libraries directory: " + directory); } downloaderService.execute(new LibraryDownloader("org.xerial", "sqlite-jdbc", "3.15.1", "")); downloaderService.execute(new LibraryDownloader("mysql", "mysql-connector-java", "5.1.39", "")); downloaderService.execute(new LibraryDownloader("org.slf4j", "slf4j-jdk14", "1.7.15", "")); downloaderService.shutdown(); try { downloaderService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { GlowServer.logger.log(Level.SEVERE, "Library Manager thread interrupted: ", e); } } private class LibraryDownloader implements Runnable { private final String group; private final String library; private final String version; private String checksum; private LibraryDownloader(String group, String library, String version, String checksum) { this.group = group; this.library = library; this.version = version; this.checksum = checksum; } @Override public void run() { // check if we already have it File file = new File(directory, library + "-" + version + ".jar"); if (!file.exists() && checksum(file, checksum)) { // download it GlowServer.logger.info("Downloading " + library + " " + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + "/" + library + "/" + version + "/" + library + "-" + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + " " + version + "."); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + " " + version, e); return; } } // hack it onto the classpath URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, file.toURI().toURL()); } catch (ReflectiveOperationException | MalformedURLException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } } public boolean checksum(File file, String checksum) { // TODO: actually check checksum return true; } } }
39.610619
157
0.614388
11c4fe5109353d338d28634bad49711585b9e964
53,317
/* * This file was automatically generated by EvoSuite * Fri Aug 24 11:17:41 GMT 2018 */ package com.soops.CEN4010.JMCA.JParser; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.shaded.org.mockito.Mockito.*; import static org.evosuite.runtime.EvoAssertions.*; import com.soops.CEN4010.JMCA.JParser.JavaCharStream; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PushbackInputStream; import java.io.Reader; import java.io.SequenceInputStream; import java.io.StringReader; import java.net.URI; import java.nio.CharBuffer; import java.util.Enumeration; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.evosuite.runtime.ViolatedAssumptionAnswer; import org.evosuite.runtime.mock.java.io.MockFile; import org.evosuite.runtime.mock.java.io.MockFileInputStream; import org.evosuite.runtime.mock.java.net.MockURI; import org.evosuite.runtime.testdata.EvoSuiteFile; import org.evosuite.runtime.testdata.FileSystemHandling; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class JavaCharStream_ESTest extends JavaCharStream_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test00() throws Throwable { File file0 = MockFile.createTempFile("7?0aOE5", "Qn)&R(1sDyr}bg8<p"); MockFileInputStream mockFileInputStream0 = new MockFileInputStream(file0); JavaCharStream javaCharStream0 = new JavaCharStream(mockFileInputStream0, 0, 0); try { javaCharStream0.readChar(); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 1 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test01() throws Throwable { int int0 = 3923; JavaCharStream javaCharStream0 = new JavaCharStream((Reader) null, 3923, 3923); javaCharStream0.column = 3923; javaCharStream0.prevCharIsLF = false; // Undeclared exception! try { javaCharStream0.ReInit((InputStream) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("java.io.Reader", e); } } /** //Test case number: 2 /*Coverage entropy=2.0794415416798357 */ @Test(timeout = 4000) public void test02() throws Throwable { Enumeration<InputStream> enumeration0 = (Enumeration<InputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer()); doReturn(false).when(enumeration0).hasMoreElements(); SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0); JavaCharStream javaCharStream0 = new JavaCharStream(sequenceInputStream0); javaCharStream0.prevCharIsLF = false; javaCharStream0.adjustBeginLineColumn(0, 0); javaCharStream0.ReInit((InputStream) sequenceInputStream0, 0, 0); PipedOutputStream pipedOutputStream0 = new PipedOutputStream(); PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0); javaCharStream0.ReInit((InputStream) pipedInputStream0); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); } /** //Test case number: 3 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test03() throws Throwable { PipedInputStream pipedInputStream0 = new PipedInputStream(14); BufferedInputStream bufferedInputStream0 = new BufferedInputStream(pipedInputStream0); PushbackInputStream pushbackInputStream0 = new PushbackInputStream(bufferedInputStream0); JavaCharStream javaCharStream0 = new JavaCharStream(pushbackInputStream0, 14, 0); char[] charArray0 = javaCharStream0.GetSuffix(0); assertEquals(0, charArray0.length); assertEquals((-1), javaCharStream0.bufpos); } /** //Test case number: 4 /*Coverage entropy=1.7478680974667573 */ @Test(timeout = 4000) public void test04() throws Throwable { StringReader stringReader0 = new StringReader(""); stringReader0.close(); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 3509, 3509, 0); javaCharStream0.GetImage(); PipedOutputStream pipedOutputStream0 = new PipedOutputStream(); pipedOutputStream0.close(); PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0); pipedInputStream0.markSupported(); byte[] byteArray0 = new byte[7]; byteArray0[0] = (byte)10; byteArray0[1] = (byte) (-110); byteArray0[2] = (byte) (-40); byteArray0[3] = (byte) (-59); byteArray0[4] = (byte)73; byteArray0[5] = (byte) (-18); byteArray0[6] = (byte)0; pipedOutputStream0.write(byteArray0); int[] intArray0 = new int[1]; intArray0[0] = 3509; javaCharStream0.bufcolumn = intArray0; javaCharStream0.ReInit((InputStream) pipedInputStream0); // Undeclared exception! try { javaCharStream0.UpdateLineColumn('q'); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 5 /*Coverage entropy=1.242453324894 */ @Test(timeout = 4000) public void test05() throws Throwable { JavaCharStream.hexval('c'); StringReader stringReader0 = new StringReader(""); char[] charArray0 = new char[3]; charArray0[0] = 'c'; charArray0[1] = 'c'; charArray0[2] = 'c'; stringReader0.read(charArray0); stringReader0.read(); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); int int0 = (-78); javaCharStream0.adjustBeginLineColumn((-78), 1696); stringReader0.markSupported(); URI uRI0 = MockURI.URI(""); MockFile mockFile0 = null; try { mockFile0 = new MockFile(uRI0); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // URI is not absolute // verifyException("java.io.File", e); } } /** //Test case number: 6 /*Coverage entropy=2.3978952727983707 */ @Test(timeout = 4000) public void test06() throws Throwable { StringReader stringReader0 = new StringReader("7E'IDNN~"); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-623), (-1891)); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean0 = stringReader0.markSupported(); assertTrue(boolean0); javaCharStream0.prevCharIsLF = true; assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.prevCharIsLF = true; assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.ReInit((Reader) stringReader0, 0, 0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); long long0 = stringReader0.skip(0); assertEquals(0L, long0); javaCharStream0.backup(0); assertFalse(JavaCharStream.staticFlag); assertEquals(4095, javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndLine()); javaCharStream0.ExpandBuff(false); assertFalse(JavaCharStream.staticFlag); assertEquals(4095, javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndLine()); char char0 = javaCharStream0.readChar(); assertEquals('7', char0); assertFalse(JavaCharStream.staticFlag); assertEquals(4096, javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndLine()); javaCharStream0.ReInit((Reader) stringReader0, (-590), (-590)); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); try { javaCharStream0.BeginToken(); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 7 /*Coverage entropy=1.4750763110546947 */ @Test(timeout = 4000) public void test07() throws Throwable { StringReader stringReader0 = new StringReader(""); assertNotNull(stringReader0); int int0 = (-1); int int1 = 1805; JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-1), 1805); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); try { javaCharStream0.ReadByte(); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 8 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test08() throws Throwable { StringReader stringReader0 = new StringReader(""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); javaCharStream0.Done(); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); // Undeclared exception! try { javaCharStream0.ExpandBuff(true); fail("Expecting exception: Error"); } catch(Error e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 9 /*Coverage entropy=1.6094379124341005 */ @Test(timeout = 4000) public void test09() throws Throwable { Enumeration<BufferedInputStream> enumeration0 = (Enumeration<BufferedInputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer()); doReturn(false).when(enumeration0).hasMoreElements(); SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0); assertNotNull(sequenceInputStream0); JavaCharStream javaCharStream0 = new JavaCharStream(sequenceInputStream0, (-1), (-1)); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); javaCharStream0.line = (-1); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.Done(); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); // Undeclared exception! try { javaCharStream0.getEndLine(); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 10 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test10() throws Throwable { StringReader stringReader0 = new StringReader("[=xPR{lyvVYh`"); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotNull(javaCharStream0); javaCharStream0.ReInit((Reader) stringReader0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); javaCharStream0.FillBuff(); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); // Undeclared exception! try { javaCharStream0.getLine(); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 11 /*Coverage entropy=2.0794415416798357 */ @Test(timeout = 4000) public void test11() throws Throwable { StringReader stringReader0 = new StringReader("}RU4yR"); assertNotNull(stringReader0); char[] charArray0 = new char[1]; charArray0[0] = '\\'; boolean boolean0 = stringReader0.ready(); assertTrue(boolean0); int int0 = stringReader0.read(); assertEquals(125, int0); CharBuffer charBuffer0 = CharBuffer.wrap(charArray0); assertFalse(charBuffer0.isDirect()); assertEquals(1, charBuffer0.length()); assertEquals(0, charBuffer0.arrayOffset()); assertTrue(charBuffer0.hasRemaining()); assertEquals("\\", charBuffer0.toString()); assertEquals(1, charBuffer0.capacity()); assertFalse(charBuffer0.isReadOnly()); assertEquals(0, charBuffer0.position()); assertEquals(1, charBuffer0.limit()); assertEquals(1, charBuffer0.remaining()); assertTrue(charBuffer0.hasArray()); assertArrayEquals(new char[] {'\\'}, charArray0); assertNotNull(charBuffer0); assertEquals(1, charArray0.length); int int1 = stringReader0.read(charBuffer0); assertFalse(int1 == int0); assertEquals(1, int1); assertFalse(charBuffer0.isDirect()); assertEquals("", charBuffer0.toString()); assertEquals(0, charBuffer0.arrayOffset()); assertEquals(1, charBuffer0.capacity()); assertFalse(charBuffer0.isReadOnly()); assertEquals(1, charBuffer0.position()); assertEquals(0, charBuffer0.length()); assertEquals(1, charBuffer0.limit()); assertFalse(charBuffer0.hasRemaining()); assertTrue(charBuffer0.hasArray()); assertEquals(0, charBuffer0.remaining()); assertArrayEquals(new char[] {''}, charArray0); assertEquals(1, charArray0.length); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotNull(javaCharStream0); int int2 = javaCharStream0.getBeginLine(); assertFalse(int2 == int1); assertFalse(int2 == int0); assertEquals(0, int2); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); int int3 = JavaCharStream.hexval('c'); assertFalse(int3 == int2); assertFalse(int3 == int0); assertFalse(int3 == int1); assertEquals(12, int3); int int4 = javaCharStream0.getBeginLine(); assertFalse(int4 == int1); assertTrue(int4 == int2); assertFalse(int4 == int0); assertFalse(int4 == int3); assertEquals(0, int4); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); char[] charArray1 = javaCharStream0.GetSuffix(1); assertFalse(charArray1.equals((Object)charArray0)); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotSame(charArray1, charArray0); assertArrayEquals(new char[] {'\u0000'}, charArray1); assertNotNull(charArray1); assertEquals(1, charArray1.length); javaCharStream0.ReInit((Reader) stringReader0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); // Undeclared exception! try { javaCharStream0.UpdateLineColumn('c'); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 12 /*Coverage entropy=1.6094379124341005 */ @Test(timeout = 4000) public void test12() throws Throwable { int int0 = 501; PipedInputStream pipedInputStream0 = new PipedInputStream(501); assertEquals(0, pipedInputStream0.available()); assertNotNull(pipedInputStream0); JavaCharStream javaCharStream0 = new JavaCharStream(pipedInputStream0, (-1465), (-1)); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); Reader reader0 = null; pipedInputStream0.close(); assertEquals(0, pipedInputStream0.available()); javaCharStream0.nextCharInd = (-2835); assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); // Undeclared exception! try { javaCharStream0.readChar(); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -2834 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 13 /*Coverage entropy=1.7917594692280547 */ @Test(timeout = 4000) public void test13() throws Throwable { Enumeration<BufferedInputStream> enumeration0 = (Enumeration<BufferedInputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer()); doReturn(false).when(enumeration0).hasMoreElements(); SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0); assertNotNull(sequenceInputStream0); JavaCharStream javaCharStream0 = new JavaCharStream(sequenceInputStream0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotNull(javaCharStream0); int int0 = sequenceInputStream0.available(); assertEquals(0, int0); javaCharStream0.AdjustBuffSize(); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); char[] charArray0 = new char[7]; charArray0[0] = '@'; charArray0[1] = ' '; charArray0[2] = 'i'; charArray0[3] = 'G'; charArray0[4] = 'h'; charArray0[5] = '2'; charArray0[6] = '\''; javaCharStream0.nextCharBuf = charArray0; assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); // Undeclared exception! try { javaCharStream0.getLine(); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 14 /*Coverage entropy=1.464816384890813 */ @Test(timeout = 4000) public void test14() throws Throwable { char char0 = '2'; int int0 = JavaCharStream.hexval('2'); assertEquals(2, int0); StringReader stringReader0 = new StringReader(""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-24), 4); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotNull(javaCharStream0); int int1 = (-1); javaCharStream0.prevCharIsLF = true; assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); int int2 = 0; char[] charArray0 = new char[8]; charArray0[0] = '2'; charArray0[1] = '2'; try { javaCharStream0.FillBuff(); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 15 /*Coverage entropy=1.0986122886681096 */ @Test(timeout = 4000) public void test15() throws Throwable { StringReader stringReader0 = new StringReader(""); assertNotNull(stringReader0); char[] charArray0 = new char[7]; charArray0[0] = ','; charArray0[1] = '$'; charArray0[2] = 's'; charArray0[3] = '<'; charArray0[4] = 'w'; charArray0[5] = 'x'; charArray0[6] = 'J'; int int0 = stringReader0.read(charArray0); assertEquals((-1), int0); assertArrayEquals(new char[] {',', '$', 's', '<', 'w', 'x', 'J'}, charArray0); assertEquals(7, charArray0.length); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); int int1 = javaCharStream0.getBeginColumn(); assertFalse(int1 == int0); assertEquals(0, int1); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); } /** //Test case number: 16 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test16() throws Throwable { char char0 = 'W'; try { JavaCharStream.hexval('W'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 17 /*Coverage entropy=2.2161022480912633 */ @Test(timeout = 4000) public void test17() throws Throwable { StringReader stringReader0 = new StringReader("M2J+-u5D[HFh_5\""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-623), 1539); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean0 = stringReader0.markSupported(); assertTrue(boolean0); javaCharStream0.ReInit((Reader) stringReader0, 144, 635); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); StringReader stringReader1 = new StringReader("M2J+-u5D[HFh_5\""); assertFalse(stringReader1.equals((Object)stringReader0)); assertNotNull(stringReader1); long long0 = stringReader1.skip(1539); assertFalse(stringReader1.equals((Object)stringReader0)); assertEquals(15L, long0); assertNotSame(stringReader1, stringReader0); javaCharStream0.backup((-623)); assertFalse(stringReader0.equals((Object)stringReader1)); assertEquals(622, javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getLine()); assertNotSame(stringReader0, stringReader1); javaCharStream0.ExpandBuff(false); assertFalse(stringReader0.equals((Object)stringReader1)); assertEquals(622, javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getLine()); assertNotSame(stringReader0, stringReader1); char char0 = javaCharStream0.readChar(); assertFalse(stringReader0.equals((Object)stringReader1)); assertEquals('M', char0); assertEquals(623, javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(144, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(635, javaCharStream0.getColumn()); assertEquals(635, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(144, javaCharStream0.getLine()); assertNotSame(stringReader0, stringReader1); javaCharStream0.ReInit((Reader) stringReader0, 144, 0); assertFalse(stringReader0.equals((Object)stringReader1)); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotSame(stringReader0, stringReader1); try { javaCharStream0.BeginToken(); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 18 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test18() throws Throwable { StringReader stringReader0 = new StringReader("}RU4yR"); assertNotNull(stringReader0); char[] charArray0 = new char[1]; charArray0[0] = '\\'; boolean boolean0 = stringReader0.ready(); assertTrue(boolean0); try { JavaCharStream.hexval('\\'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 19 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test19() throws Throwable { DataInputStream dataInputStream0 = new DataInputStream((InputStream) null); assertNotNull(dataInputStream0); try { JavaCharStream.hexval('o'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 20 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test20() throws Throwable { int int0 = JavaCharStream.hexval('c'); assertEquals(12, int0); String string0 = "2@"; StringReader stringReader0 = new StringReader("2@"); assertNotNull(stringReader0); char[] charArray0 = new char[3]; charArray0[0] = 'c'; charArray0[1] = 'c'; charArray0[2] = 'c'; int int1 = stringReader0.read(charArray0); assertFalse(int1 == int0); assertEquals(2, int1); assertArrayEquals(new char[] {'2', '@', 'c'}, charArray0); assertEquals(3, charArray0.length); try { JavaCharStream.hexval('@'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 21 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test21() throws Throwable { Enumeration<InputStream> enumeration0 = (Enumeration<InputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer()); doReturn(false).when(enumeration0).hasMoreElements(); SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0); assertNotNull(sequenceInputStream0); try { JavaCharStream.hexval('S'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 22 /*Coverage entropy=1.9730014063936125 */ @Test(timeout = 4000) public void test22() throws Throwable { StringReader stringReader0 = new StringReader("7E'IDNN~"); assertNotNull(stringReader0); long long0 = stringReader0.skip((-1891)); assertEquals(0L, long0); boolean boolean0 = FileSystemHandling.appendStringToFile((EvoSuiteFile) null, "7E'IDNN~"); assertFalse(boolean0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-623), (-1891)); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean1 = stringReader0.markSupported(); assertFalse(boolean1 == boolean0); assertTrue(boolean1); javaCharStream0.prevCharIsLF = true; assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.prevCharIsLF = true; assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.ReInit((Reader) stringReader0, 0, 0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); long long1 = stringReader0.skip(0); assertTrue(long1 == long0); assertEquals(0L, long1); javaCharStream0.backup(3); assertEquals(4092, javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getColumn()); javaCharStream0.ExpandBuff(false); assertEquals(4092, javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getColumn()); char char0 = javaCharStream0.readChar(); assertEquals('\u0000', char0); assertFalse(JavaCharStream.staticFlag); assertEquals(4093, javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getEndLine()); assertEquals(0, javaCharStream0.getColumn()); javaCharStream0.ReInit((Reader) stringReader0, (-590), (-590)); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); // Undeclared exception! try { javaCharStream0.UpdateLineColumn('\u0000'); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 23 /*Coverage entropy=1.0882231038287276 */ @Test(timeout = 4000) public void test23() throws Throwable { EvoSuiteFile evoSuiteFile0 = null; String string0 = null; boolean boolean0 = FileSystemHandling.appendStringToFile((EvoSuiteFile) null, (String) null); assertFalse(boolean0); boolean boolean1 = FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null); assertTrue(boolean1 == boolean0); assertFalse(boolean1); PipedInputStream pipedInputStream0 = new PipedInputStream(78); assertEquals(0, pipedInputStream0.available()); assertNotNull(pipedInputStream0); PushbackInputStream pushbackInputStream0 = new PushbackInputStream(pipedInputStream0, 78); assertEquals(0, pipedInputStream0.available()); assertNotNull(pushbackInputStream0); BufferedInputStream bufferedInputStream0 = new BufferedInputStream(pushbackInputStream0, 78); assertEquals(0, pipedInputStream0.available()); assertNotNull(bufferedInputStream0); boolean boolean2 = pushbackInputStream0.markSupported(); assertTrue(boolean2 == boolean0); assertTrue(boolean2 == boolean1); assertFalse(boolean2); assertEquals(0, pipedInputStream0.available()); JavaCharStream javaCharStream0 = new JavaCharStream(bufferedInputStream0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean3 = pushbackInputStream0.markSupported(); assertTrue(boolean3 == boolean0); assertTrue(boolean3 == boolean2); assertTrue(boolean3 == boolean1); assertFalse(boolean3); assertEquals(0, pipedInputStream0.available()); javaCharStream0.bufpos = 10; assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getEndLine()); char[] charArray0 = new char[3]; charArray0[0] = 'E'; boolean boolean4 = FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false); assertTrue(boolean4 == boolean3); assertTrue(boolean4 == boolean0); assertTrue(boolean4 == boolean1); assertTrue(boolean4 == boolean2); assertFalse(boolean4); charArray0[1] = '2'; charArray0[2] = 'E'; javaCharStream0.buffer = charArray0; assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getLine()); assertEquals(0, javaCharStream0.getEndColumn()); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getEndLine()); int int0 = JavaCharStream.hexval('E'); assertEquals(14, int0); try { javaCharStream0.BeginToken(); fail("Expecting exception: IOException"); } catch(IOException e) { // // Pipe not connected // verifyException("java.io.PipedInputStream", e); } } /** //Test case number: 24 /*Coverage entropy=0.9404479886553264 */ @Test(timeout = 4000) public void test24() throws Throwable { int int0 = JavaCharStream.hexval('6'); assertEquals(6, int0); char[] charArray0 = new char[8]; charArray0[0] = '6'; charArray0[1] = '6'; charArray0[4] = '6'; Enumeration<BufferedInputStream> enumeration0 = (Enumeration<BufferedInputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer()); doReturn(false).when(enumeration0).hasMoreElements(); SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0); assertNotNull(sequenceInputStream0); SequenceInputStream sequenceInputStream1 = new SequenceInputStream(sequenceInputStream0, sequenceInputStream0); assertFalse(sequenceInputStream1.equals((Object)sequenceInputStream0)); assertNotNull(sequenceInputStream1); JavaCharStream javaCharStream0 = new JavaCharStream(sequenceInputStream1); assertFalse(sequenceInputStream0.equals((Object)sequenceInputStream1)); assertFalse(sequenceInputStream1.equals((Object)sequenceInputStream0)); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); } /** //Test case number: 25 /*Coverage entropy=1.3862943611198906 */ @Test(timeout = 4000) public void test25() throws Throwable { StringReader stringReader0 = new StringReader(""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); stringReader0.reset(); javaCharStream0.maxNextCharInd = 584; assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); javaCharStream0.adjustBeginLineColumn(1, 1); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(2, javaCharStream0.getBeginLine()); assertEquals(1, javaCharStream0.getBeginColumn()); // Undeclared exception! try { javaCharStream0.getColumn(); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 26 /*Coverage entropy=1.6094379124341005 */ @Test(timeout = 4000) public void test26() throws Throwable { int int0 = JavaCharStream.hexval('C'); assertEquals(12, int0); PipedInputStream pipedInputStream0 = new PipedInputStream(12); assertEquals(0, pipedInputStream0.available()); assertNotNull(pipedInputStream0); JavaCharStream javaCharStream0 = new JavaCharStream(pipedInputStream0); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, pipedInputStream0.available()); assertEquals(0, javaCharStream0.getBeginLine()); assertEquals(0, javaCharStream0.getBeginColumn()); assertNotNull(javaCharStream0); // Undeclared exception! try { javaCharStream0.getEndColumn(); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -1 // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 27 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test27() throws Throwable { boolean boolean0 = FileSystemHandling.appendStringToFile((EvoSuiteFile) null, (String) null); assertFalse(boolean0); boolean boolean1 = FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null); assertTrue(boolean1 == boolean0); assertFalse(boolean1); int int0 = JavaCharStream.hexval('1'); assertEquals(1, int0); PipedOutputStream pipedOutputStream0 = new PipedOutputStream(); assertNotNull(pipedOutputStream0); PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0); assertEquals(0, pipedInputStream0.available()); assertNotNull(pipedInputStream0); PipedOutputStream pipedOutputStream1 = null; try { pipedOutputStream1 = new PipedOutputStream(pipedInputStream0); fail("Expecting exception: IOException"); } catch(Throwable e) { // // Already connected // verifyException("java.io.PipedOutputStream", e); } } /** //Test case number: 28 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test28() throws Throwable { int int0 = JavaCharStream.hexval('c'); assertEquals(12, int0); PipedInputStream pipedInputStream0 = new PipedInputStream(); assertEquals(0, pipedInputStream0.available()); assertNotNull(pipedInputStream0); PushbackInputStream pushbackInputStream0 = new PushbackInputStream(pipedInputStream0); assertEquals(0, pipedInputStream0.available()); assertNotNull(pushbackInputStream0); boolean boolean0 = FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true); assertFalse(boolean0); int int1 = JavaCharStream.hexval('A'); assertFalse(int1 == int0); assertEquals(10, int1); } /** //Test case number: 29 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test29() throws Throwable { boolean boolean0 = FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null); assertFalse(boolean0); int int0 = JavaCharStream.hexval('7'); assertEquals(7, int0); } /** //Test case number: 30 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test30() throws Throwable { EvoSuiteFile evoSuiteFile0 = null; boolean boolean0 = FileSystemHandling.appendStringToFile((EvoSuiteFile) null, (String) null); assertFalse(boolean0); boolean boolean1 = FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null); assertTrue(boolean1 == boolean0); assertFalse(boolean1); boolean boolean2 = FileSystemHandling.setPermissions((EvoSuiteFile) null, true, false, false); assertTrue(boolean2 == boolean1); assertTrue(boolean2 == boolean0); assertFalse(boolean2); try { JavaCharStream.hexval(';'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 31 /*Coverage entropy=0.2287207447761076 */ @Test(timeout = 4000) public void test31() throws Throwable { StringReader stringReader0 = new StringReader("M2J+-u5D[HFh_5\""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-623), 1539); assertEquals((-1), javaCharStream0.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean0 = stringReader0.markSupported(); assertTrue(boolean0); char char0 = 'V'; try { JavaCharStream.hexval('V'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 32 /*Coverage entropy=1.8290814369082264 */ @Test(timeout = 4000) public void test32() throws Throwable { StringReader stringReader0 = new StringReader("M2J+-u5D[HFh_5\""); assertNotNull(stringReader0); JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, (-623), 1539); assertFalse(JavaCharStream.staticFlag); assertEquals((-1), javaCharStream0.bufpos); assertEquals(0, javaCharStream0.getBeginColumn()); assertEquals(0, javaCharStream0.getBeginLine()); assertNotNull(javaCharStream0); boolean boolean0 = stringReader0.markSupported(); assertTrue(boolean0); boolean boolean1 = FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true); assertFalse(boolean1 == boolean0); assertFalse(boolean1); int int0 = JavaCharStream.hexval('2'); assertEquals(2, int0); char char0 = javaCharStream0.BeginToken(); assertEquals('M', char0); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.bufpos); assertEquals((-623), javaCharStream0.getEndLine()); assertEquals(1539, javaCharStream0.getBeginColumn()); assertEquals(1539, javaCharStream0.getColumn()); assertEquals((-623), javaCharStream0.getLine()); assertEquals(1539, javaCharStream0.getEndColumn()); assertEquals((-623), javaCharStream0.getBeginLine()); int int1 = javaCharStream0.getEndColumn(); assertFalse(int1 == int0); assertEquals(1539, int1); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.bufpos); assertEquals((-623), javaCharStream0.getEndLine()); assertEquals(1539, javaCharStream0.getBeginColumn()); assertEquals(1539, javaCharStream0.getColumn()); assertEquals((-623), javaCharStream0.getLine()); assertEquals(1539, javaCharStream0.getEndColumn()); assertEquals((-623), javaCharStream0.getBeginLine()); javaCharStream0.UpdateLineColumn('T'); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.bufpos); assertEquals(1540, javaCharStream0.getColumn()); assertEquals((-623), javaCharStream0.getEndLine()); assertEquals(1540, javaCharStream0.getBeginColumn()); assertEquals(1540, javaCharStream0.getEndColumn()); assertEquals((-623), javaCharStream0.getLine()); assertEquals((-623), javaCharStream0.getBeginLine()); byte[] byteArray0 = new byte[1]; int int2 = JavaCharStream.hexval('9'); assertFalse(int2 == int0); assertFalse(int2 == int1); assertEquals(9, int2); JavaCharStream javaCharStream1 = new JavaCharStream(stringReader0); assertFalse(javaCharStream1.equals((Object)javaCharStream0)); assertEquals((-1), javaCharStream1.bufpos); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream1.getBeginLine()); assertEquals(0, javaCharStream1.getBeginColumn()); assertNotNull(javaCharStream1); String string0 = javaCharStream0.GetImage(); assertFalse(javaCharStream0.equals((Object)javaCharStream1)); assertEquals("M", string0); assertFalse(JavaCharStream.staticFlag); assertEquals(0, javaCharStream0.bufpos); assertEquals(1540, javaCharStream0.getColumn()); assertEquals((-623), javaCharStream0.getEndLine()); assertEquals(1540, javaCharStream0.getBeginColumn()); assertEquals(1540, javaCharStream0.getEndColumn()); assertEquals((-623), javaCharStream0.getLine()); assertEquals((-623), javaCharStream0.getBeginLine()); assertNotSame(javaCharStream0, javaCharStream1); assertNotNull(string0); } /** //Test case number: 33 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test33() throws Throwable { char char0 = '6'; char char1 = 'M'; try { JavaCharStream.hexval('M'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } /** //Test case number: 34 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test34() throws Throwable { try { JavaCharStream.hexval('J'); fail("Expecting exception: IOException"); } catch(IOException e) { // // no message in exception (getMessage() returned null) // verifyException("com.soops.CEN4010.JMCA.JParser.JavaCharStream", e); } } }
36.098172
176
0.666954
eeb2bbd16f36149de828dfa40d14eb21eab3b530
459
package no.hvl.dat104; import java.util.HashMap; import java.util.Map; public class Votes { private Map<Integer, Integer> votes; public Votes() { this.votes = new HashMap<>(); } public void addVote(int valg) { votes.put(valg, votes.get(valg) + 1); } public Map<Integer, Integer> getVotes() { return votes; } public void setVotes(Map<Integer, Integer> votes) { this.votes = votes; } }
17.653846
55
0.601307
024a73f44c5253c8796fa51ff97921fc433d1b6c
357
package cn.zzq0324.alarm.bot.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * description: 钉钉回调 <br> * date: 2022/2/18 10:05 下午 <br> * author: zzq0324 <br> * version: 1.0 <br> */ @Controller @RequestMapping("/dingtalk") public class DingTalkCallbackController { }
22.3125
62
0.747899
19d27f2402baaf1933edebb3546d86ad92a977b1
1,178
package com.imasson.commandrouter.demo; import com.imasson.commandrouter.CommandRouter; import com.imasson.commandrouter.CommandRouterBuilder; import com.imasson.commandrouter.driver.UriDriver; public class Main { public static void main(String[] args) { final CommandRouter router = new CommandRouterBuilder() .setDriver(new UriDriver()) .addCommandHandler(TestHandler.class) .addGeneralValueConverters() .build(); router.setDebug(true); System.out.println(router.dump()); // Sample 1: hello world final String rawCommand1 = "demo://trial/show?msg=helloworld"; router.executeCommand("I'm context", rawCommand1); // Sample 2: custom converter final String rawCommand2 = "demo://trial/locate?addr=N%20Western%20Avenue,Chicago,90027"; router.executeCommand(null, rawCommand2); // Sample 3: use return value final String rawCommand3 = "demo://trial/sayHello"; String ret = (String) router.executeCommand(null, rawCommand3); System.out.println("'demo://trial/sayHello' outputs '" + ret + "'"); } }
34.647059
97
0.657895
165134fe8009e2535e90dd714054f90fd62fd000
339
package com.trace.keywords.masker; import com.trace.keywords.Masker; /** * 密码脱敏器 * * @author [email protected] * */ public class PasswordMasker implements Masker { @Override public String masking(String name, Object value) { if (value == null) { return null; } return "******"; } }
16.142857
54
0.587021
d6068fdaccca9d0ba71af3003d70879a1fe83d19
562
package kr.spring.batch.chapter07; import kr.spring.batch.chapter07.jpa.ProductRepository; import lombok.Setter; import org.springframework.batch.item.ItemProcessor; /** * kr.spring.batch.chapter07.IdToProductItemProcessor * * @author 배성혁 [email protected] * @since 13. 8. 8. 오후 2:49 */ public class IdToProductItemProcessor implements ItemProcessor<String, Product> { @Setter private ProductRepository productRepository; @Override public Product process(String productId) throws Exception { return productRepository.findOne(productId); } }
25.545455
81
0.791815
511c40c537bcb5139bb59f20ff69355164ea27fd
3,417
package com.krys.codelibrary.ui.room; import androidx.annotation.LayoutRes; import androidx.lifecycle.Observer; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Handler; import android.os.Looper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.krys.codelibrary.R; import com.krys.codelibrary.adapters.MoviesAdapter; import com.krys.codelibrary.models.MoviesRoomModel; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class RoomFragment extends Fragment { private RoomViewModel mViewModel; private RecyclerView rvMovies; private RecyclerView rvNewReleaseMovies; private RecyclerView rvBestRatedMovies; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mViewModel = ViewModelProviders.of(this).get(RoomViewModel.class); View root = inflater.inflate(R.layout.fragment_room, container, false); findViewById(root); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void findViewById(View root) { rvMovies = root.findViewById(R.id.rvMovies); rvNewReleaseMovies = root.findViewById(R.id.rvNewReleaseMovies); rvBestRatedMovies = root.findViewById(R.id.rvBestRatedMovies); } private void init() { observeApiCall(); } private void observeApiCall() { ExecutorService executor = Executors.newSingleThreadExecutor(); Handler handler = new Handler(Looper.getMainLooper()); executor.execute(() -> { getActivity().runOnUiThread(() -> mViewModel.callMoviesApi(requireActivity())); handler.post(this::observeDBData); }); } private void observeDBData() { mViewModel.getListRoomData().observe(this, new Observer<List<MoviesRoomModel>>() { @Override public void onChanged(List<MoviesRoomModel> movies) { setUpData(movies); } }); } private void setUpData(List<MoviesRoomModel> movies) { MoviesAdapter moviesAdapter = getAdapter(movies, R.layout.list_item_movie); setUpRv(moviesAdapter, rvMovies); MoviesAdapter newReleaseAdapter = getAdapter(movies, R.layout.list_item_movie_categories); setUpRv(newReleaseAdapter, rvNewReleaseMovies); MoviesAdapter bestRatedAdapter = getAdapter(movies, R.layout.list_item_movie_categories); setUpRv(bestRatedAdapter, rvBestRatedMovies); } private void setUpRv(MoviesAdapter moviesAdapter, RecyclerView recyclerView){ recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false)); recyclerView.setAdapter(moviesAdapter); } private MoviesAdapter getAdapter(List<MoviesRoomModel> movies, @LayoutRes int layout){ return new MoviesAdapter(getActivity(), movies, layout); } }
34.515152
132
0.731343
301592c0debd48d209eaaccf126c82812343bd6b
1,478
package com.alibha; import com.alibha.db.ExpenseItemDao; import com.alibha.db.ExpenseItemRepository; import com.alibha.resources.ExpenseItemResource; import io.dropwizard.Application; import io.dropwizard.jdbi3.JdbiFactory; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.jdbi.v3.core.Jdbi; public class PersonalExpenseServiceApplication extends Application<PersonalExpenseServiceConfiguration> { public static void main(final String[] args) throws Exception { new PersonalExpenseServiceApplication().run(args); } @Override public String getName() { return "PersonalExpenseService"; } @Override public void initialize(final Bootstrap<PersonalExpenseServiceConfiguration> bootstrap) { // TODO: application initialization } @Override public void run(final PersonalExpenseServiceConfiguration configuration, final Environment environment) { final JdbiFactory factory = new JdbiFactory(); final Jdbi jdbi = factory.build(environment, configuration.getDataSourceFactory(), "postgresql"); final ExpenseItemDao expenseItemDao = jdbi.onDemand(ExpenseItemDao.class); ExpenseItemRepository expenseItemRepository = new ExpenseItemRepository(expenseItemDao); ExpenseItemResource expenseItemResource = new ExpenseItemResource(expenseItemRepository); environment.jersey().register(expenseItemResource); } }
36.04878
105
0.76184
68f12b28b989b62451792a248f1a430d05899efa
13,400
/** ** TurkanaSouthModel.java ** ** Copyright 2011 by Andrew Crooks, Joey Harrison, Mark Coletti, and ** George Mason University. ** ** Licensed under the Academic Free License version 3.0 ** ** See the file "LICENSE" for more information ** ** $Id$ **/ package sim.app.geo.turkana; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import sim.engine.SimState; import sim.engine.Steppable; import sim.field.geo.GeomGridField; import sim.field.geo.GeomGridField.GridDataType; import sim.field.grid.DoubleGrid2D; import sim.field.grid.IntGrid2D; import sim.field.grid.SparseGrid2D; import sim.io.geo.ArcInfoASCGridExporter; import sim.io.geo.ArcInfoASCGridImporter; /* * TurkanaSouthModel * Main simulation class for the TurkanaSouth model. * * Author: Joey Harrison & Mark Coletti * */ public class TurkanaSouthModel extends SimState { private static final long serialVersionUID = 1L; GeomGridField populationDensityGrid; // integer [0,inf] indicating relative density DoubleGrid2D rainGrid; // double [0,inf] indicating rain in mm/hr GeomGridField[] monthlyRainGrids; // array of rain grids GeomGridField NdviGrid; // double [0,1] indicating level of vegetation DoubleGrid2D vegetationGrid; // double [0,maxVegetationLevel] SparseGrid2D agentGrid; ArrayList<Turkanian> agents = new ArrayList<Turkanian>(); public int ticksPerMonth = 1; public int getTicksPerMonth() { return ticksPerMonth; } public void setTicksPerMonth(int val) { ticksPerMonth = val; } public double vegetationGrowthRate = 0.1; // for tweaking the vegetation growth public double getVegetationGrowthRate() { return vegetationGrowthRate; } public void setVegetationGrowthRate(double val) { vegetationGrowthRate = val; } public double vegetationConsumptionRate = 0.1; // how much vegetation a herd can eat in a month public double getVegetationConsumptionRate() { return vegetationConsumptionRate; } public void setVegetationConsumptionRate(double val) { vegetationConsumptionRate = val; } public double maxVegetationLevel = 1; public double getMaxVegetationLevel() { return maxVegetationLevel; } public void setMaxVegetationLevel(double val) { maxVegetationLevel = val; } public double energyPerUnitOfVegetation = 15; // energy gained from eating one unit of vegetation public double getEnergyPerUnitOfVegetation() { return energyPerUnitOfVegetation; } public void setEnergyPerUnitOfVegetation(double val) { energyPerUnitOfVegetation = val; } public double birthEnergy = 20; // new agents/herds begin with this much energy public double getBirthEnergy() { return birthEnergy; } public void setBirthEnergy(double val) { birthEnergy = val; } public double energyConsumptionRate = 1; // energy used per month public double getEnergyConsumptionRate() { return energyConsumptionRate; } public void setEnergyConsumptionRate(double val) { energyConsumptionRate = val; } public double starvationLevel = -2; // cows can survive for up to 60 days without food public double getStarvationLevel() { return starvationLevel; } public void setStarvationLevel(double val) { starvationLevel = val; } public boolean initWithNDVI = true; // if false, the initial vegetaion will be zero public boolean getInitWithNDVI() { return initWithNDVI; } public void setInitWithNDVI(boolean val) { initWithNDVI = val; } public int numberOfAgents = 50; public int getNumberOfAgents() { return numberOfAgents; } public void setNumberOfAgents(int val) { numberOfAgents = val; } public int herderVision = 1; // how far away herders look when considering where to go (not yet implemented) // public int getHerderVision() { return herderVision; } // public void setHerderVision(int val) { herderVision = val; } public int windowWidth = 400; // public int getWindowWidth() { return windowWidth; } // public void setWindowWidth(int val) { windowWidth = val; } public int windowHeight = 400; // public int getWindowHeight() { return windowHeight; } // public void setWindowHeight(int val) { windowHeight = val; } public boolean printStats = true; // useful for printing the stats when running from the cmd line but not the gui public int monthsOfWeather = 144; // there are 144 files of monthly rainfall data public int month = 0; // current month public TurkanaSouthModel(long seed) { super(seed); } @Override public void finish() { super.finish(); // This is an example of how to automatically write grid data when the // simulation finishes. try { // Write out the population density grid field; it should be exactly // like "data/tspop2007.txt". BufferedWriter fos = new BufferedWriter( new FileWriter("newpop.asc") ); ArcInfoASCGridExporter.write(this.populationDensityGrid, fos); fos.close(); } catch (IOException ex) { Logger.getLogger(TurkanaSouthModel.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void start() { super.start(); month = 0; try { // Read the raster GIS data populationDensityGrid = new GeomGridField(); InputStream inputStream = TurkanaSouthModel.class.getResourceAsStream("data/tspop2007.txt"); ArcInfoASCGridImporter.read(inputStream, GridDataType.INTEGER, populationDensityGrid); // Example of how to use GDAL to read the same dataset // URL inputSource = TurkanaSouthModel.class.getResource("data/turkana/tspop2007.txt"); // GDALImporter.read(inputSource, GridDataType.INTEGER, populationDensityGrid); NdviGrid = new GeomGridField(); inputStream = TurkanaSouthModel.class.getResourceAsStream("data/ts_ndvi.txt"); ArcInfoASCGridImporter.read(inputStream, GridDataType.DOUBLE, NdviGrid); // Read all 144 months of rainfall data into an array monthlyRainGrids = new GeomGridField[monthsOfWeather]; for (int i = 0; i < monthsOfWeather; i++) { monthlyRainGrids[i] = new GeomGridField(); inputStream = TurkanaSouthModel.class.getResourceAsStream(String.format("data/%d.txt", i + 1)); ArcInfoASCGridImporter.read(inputStream, GridDataType.DOUBLE, monthlyRainGrids[i]); } // rainGrid will hold the current month's rainfall data. Just need the dimensions for now. rainGrid = (DoubleGrid2D) monthlyRainGrids[0].getGrid(); } catch (Exception e) { e.printStackTrace(); } // create the agent and vegetation grids to match the pop. grid's dimensions agentGrid = new SparseGrid2D(populationDensityGrid.getGridWidth(), populationDensityGrid.getGridHeight()); vegetationGrid = new DoubleGrid2D(populationDensityGrid.getGridWidth(), populationDensityGrid.getGridHeight()); if (initWithNDVI) { vegetationGrid.setTo((DoubleGrid2D)NdviGrid.getGrid()); } createInitialPopulation(); for (int i = 0; i < numberOfAgents; i++) { schedule.scheduleOnce(agents.get(i)); } schedule.scheduleRepeating(new Steppable() { @Override public void step(SimState state) { // check to see if it's time to switch months and rain grids if (schedule.getSteps() % ticksPerMonth == 0) { rainGrid.setTo((DoubleGrid2D)monthlyRainGrids[month % monthlyRainGrids.length].getGrid()); month++; } // grow the grass for (int j = 0; j < vegetationGrid.getHeight(); j++) { for (int i = 0; i < vegetationGrid.getWidth(); i++) { double rainfall = getRainfall(i, j); vegetationGrid.field[i][j] += 1.057 * Math.pow((rainfall / ticksPerMonth), 1.001) * ((DoubleGrid2D)NdviGrid.getGrid()).field[i][j] * vegetationGrowthRate; vegetationGrid.field[i][j] = clamp(vegetationGrid.field[i][j], 0, maxVegetationLevel); } } if (printStats) { System.out.format("Step: %d Population: %d\n", schedule.getSteps(), agents.size()); } } }); } /** * Clamp the given value to be between min and max. */ private double clamp(double value, double min, double max) { if (value < min) { return min; } if (value > max) { return max; } return value; } /** * Create the initial population based on the prior population densities. */ public void createInitialPopulation() { int width = populationDensityGrid.getGridWidth(); int height = populationDensityGrid.getGridHeight(); int length = width * height; double total = 0; double cumul[] = new double[length]; int k = 0; // calculate a 1D array of cumulative probabilities for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { total += ((IntGrid2D)populationDensityGrid.getGrid()).field[i][j]; cumul[k++] = total; } } // create the agents and add them agents.clear(); for (int i = 0; i < numberOfAgents; i++) { double val = random.nextDouble() * total; // [0,total) int index = linearSearch(cumul, val); if (index == -1) { // this should never happen System.out.println("ERROR: population sampling range failure."); continue; } // calculate the x and y indices based on the linear index int x = index % width; int y = index / width; Turkanian t = new Turkanian(this, x, y); t.energy = random.nextDouble() * birthEnergy; agents.add(t); agentGrid.setObjectLocation(t, x, y); } } /** * @return the current rainfall corresponding to the given coordinates in the vegetation grid. */ public double getRainfall(int i, int j) { int vWidth = vegetationGrid.getWidth(); int vHeight = vegetationGrid.getHeight(); int rWidth = rainGrid.getWidth(); int rHeight = rainGrid.getHeight(); // calculate the width and height ratios between the rain and veg grid. // Since we're using these to rescale the *index* and arrays are zero-based, // we need to subtract one. For example (in 1-d): // rWidth = 3 (indices: 0,1,2), vWidth = 4 (indices: 0,1,2,3) // r_per_v_width = (3-1) / (4-1) = 2/3 = 0.667 // // i = 0: rx = round(0 * 0.667) = 0 // i = 1: rx = round(1 * 0.667) = 1 // i = 2: rx = round(2 * 0.667) = 1 // i = 3: rx = round(3 * 0.667) = 2 double r_per_v_width = (rWidth - 1.0) / (vWidth - 1.0); double r_per_v_height = (rHeight - 1.0) / (vHeight - 1.0); int rx = (int) Math.round(i * r_per_v_width); int ry = (int) Math.round(j * r_per_v_height); // this was crucial during debugging if ((rx >= rWidth) || (ry >= rHeight)) { System.out.format("ERROR: getRainfall index calculation out of range.\n"); return 0; } return rainGrid.field[rx][ry]; } /** * Create offspring of the current agent and add them to the grid in the same cell. * @param parent */ public void createOffspring(Turkanian parent) { if (parent.energy <= birthEnergy) { return; } Turkanian offspring = new Turkanian(this, parent.x, parent.y); parent.energy -= birthEnergy; offspring.energy = 0; agents.add(offspring); agentGrid.setObjectLocation(offspring, offspring.x, offspring.y); schedule.scheduleOnce(offspring); } /** * Remove an agent who has died. */ public void removeAgent(Turkanian t) { agents.remove(t); agentGrid.remove(t); } /** * Find the index of the given value in the given array. If the value isn't * in the array, it returns the first one larger than the value. */ static public int linearSearch(double[] array, double value) { for (int i = 0; i < array.length; i++) { if (value <= array[i]) { return i; } } return -1; } /** * Main function, runs the simulation without any visualization. * @param args */ public static void main(String[] args) { doLoop(TurkanaSouthModel.class, args); System.exit(0); } }
33.58396
178
0.614627
717338f80ade2ee323b125e405e8691aa40d859d
900
package io.quarkus.security.test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; /** * Tests of a CUSTOM authentication mechanism that uses the BASIC authentication headers */ public class CustomAuthEmbeddedEncryptedTestCase extends CustomAuthEmbeddedBase { static Class[] testClasses = { TestSecureServlet.class, TestApplication.class, RolesEndpointClassLevel.class, ParametrizedPathsResource.class, SubjectExposingResource.class }; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(testClasses) .addClasses(CustomAuth.class) .addAsResource("application-custom-auth-embedded-encrypted.properties", "application.properties")); }
39.130435
91
0.701111
5dad36f93a6a59ed57e9c3e2e673dd009b044481
14,464
/* * Copyright 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 androidx.fragment.app; import static org.junit.Assert.assertEquals; import android.app.Activity; import android.app.Instrumentation; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Parcelable; import android.os.SystemClock; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.Animation; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.fragment.app.test.FragmentTestActivity; import androidx.lifecycle.ViewModelStore; import androidx.lifecycle.ViewModelStoreOwner; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.rule.ActivityTestRule; import java.io.FileDescriptor; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.util.ArrayList; public class FragmentTestUtil { private static final Runnable DO_NOTHING = new Runnable() { @Override public void run() { } }; public static void waitForExecution(final ActivityTestRule<? extends FragmentActivity> rule) { // Wait for two cycles. When starting a postponed transition, it will post to // the UI thread and then the execution will be added onto the queue after that. // The two-cycle wait makes sure fragments have the opportunity to complete both // before returning. try { rule.runOnUiThread(DO_NOTHING); rule.runOnUiThread(DO_NOTHING); } catch (Throwable throwable) { throw new RuntimeException(throwable); } } private static void runOnUiThreadRethrow(ActivityTestRule<? extends Activity> rule, Runnable r) { if (Looper.getMainLooper() == Looper.myLooper()) { r.run(); } else { try { rule.runOnUiThread(r); } catch (Throwable t) { throw new RuntimeException(t); } } } public static boolean executePendingTransactions( final ActivityTestRule<? extends FragmentActivity> rule) { FragmentManager fragmentManager = rule.getActivity().getSupportFragmentManager(); return executePendingTransactions(rule, fragmentManager); } public static boolean executePendingTransactions( final ActivityTestRule<? extends Activity> rule, final FragmentManager fm) { final boolean[] ret = new boolean[1]; runOnUiThreadRethrow(rule, new Runnable() { @Override public void run() { ret[0] = fm.executePendingTransactions(); } }); return ret[0]; } public static boolean popBackStackImmediate(final ActivityTestRule<FragmentTestActivity> rule) { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); final boolean[] ret = new boolean[1]; instrumentation.runOnMainSync(new Runnable() { @Override public void run() { ret[0] = rule.getActivity().getSupportFragmentManager().popBackStackImmediate(); } }); return ret[0]; } public static boolean popBackStackImmediate(final ActivityTestRule<FragmentTestActivity> rule, final int id, final int flags) { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); final boolean[] ret = new boolean[1]; instrumentation.runOnMainSync(new Runnable() { @Override public void run() { ret[0] = rule.getActivity().getSupportFragmentManager().popBackStackImmediate(id, flags); } }); return ret[0]; } public static boolean popBackStackImmediate(final ActivityTestRule<FragmentTestActivity> rule, final String name, final int flags) { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); final boolean[] ret = new boolean[1]; instrumentation.runOnMainSync(new Runnable() { @Override public void run() { ret[0] = rule.getActivity().getSupportFragmentManager().popBackStackImmediate(name, flags); } }); return ret[0]; } public static void setContentView(final ActivityTestRule<FragmentTestActivity> rule, final int layoutId) { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); instrumentation.runOnMainSync(new Runnable() { @Override public void run() { rule.getActivity().setContentView(layoutId); } }); } public static void assertChildren(ViewGroup container, Fragment... fragments) { final int numFragments = fragments == null ? 0 : fragments.length; assertEquals("There aren't the correct number of fragment Views in its container", numFragments, container.getChildCount()); for (int i = 0; i < numFragments; i++) { assertEquals("Wrong Fragment View order for [" + i + "]", container.getChildAt(i), fragments[i].getView()); } } public static FragmentController createController( ActivityTestRule<? extends FragmentActivity> rule) { final FragmentController[] controller = new FragmentController[1]; final FragmentActivity activity = rule.getActivity(); runOnUiThreadRethrow(rule, new Runnable() { @Override public void run() { Handler handler = new Handler(); androidx.fragment.app.HostCallbacks hostCallbacks = new androidx.fragment.app.HostCallbacks(activity, handler, 0); controller[0] = FragmentController.createController(hostCallbacks); } }); return controller[0]; } public static void resume(ActivityTestRule<? extends Activity> rule, final FragmentController fragmentController, final Pair<Parcelable, FragmentManagerNonConfig> savedState) { runOnUiThreadRethrow(rule, new Runnable() { @Override public void run() { fragmentController.attachHost(null); if (savedState != null) { fragmentController.restoreAllState(savedState.first, savedState.second); } fragmentController.dispatchCreate(); fragmentController.dispatchActivityCreated(); fragmentController.noteStateNotSaved(); fragmentController.execPendingActions(); fragmentController.dispatchStart(); fragmentController.dispatchResume(); fragmentController.execPendingActions(); } }); } public static Pair<Parcelable, FragmentManagerNonConfig> destroy( ActivityTestRule<? extends Activity> rule, final FragmentController fragmentController) { final Pair<Parcelable, FragmentManagerNonConfig>[] result = new Pair[1]; runOnUiThreadRethrow(rule, new Runnable() { @Override public void run() { fragmentController.dispatchPause(); final Parcelable savedState = fragmentController.saveAllState(); final FragmentManagerNonConfig nonConfig = fragmentController.retainNestedNonConfig(); fragmentController.dispatchStop(); fragmentController.dispatchDestroy(); result[0] = Pair.create(savedState, nonConfig); } }); return result[0]; } public static boolean waitForAnimationEnd(long timeout, final Animation animation) { long endTime = SystemClock.uptimeMillis() + timeout; final boolean[] hasEnded = new boolean[1]; Runnable check = new Runnable() { @Override public void run() { hasEnded[0] = animation.hasEnded(); } }; Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); do { SystemClock.sleep(10); instrumentation.runOnMainSync(check); } while (!hasEnded[0] && SystemClock.uptimeMillis() < endTime); return hasEnded[0]; } /** * Allocates until a garbage collection occurs. */ public static void forceGC() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { // The following works on O+ Runtime.getRuntime().gc(); Runtime.getRuntime().gc(); Runtime.getRuntime().runFinalization(); } else { // The following works on older versions for (int i = 0; i < 2; i++) { // Use a random index in the list to detect the garbage collection each time because // .get() may accidentally trigger a strong reference during collection. ArrayList<WeakReference<byte[]>> leak = new ArrayList<>(); do { WeakReference<byte[]> arr = new WeakReference<byte[]>(new byte[100]); leak.add(arr); } while (leak.get((int) (Math.random() * leak.size())).get() != null); } } } static class HostCallbacks extends FragmentHostCallback<FragmentActivity> implements ViewModelStoreOwner { private final FragmentActivity mActivity; private final ViewModelStore mViewModelStore; HostCallbacks(FragmentActivity activity, ViewModelStore viewModelStore) { super(activity); mActivity = activity; mViewModelStore = viewModelStore; } @NonNull @Override public ViewModelStore getViewModelStore() { return mViewModelStore; } @Override public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { } @Override public boolean onShouldSaveFragmentState(Fragment fragment) { return !mActivity.isFinishing(); } @Override @NonNull public LayoutInflater onGetLayoutInflater() { return mActivity.getLayoutInflater().cloneInContext(mActivity); } @Override public FragmentActivity onGetHost() { return mActivity; } @Override public void onSupportInvalidateOptionsMenu() { mActivity.supportInvalidateOptionsMenu(); } @Override public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode) { mActivity.startActivityFromFragment(fragment, intent, requestCode); } @Override public void onStartActivityFromFragment( Fragment fragment, Intent intent, int requestCode, @Nullable Bundle options) { mActivity.startActivityFromFragment(fragment, intent, requestCode, options); } @Override public void onRequestPermissionsFromFragment(@NonNull Fragment fragment, @NonNull String[] permissions, int requestCode) { throw new UnsupportedOperationException(); } @Override public boolean onShouldShowRequestPermissionRationale(@NonNull String permission) { return ActivityCompat.shouldShowRequestPermissionRationale( mActivity, permission); } @Override public boolean onHasWindowAnimations() { return mActivity.getWindow() != null; } @Override public int onGetWindowAnimations() { final Window w = mActivity.getWindow(); return (w == null) ? 0 : w.getAttributes().windowAnimations; } @Override public void onAttachFragment(Fragment fragment) { mActivity.onAttachFragment(fragment); } @Nullable @Override public View onFindViewById(int id) { return mActivity.findViewById(id); } @Override public boolean onHasView() { final Window w = mActivity.getWindow(); return (w != null && w.peekDecorView() != null); } } public static FragmentController startupFragmentController(FragmentActivity activity, Parcelable savedState, ViewModelStore viewModelStore) { final FragmentController fc = FragmentController.createController( new HostCallbacks(activity, viewModelStore)); fc.attachHost(null); fc.restoreSaveState(savedState); fc.dispatchCreate(); fc.dispatchActivityCreated(); fc.noteStateNotSaved(); fc.execPendingActions(); fc.dispatchStart(); fc.dispatchResume(); fc.execPendingActions(); return fc; } public static FragmentController restartFragmentController(FragmentActivity activity, FragmentController fc, ViewModelStore viewModelStore) { Parcelable savedState = shutdownFragmentController(fc, viewModelStore); return startupFragmentController(activity, savedState, viewModelStore); } public static Parcelable shutdownFragmentController(FragmentController fc, ViewModelStore viewModelStore) { fc.dispatchPause(); final Parcelable savedState = fc.saveAllState(); fc.dispatchStop(); viewModelStore.clear(); fc.dispatchDestroy(); return savedState; } }
37.568831
100
0.633435
2e4a309c74bc3e3f6a5ccfb6910ef167796bb6ce
288
package tk.traiders.ui.markets.children; import tk.traiders.ui.markets.children.util.ParityFragment; public class CurrencyFragment extends ParityFragment { @Override protected String getURL() { return "https://api.traiders.tk/parity/latest?category=currency"; } }
22.153846
73
0.743056
93753ddb9f0259cedb5ddedcd1a7bd9524f2b5f2
1,035
package timely.testing; import java.util.Map; import java.util.Random; public class MetricPut { private String metric = null; private Map<String, String> tags; private Random r = new Random(); public MetricPut(String metric, Map<String, String> tags) { this.metric = metric; this.tags = tags; } public String formatTcp(long timestamp, Double value) { StringBuilder sb = new StringBuilder(); sb.append("put "); sb.append(metric).append(" "); sb.append(Long.toString(timestamp)).append(" "); sb.append(Double.toString(value)); for (Map.Entry<String, String> entry : tags.entrySet()) { sb.append(" "); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } sb.append("\n"); return sb.toString(); } public String generateTcpLine(long timestamp) { double value = r.nextInt(1000) / 1.0; return formatTcp(timestamp, value); } }
26.538462
65
0.586473
b22ca1f9d767a46a4ef1cca489c7bed7437c4439
1,280
package cminor.ast; import java.util.List; import cminor.parser.LocationInfo; import cminor.symbol.StringSymbol; import cminor.visit.Visitor; public class PrintStatement extends Statement { public static final String TRUE_STRING = "true"; public static final String FALSE_STRING = "false"; public static final String BOOL_STRING = FALSE_STRING + "\0" + TRUE_STRING; public static final int OFFSET = FALSE_STRING.length() + 1; public static final String CHAR_FORMAT = "%c"; public static final String INT_FORMAT = "%d"; public static final String STRING_FORMAT = "%s"; private List<Expression> arguments; private StringSymbol symbol; private List<Expression> actualArguments; public PrintStatement(LocationInfo info, List<Expression> arguments) { super(info); this.arguments = arguments; } public List<Expression> getArguments() { return this.arguments; } public StringSymbol getSymbol() { return this.symbol; } public void setSymbol(StringSymbol symbol) { this.symbol = symbol; } public List<Expression> getActualArguments() { return this.actualArguments; } public void setActualArguments(List<Expression> actualArguments) { this.actualArguments = actualArguments; } public void accept(Visitor v) { v.visit(this); } }
24.150943
76
0.751563
f4a25a895d9c41c852e5c278b5cf57cd0b49a508
1,655
/* * 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.accolite.pru.health.AuthApp.event; import com.accolite.pru.health.AuthApp.model.PasswordResetToken; import org.springframework.context.ApplicationEvent; import org.springframework.web.util.UriComponentsBuilder; public class OnGenerateResetLinkEvent extends ApplicationEvent { private transient UriComponentsBuilder redirectUrl; private transient PasswordResetToken passwordResetToken; public OnGenerateResetLinkEvent(PasswordResetToken passwordResetToken, UriComponentsBuilder redirectUrl) { super(passwordResetToken); this.passwordResetToken = passwordResetToken; this.redirectUrl = redirectUrl; } public PasswordResetToken getPasswordResetToken() { return passwordResetToken; } public void setPasswordResetToken(PasswordResetToken passwordResetToken) { this.passwordResetToken = passwordResetToken; } public UriComponentsBuilder getRedirectUrl() { return redirectUrl; } public void setRedirectUrl(UriComponentsBuilder redirectUrl) { this.redirectUrl = redirectUrl; } }
33.77551
110
0.764955
bf7374347b44f11de9ba9ae658d0ad58547364a4
4,219
package com.example.pay.controller; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.domain.AlipayTradeWapPayModel; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayTradeWapPayRequest; import com.example.pay.configuration.AlipayProperties; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.UUID; /** * 支付宝-手机网站支付. * <p> * 手机网站支付 * * @author Mengday Zhang * @version 1.0 * @since 2018/6/11 */ @Slf4j @Controller @RequestMapping("/alipay/wap") public class AlipayWAPPayController { @Autowired private AlipayProperties alipayProperties; @Autowired private AlipayClient alipayClient; /** * 去支付 * * 支付宝返回一个form表单,并自动提交,跳转到支付宝页面 * * @param response * @throws Exception */ @PostMapping("/gotoPayPage") public void gotoPayPage(HttpServletResponse response) throws AlipayApiException, IOException { // 订单模型 String productCode="QUICK_WAP_WAY"; AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); model.setOutTradeNo(UUID.randomUUID().toString()); model.setSubject("支付测试"); model.setTotalAmount("1.00"); model.setBody("支付测试,共1.00元"); model.setTimeoutExpress("5m"); model.setProductCode(productCode); AlipayTradeWapPayRequest wapPayRequest =new AlipayTradeWapPayRequest(); wapPayRequest.setReturnUrl("http://doudh.wicp.vip/alipay/wap/returnUrl"); wapPayRequest.setNotifyUrl(alipayProperties.getNotifyUrl()); wapPayRequest.setBizModel(model); // 调用SDK生成表单, 并直接将完整的表单html输出到页面 String form = alipayClient.pageExecute(wapPayRequest).getBody(); System.out.println(form); response.setContentType("text/html;charset=" + alipayProperties.getCharset()); response.getWriter().write(form); response.getWriter().flush(); response.getWriter().close(); } /** * 支付宝页面跳转同步通知页面 * @param request * @return * @throws UnsupportedEncodingException * @throws AlipayApiException */ @RequestMapping("/returnUrl") public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException { response.setContentType("text/html;charset=" + alipayProperties.getCharset()); //获取支付宝GET过来反馈信息 Map<String,String> params = new HashMap<>(); Map requestParams = request.getParameterMap(); for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ","; } //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化 valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); params.put(name, valueStr); } boolean verifyResult = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), "RSA2"); if(verifyResult){ //验证成功 //请在这里加上商户的业务逻辑程序代码,如保存支付宝交易号 //商户订单号 String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); //支付宝交易号 String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); return "wapPaySuccess"; }else{ return "wapPayFail"; } } }
34.300813
144
0.674804
8abf0390189bde63e0137c57279f8068d19f0e50
10,911
package me.jessyan.mvpart.demo.app.utils.net.sign; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; import javax.crypto.Cipher; /** * 掌沃验签相关的类 * Created by tao on 2016-07-14. */ public class RSAUtils { public static final String KEY_ALGORITHM = "RSA"; public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; public static final String PUBLIC_KEY = "RSAPublicKey"; public static final String PRIVATE_KEY = "RSAPrivateKey"; private static final int MAX_ENCRYPT_BLOCK = 117; private static final int MAX_DECRYPT_BLOCK = 128; private static final int PRIVATE_KEY_LENGTH = 1024; //公钥 public static final String RSA = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfpp4gBXCsMwlahzypEYMdKFRxLaQWZKPkry3T4MglyoIy0eJAsxAYnEixNgkzBWNu2fqXfxupEfq423+VcQLwgFPawvxjel8I3gTihO2saOdsTWmbaVu/zzqOBiT2xB7gJu8MW2dXPHmw9pZI8FdS2GH9wWQS8BxvWN2f8MLOlwIDAQAB"; public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map keyMap = new HashMap(2); keyMap.put("RSAPublicKey", publicKey); keyMap.put("RSAPrivateKey", privateKey); return keyMap; } public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateK); signature.update(data); return EncryptionUtils.encodeToStringBASE64(signature.sign()); } public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(publicKey); System.out.println("keyBytes =" + keyBytes); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initVerify(publicK); signature.update(data); return signature.verify(EncryptionUtils.decodeBASE64(sign)); } private static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(2, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; while (inputLen - offSet > 0) { byte[] cache; if (inputLen - offSet > 128) cache = cipher.doFinal(encryptedData, offSet, 128); else { cache = cipher .doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * 128; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } private static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(2, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; while (inputLen - offSet > 0) { byte[] cache; if (inputLen - offSet > 128) cache = cipher.doFinal(encryptedData, offSet, 128); else { cache = cipher .doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * 128; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } private static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(1, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; while (inputLen - offSet > 0) { byte[] cache; if (inputLen - offSet > 117) cache = cipher.doFinal(data, offSet, 117); else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * 117; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } private static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = EncryptionUtils.decodeBASE64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(1, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; while (inputLen - offSet > 0) { byte[] cache; if (inputLen - offSet > 117) cache = cipher.doFinal(data, offSet, 117); else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * 117; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get("RSAPrivateKey"); return EncryptionUtils.encodeToStringBASE64(key.getEncoded()); } public static String getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get("RSAPublicKey"); return EncryptionUtils.encodeToStringBASE64(key.getEncoded()); } /** * 加密方法 * * @param value 需要加密参数 * @param publicKey 公钥 * @return 返回加密后参数 */ public static String sensitiveEncrypt(String value, String publicKey) { try { return EncryptionUtils.encodeToStringBASE64(encryptByPublicKey(value.getBytes(), publicKey)); } catch (Exception e) { e.printStackTrace(); Log.e("sensitiveEncrypt_e ", e.toString()); } return ""; } /** * RSA加密方法 * * @param value 需要加密的值 * @return 加密后的值 */ public static String sensitiveEncryptWithRSA(String value) { return sensitiveEncrypt(md5(value), RSA); } /** * 进行md5加密 * * @param str 需要加密md5的字符串 * @return */ public static String md5(String str) { if (str == null) { return null; } MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { return str; } catch (UnsupportedEncodingException e) { return str; } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append( Integer.toHexString(0xFF & byteArray[i])); else { md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } } return md5StrBuff.toString(); } public static String sensitiveDecrypt(String value, String privateKey) { try { return new String(decryptByPrivateKey(EncryptionUtils.decodeBASE64(value), privateKey)); } catch (Exception e) { e.printStackTrace(); Log.e("sensitiveDecrypt_e ", e.toString()); } return ""; } /** * 解密方法 * * @param value 接收加密参数 * @param publicKey 公钥 * @return 返回解密后参数 */ public static String sensitiveDecryptByPublicKey(String value, String publicKey) { try { return new String(decryptByPublicKey(EncryptionUtils.decodeBASE64(value), publicKey)); } catch (Exception e) { e.printStackTrace(); Log.e("sensitiveDecrypt_e",e.toString()); } return ""; } }
35.891447
256
0.623774
1073a2f682e72fe37fe56c06dcaa45ed7bd68641
1,979
package gov.loc.repository.bagit.conformance.profile; import java.io.File; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class BagitProfileDeserializerTest extends AbstractBagitProfileTest{ @Test public void testDeserialize() throws Exception{ BagitProfile expectedProfile = createExpectedProfile(); BagitProfile profile = mapper.readValue(new File("src/test/resources/bagitProfiles/exampleProfile.json"), BagitProfile.class); Assertions.assertEquals(expectedProfile, profile); Assertions.assertEquals(expectedProfile.getAcceptableBagitVersions(), profile.getAcceptableBagitVersions()); Assertions.assertEquals(expectedProfile.getAcceptableMIMESerializationTypes(), profile.getAcceptableMIMESerializationTypes()); Assertions.assertEquals(expectedProfile.getBagInfoRequirements(), profile.getBagInfoRequirements()); Assertions.assertEquals(expectedProfile.getBagitProfileIdentifier(), profile.getBagitProfileIdentifier()); Assertions.assertEquals(expectedProfile.getContactEmail(), profile.getContactEmail()); Assertions.assertEquals(expectedProfile.getContactName(), profile.getContactName()); Assertions.assertEquals(expectedProfile.getExternalDescription(), profile.getExternalDescription()); Assertions.assertEquals(expectedProfile.getManifestTypesRequired(), profile.getManifestTypesRequired()); Assertions.assertEquals(expectedProfile.getSerialization(), profile.getSerialization()); Assertions.assertEquals(expectedProfile.getSourceOrganization(), profile.getSourceOrganization()); Assertions.assertEquals(expectedProfile.getTagFilesRequired(), profile.getTagFilesRequired()); Assertions.assertEquals(expectedProfile.getTagManifestTypesRequired(), profile.getTagManifestTypesRequired()); Assertions.assertEquals(expectedProfile.getVersion(), profile.getVersion()); Assertions.assertEquals(expectedProfile.hashCode(), profile.hashCode()); } }
56.542857
130
0.81809
ce89669fde78c60d1e7bd0c2fc04066531d97759
479
package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class SampleController { @GetMapping("/sample") public String showForm() { return "sample"; } @GetMapping("/sample2") public String showForm2() { return "sample2"; } @GetMapping("/sample3") public String showForm3() { return "sample3"; } }
19.16
58
0.653445
71c270fba97106e4fdaa693f7f9c49fb4bc8d42b
2,595
package io.github.bycubed7.lifestealcore.commands; import java.util.List; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import io.github.bycubed7.corecubes.CubePlugin; import io.github.bycubed7.corecubes.commands.Action; import io.github.bycubed7.corecubes.commands.ActionUse; import io.github.bycubed7.corecubes.commands.Arg; import io.github.bycubed7.corecubes.commands.Execution; import io.github.bycubed7.corecubes.managers.ConfigManager; import io.github.bycubed7.corecubes.managers.Debug; import io.github.bycubed7.corecubes.managers.Tell; import io.github.bycubed7.lifestealcore.managers.MemberManager; import io.github.bycubed7.lifestealcore.units.Member; public class CommandSet extends Action { private String feedbackMessage = "Updated your hearts!"; public CommandSet(CubePlugin _plugin) { super("Set", _plugin); ConfigManager config = new ConfigManager(plugin, "LifeStealCore.yml"); feedbackMessage = config.getString("messages."+name.toLowerCase()); } @Override protected void setupArguments(List<ActionUse> arguments) { arguments.add( ActionUse.create() .add(Arg.create("player", "PLAYER")) .add(Arg.create("value", "20")) ); arguments.add( ActionUse.create() .add(Arg.create("value", "20")) ); } @Override protected Execution approved(Player player, Map<String, String> args) { String targetPlayerName = args.get("player"); String targetTransferAmount = args.getOrDefault("value", "2"); Debug.log("targetPlayerName : " + targetPlayerName); Debug.log("targetTransferAmount : " + targetTransferAmount); if (targetPlayerName == null) return Execution.createFail() .setReason("Can't find player to set!"); // Check the argument is a number try { Integer.parseInt(targetTransferAmount); } catch (NumberFormatException ex) { return Execution.USAGE; } return Execution.NONE; } @Override protected boolean execute(Player player, Map<String, String> args) { String targetPlayerName = args.get("player"); String targetTransferAmount = args.getOrDefault("value", "2"); // Iterate through all except the last argument Player foundPlayer = Bukkit.getPlayer(targetPlayerName); int transferAmount = Integer.parseInt(targetTransferAmount); Member member = MemberManager.getMember(foundPlayer); member.setHearts(transferAmount); member.updateHearts(); member.updateGamemode(); MemberManager.setMember(member); Tell.player(foundPlayer, feedbackMessage); MemberManager.saveToConfig(); return true; } }
28.516484
72
0.746435
5f10871ba833eae89a7c4661da0a3e0ed9bb0835
713
//package com.lujiahao.canal.client.mq; // //import org.springframework.beans.factory.annotation.Value; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // ///** // * RocketMQ生产者配置 // * @author lujiahao // * @date 2018/10/21 // */ //@Configuration //public class MqProducerConfig { // // /** // * // * @param namesrvAddr // * @return // */ // @Bean // public RocketMqProducer testCanalProducer(@Value("${rocketUrl}") String namesrvAddr) { // String groupName = "businessGroup"; // String instanceName = "businessMq"; // return new RocketMqProducer(groupName, namesrvAddr, instanceName); // } //}
26.407407
92
0.657784
fc16c19a930f0ea84f10126521eb24e91050a9a7
3,107
package app.services; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import javax.swing.BorderFactory; import javax.swing.border.Border; public class RecursosService { private Color cyan, cyanOscuro, verdeClaro, verde, verdePastel, morado, moradoClaro; private Font fuenteTitulo, fuenteVersion, fuenteOpcion, fuenteTituloJuego, fuenteSubtitulo; private Cursor cMano; private Border borderGris, borderNegro; private int size; static private RecursosService servicio; private RecursosService(){ //Paletas de colores---------------------------------------------------------- //paleta estándar cyan = new Color(72, 206, 247); cyanOscuro = new Color(70, 147, 171); //paleta verde pastel complementario verdeClaro = new Color(193, 255, 171); verde = new Color(122, 179, 102); verdePastel = new Color(212, 255, 196); morado = new Color(179, 84, 167); moradoClaro = new Color(255, 171, 245); //Fuentes--------------------------------------------------------------------- //fuentes estándar fuenteTitulo = new Font("Gill Sans MT Condensed", Font.PLAIN, 64); fuenteSubtitulo = new Font("Gill Sans MT Condensed", Font.PLAIN, 32); fuenteTituloJuego = new Font("Imprint MT Shadow", Font.PLAIN, 72); fuenteVersion = new Font("Arial", Font.PLAIN, 14); fuenteOpcion = new Font("Arial Narrow", Font.PLAIN, 18); //Cursores //cursores estándar cMano = new Cursor(Cursor.HAND_CURSOR); //Borders //bordes estándar borderNegro = BorderFactory.createLineBorder(Color.black, 2, true); borderGris = BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2, true); } public Color getColorCyan(){ return cyan; } public Color getColorCyanOscuro(){ return cyanOscuro; } public Color getColorVerdeClaro(){ return verdeClaro; } public Color getColorVerde(){ return verde; } public Color getColorVerdePastel(){ return verdePastel; } public Color getColorMorado(){ return morado; } public Color getColorMoradoClaro(){ return moradoClaro; } public Font getFuenteTitulo(){ return fuenteTitulo; } public Font getFuenteSubtitulo(){ return fuenteSubtitulo; } public Font getFuenteTituloJuego(){ return fuenteTituloJuego; } public Font getFuenteVersion(){ return fuenteVersion; } public Font getFuenteOpcion(){ return fuenteOpcion; } public Cursor getCursorMano(){ return cMano; } public Border getBorderGris(){ return borderGris; } public Border getBorderNegro(){ return borderNegro; } public static RecursosService getService(){ if(servicio == null){ servicio = new RecursosService(); } return servicio; } }
26.784483
95
0.590602
9373128c7b9c70c8b436addf67b66f733b51618e
296
package org.uma.jmetal.auto.component.evaluation; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.observable.ObservableEntity; import java.util.List; public interface Evaluation<S extends Solution<?>> extends ObservableEntity { List<S> evaluate(List<S> solutionList) ; }
26.909091
77
0.797297
352ace1a1798df2c5abc1ebb2c3a3a4fb9f62ccc
1,541
package com.fincatto.documentofiscal.cte300.classes; import org.junit.Assert; import org.junit.Test; public class CTCodigoSituacaoTributariaICMSTest { @Test public void deveRepresentarOCodigoCorretamente() { Assert.assertNull(CTCodigoSituacaoTributariaICMS.valueOfCodigo(null)); Assert.assertEquals("00", CTCodigoSituacaoTributariaICMS.TRIBUTACAO_INTEGRALMENTE.getCodigo()); Assert.assertEquals("10", CTCodigoSituacaoTributariaICMS.TRIBUTADA_COM_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA.getCodigo()); Assert.assertEquals("20", CTCodigoSituacaoTributariaICMS.COM_REDUCAO_BASE_CALCULO.getCodigo()); Assert.assertEquals("30", CTCodigoSituacaoTributariaICMS.ISENTA_OU_NAO_TRIBUTADA_COM_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA.getCodigo()); Assert.assertEquals("40", CTCodigoSituacaoTributariaICMS.ISENTA.getCodigo()); Assert.assertEquals("41", CTCodigoSituacaoTributariaICMS.NAO_TRIBUTADO.getCodigo()); Assert.assertEquals("50", CTCodigoSituacaoTributariaICMS.SUSPENSAO.getCodigo()); Assert.assertEquals("51", CTCodigoSituacaoTributariaICMS.DIFERIMENTO.getCodigo()); Assert.assertEquals("60", CTCodigoSituacaoTributariaICMS.ICMS_COBRADO_ANTERIORMENTE_POR_SUBSTITUICAO_TRIBUTARIA.getCodigo()); Assert.assertEquals("70", CTCodigoSituacaoTributariaICMS.COM_REDUCAO_BASE_CALCULO_COBRANCA_ICMS_POR_SUBSTITUICAO_TRIBUTARIA_ICMS_SUBSTITUICAO_TRIBUTARIA.getCodigo()); Assert.assertEquals("90", CTCodigoSituacaoTributariaICMS.OUTROS.getCodigo()); } }
61.64
172
0.814406
57b63e31d3316362f68a2a65904437beb26f956c
142
package com.paragon_software.word_of_day; import androidx.core.content.FileProvider; public class WotDFileProvider extends FileProvider { }
23.666667
54
0.84507
3b1ab632cc7b298d380e54393e350e819740db58
2,390
/* * Copyright 2019 くまねこそふと. * * 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 dev.pandasoft.simplejuke.discord.command; import dev.pandasoft.simplejuke.Main; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.util.Arrays; public class BotCommandParser { /** * 受信したメッセージをBotコマンドとして使用できる形に整形します。 * * @param prefix メッセージをコマンドとして認識する接頭辞 * @param event 受信したメッセージイベント * @return 生成されたBotコマンド */ public BotCommand parse(String prefix, MessageReceivedEvent event) { String raw = event.getMessage().getContentRaw(); String input; // 自分宛てのメンションの場合はコマンドとして認識 if (raw.startsWith(prefix)) { input = raw.substring(prefix.length()).trim(); } else if (!event.getMessage().getMentions().isEmpty()) { if (!event.getMessage().isMentioned(event.getJDA().getSelfUser())) return null; input = raw.substring(event.getJDA().getSelfUser().getAsMention().length()).trim(); // コマンドではないメッセージを無視 } else { return null; } if (input.isEmpty()) return null; // コマンドオプションを分割 String[] args = input.split("\\p{javaSpaceChar}+"); if (args.length == 0) return null; String commandTrigger = args[0]; // コマンドクラスの取得 CommandExecutor command = Main.getController().getCommandManager().getExecutor(commandTrigger.toLowerCase()); if (command == null) return null; else return new BotCommand( event.getGuild(), event.getTextChannel(), event.getMember(), event.getMessage(), commandTrigger, Arrays.copyOfRange(args, 1, args.length), command); } }
32.739726
117
0.615063
36ac5d31c1fa8305b9f8623a4a98f5cdb79ac0d2
11,899
/* * Copyright (c) 2019. Semenoff Slava */ package ex.capybara; import org.openqa.selenium.*; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class MainPages { protected MainTest mainTest; protected WebDriver driver; protected void isPageload(int loadTime, String errMsg) { isElementPresent(By.cssSelector("body"), loadTime, errMsg); } private void isElementPresent(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); getElement(locator, waitSec, errMsg); } // protected void waitForUrlToContainString_old(String URL, int waitSec, String errMsg) { // isPageload(waitSec, errMsg); // String currentUrl = driver.getCurrentUrl(); // boolean result = currentUrl.contains(URL); // Assert.assertTrue(result, errMsg); // } protected void waitForUrlToContainString(String URL, int waitSec, String errMsg) { final WebDriverWait wait = new WebDriverWait(driver, waitSec); try { wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return driver.getCurrentUrl().contains(URL); } }); } catch (TimeoutException timeout) { Assert.assertEquals(driver.getCurrentUrl().toLowerCase(), URL.toLowerCase(), errMsg + " | " + timeout.getMessage()); } } // interact with elements protected WebElement getElement(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); try { WebElement element = this.driver.findElement(locator); driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); return element; } catch (NoSuchElementException e) { System.err.print(errMsg + " | " + e.getMessage()); throw new WebDriverException(errMsg); } finally { driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } } protected void clickOnElement(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); WebElement element = getElement(locator, waitSec, errMsg); WebDriverWait wait = new WebDriverWait(driver, waitSec); wait.until(ExpectedConditions.elementToBeClickable(element)); Assert.assertTrue(element.isEnabled(), errMsg); try { element.click(); } catch (WebDriverException e) { try { JavascriptExecutor executor = (JavascriptExecutor) driver; executor.executeScript("arguments[0].click();", element); } catch (WebDriverException er) { System.err.print(errMsg + " | " + er.getMessage()); Assert.fail(errMsg + " | " + er.getMessage(), er); } } } protected void isDisplayed(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); try { WebElement element = getElement(locator, waitSec, errMsg); WebDriverWait wait = new WebDriverWait(driver, waitSec); wait.until(ExpectedConditions.visibilityOfElementLocated(locator)); Assert.assertTrue(driver.findElement(locator).isDisplayed(), errMsg); } catch (WebDriverException e) { System.err.print(errMsg + " | " + e.getMessage()); Assert.fail(errMsg + " | " + e.getMessage(), e); } finally { driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } } protected void isNotDisplayedAlready(final By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, waitSec); wait.until(ExpectedConditions.visibilityOfElementLocated(locator)); Assert.assertTrue(driver.findElement(locator).isDisplayed(), errMsg); // WebDriverWait _wait = new WebDriverWait(driver, waitSec); driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); WebDriverWait _wait = new WebDriverWait(driver, waitSec, 300); ExpectedCondition elementIsDisplayed = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver arg0) { try { driver.findElement(locator).isDisplayed(); return false; } catch (NoSuchElementException e) { // System.err.println("locator not displayed"); return true; } catch (StaleElementReferenceException f) { // System.err.println("locator not displayed"); return true; } } }; _wait.until(elementIsDisplayed); // _wait.until(ExpectedConditions.invisibilityOfElementLocated(locator)); // try { // Assert.assertTrue(!driver.findElement(locator).isDisplayed(), errMsg); // } catch (NoSuchElementException e){ // Assert.assertTrue(true); // } driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } protected void isNotVisibleAlready(final By locator, int delaySeconds, String errorMassage) { driver.manage().timeouts().implicitlyWait(delaySeconds, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, delaySeconds); wait.until(ExpectedConditions.visibilityOfElementLocated(locator)); Assert.assertTrue(driver.findElement(locator).isDisplayed(), errorMassage); WebDriverWait _wait = new WebDriverWait(driver, delaySeconds); _wait.until(ExpectedConditions.invisibilityOfElementLocated(locator)); Assert.assertTrue(!driver.findElement(locator).isDisplayed(), errorMassage); driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } protected void clearFieldAndFillItWithText(By locator, String text, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); WebElement element = getElement(locator, waitSec, errMsg); element.clear(); element.sendKeys(text); } protected void moveTo(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); WebElement element = getElement(locator, waitSec, errMsg); Actions action = new Actions(driver); action.moveToElement(element).perform(); } protected void selectedByIndex(By locator, int index, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); Select select = new Select(getElement(locator, waitSec, errMsg)); select.selectByIndex(index); } protected void selectedByText(By locator, String text, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); Select select = new Select(getElement(locator, waitSec, errMsg)); select.selectByVisibleText(text); } protected void isTextContains(By locator, String text, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); WebElement element = getElement(locator, waitSec, errMsg); String containText = element.getText().toLowerCase(); Assert.assertTrue(containText.contains(text.toLowerCase())); } protected void waitForTextEqual(final By locator, final String text, final int waitSec, final String errMsg) { final WebDriverWait wait = new WebDriverWait(driver, waitSec); try { wait.until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { WebElement element = getElement(locator, waitSec, "element did not display" + waitSec + " seconds"); String element_text = element.getText(); if (element_text.equalsIgnoreCase(text)) { return true; } else { return false; } } }); } catch (TimeoutException timeout) { String element_text = getElement(locator, waitSec, "element did not display" + waitSec + " seconds").getText(); Assert.assertEquals(element_text.toLowerCase(), text.toLowerCase(), errMsg + " | " + timeout.getMessage()); } } //! with return parameter functions protected boolean getIsDisplayed(By locator, int waitSec) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); boolean isDisplayed; try { WebElement element = this.driver.findElement(locator); isDisplayed = element.isDisplayed(); return isDisplayed; } catch (NoSuchElementException e) { isDisplayed = false; return isDisplayed; } finally { driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } } protected boolean getIsElementExist(By locator, int waitSec) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); boolean isElementExist = false; try { WebElement element = this.driver.findElement(locator); if (element != null) isElementExist = true; } catch (NoSuchElementException e) { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); isElementExist = false; } finally { driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return isElementExist; } } protected Integer getRandomInt(int lowerBound, int upperBound) { Random r = new Random(); int result; if (lowerBound != upperBound) { result = r.nextInt(upperBound - lowerBound) + lowerBound; } else { result = lowerBound; } System.err.println("upperBound = " + upperBound + "| result = " + result); return result; } protected Integer getElements_size(By locator, int waitSec, String errMsg) { driver.manage().timeouts().implicitlyWait(waitSec, TimeUnit.SECONDS); try { List<WebElement> elements = this.driver.findElements(locator); driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); return elements.size(); } catch (NoSuchElementException e) { System.err.print(errMsg + " | " + e.getMessage()); throw new WebDriverException(errMsg); } finally { driver.manage().timeouts().implicitlyWait(MainTest.DefaultDelay, TimeUnit.SECONDS); } } // Other functions protected static Integer StrToInt( final CharSequence input) { final StringBuilder sb = new StringBuilder( input.length()); for (int i = 0; i < input.length(); i++) { final char c = input.charAt(i); if (c > 47 && c < 58) { sb.append(c); } } String resultStr = sb.toString(); return Integer.parseInt(resultStr); } }
40.063973
128
0.633246
fa573ab838411d4611b8eb19137ccc8df247a6dc
2,753
package com.p6e.germ.security.config; import java.io.Serializable; import java.util.List; import java.util.Map; /** * 认证的模型对象 * 自定义的认证的模型对象需要继承 P6eAuthModel 对象 * @author lidashuang * @version 1.0 */ public class P6eAuthModel extends com.p6e.germ.starter.oauth2.P6eAuthModel implements Serializable { private Integer id; private Integer status; private String avatar; private String name; private String nickname; private String sex; private String birthday; private String role; private String token; private String refreshToken; private Long expirationTime; private List<Map<String, String>> groupList; private List<Map<String, String>> jurisdictionList; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public List<Map<String, String>> getGroupList() { return groupList; } public void setGroupList(List<Map<String, String>> groupList) { this.groupList = groupList; } public List<Map<String, String>> getJurisdictionList() { return jurisdictionList; } public void setJurisdictionList(List<Map<String, String>> jurisdictionList) { this.jurisdictionList = jurisdictionList; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public Long getExpirationTime() { return expirationTime; } public void setExpirationTime(Long expirationTime) { this.expirationTime = expirationTime; } }
20.856061
100
0.630585
1c42139873b6b1f2371e3539167c57380d30951d
4,962
package io.crnk.client; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.crnk.client.legacy.RelationshipRepositoryStub; import io.crnk.client.legacy.ResourceRepositoryStub; import io.crnk.core.exception.ResourceNotFoundException; import io.crnk.legacy.queryParams.QueryParams; import io.crnk.test.mock.models.Project; import io.crnk.test.mock.models.Schedule; import io.crnk.test.mock.models.Task; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class QueryParamsClientTest extends AbstractClientTest { protected ResourceRepositoryStub<Task, Long> taskRepo; protected ResourceRepositoryStub<Project, Long> projectRepo; protected RelationshipRepositoryStub<Task, Long, Project, Long> relRepo; private ResourceRepositoryStub<Schedule, Serializable> scheduleRepo; @Before public void setup() { super.setup(); scheduleRepo = client.getQueryParamsRepository(Schedule.class); taskRepo = client.getQueryParamsRepository(Task.class); projectRepo = client.getQueryParamsRepository(Project.class); relRepo = client.getQueryParamsRepository(Task.class, Project.class); } @Test public void testFindEmpty() { List<Task> tasks = taskRepo.findAll(new QueryParams()); Assert.assertTrue(tasks.isEmpty()); } @Test public void testAccessQuerySpecRepository() { List<Schedule> schedule = scheduleRepo.findAll(new QueryParams()); Assert.assertTrue(schedule.isEmpty()); } @Test(expected = ResourceNotFoundException.class) public void testFindNull() { taskRepo.findOne(1L, new QueryParams()); } @Test public void testSaveAndFind() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); // check retrievable with findAll List<Task> tasks = taskRepo.findAll(new QueryParams()); Assert.assertEquals(1, tasks.size()); Task savedTask = tasks.get(0); Assert.assertEquals(task.getId(), savedTask.getId()); Assert.assertEquals(task.getName(), savedTask.getName()); // check retrievable with findAll(ids) tasks = taskRepo.findAll(Arrays.asList(1L), new QueryParams()); Assert.assertEquals(1, tasks.size()); savedTask = tasks.get(0); Assert.assertEquals(task.getId(), savedTask.getId()); Assert.assertEquals(task.getName(), savedTask.getName()); // check retrievable with findOne savedTask = taskRepo.findOne(1L, new QueryParams()); Assert.assertEquals(task.getId(), savedTask.getId()); Assert.assertEquals(task.getName(), savedTask.getName()); } @Test public void testGeneratedId() { Task task = new Task(); task.setId(null); task.setName("test"); Task savedTask = taskRepo.create(task); Assert.assertNotNull(savedTask.getId()); } @Test public void testDelete() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); taskRepo.delete(1L); List<Task> tasks = taskRepo.findAll(new QueryParams()); Assert.assertEquals(0, tasks.size()); } @Test public void testSetRelation() { Project project = new Project(); project.setId(1L); project.setName("project"); projectRepo.create(project); Task task = new Task(); task.setId(2L); task.setName("test"); taskRepo.create(task); relRepo.setRelation(task, project.getId(), "project"); Project relProject = relRepo.findOneTarget(task.getId(), "project", new QueryParams()); Assert.assertNotNull(relProject); Assert.assertEquals(project.getId(), relProject.getId()); } @Test public void testAddSetRemoveRelations() { Project project0 = new Project(); project0.setId(1L); project0.setName("project0"); projectRepo.create(project0); Project project1 = new Project(); project1.setId(2L); project1.setName("project1"); projectRepo.create(project1); Task task = new Task(); task.setId(3L); task.setName("test"); taskRepo.create(task); relRepo.addRelations(task, Arrays.asList(project0.getId(), project1.getId()), "projects"); List<Project> relProjects = relRepo.findManyTargets(task.getId(), "projects", new QueryParams()); Assert.assertEquals(2, relProjects.size()); relRepo.setRelations(task, Arrays.asList(project1.getId()), "projects"); relProjects = relRepo.findManyTargets(task.getId(), "projects", new QueryParams()); Assert.assertEquals(1, relProjects.size()); Assert.assertEquals(project1.getId(), relProjects.get(0).getId()); // FIXME HTTP DELETE method with payload not supported? at least in // Jersey // relRepo.removeRelations(task, Arrays.asList(project1.getId()), // "projects"); // relProjects = relRepo.findManyTargets(task.getId(), "projects", new // QueryParams()); // Assert.assertEquals(0, relProjects.size()); } @Test public void testValidationException() { } private void addParams(Map<String, Set<String>> params, String key, String value) { params.put(key, new HashSet<String>(Arrays.asList(value))); } }
29.360947
99
0.735994
a15a02e46d2c5977ac37325b0a1975981241e1ac
8,838
/* * @#KnownServerCatalogInfo.java - 2015 * Copyright bitDubai.com., All rights reserved.  * You may not modify, use, reproduce or distribute this software. * BITDUBAI/CONFIDENTIAL */ package com.bitdubai.fermat_p2p_plugin.layer.ws.communications.cloud.server.developer.bitdubai.version_1.structure.entities; import java.sql.Timestamp; import java.util.Objects; /** * The Class <code>com.bitdubai.fermat_p2p_plugin.layer.ws.communications.cloud.server.developer.bitdubai.version_1.structure.entities.KnownServerCatalogInfo</code> * <p/> * Created by Roberto Requena - ([email protected]) on 22/10/15. * * @version 1.0 * @since Java JDK 1.7 */ public class KnownServerCatalogInfo { /** * Represent the identityPublicKey */ private String identityPublicKey; /** * Represent the name */ private String name; /** * Represent the ip */ private String ip; /** * Represent the defaultPort */ private Integer defaultPort; /** * Represent the webServicePort */ private Integer webServicePort; /** * Represent the latitude */ private Double latitude; /** * Represent the longitude */ private Double longitude; /** * Represent the lateNotificationCounter */ private Integer lateNotificationCounter; /** * Represent the offlineCounter */ private Integer offlineCounter; /** * Represent the registeredTimestamp */ private Timestamp registeredTimestamp; /** * Represent the lastConnectionTimestamp */ private Timestamp lastConnectionTimestamp; /** * Constructor */ public KnownServerCatalogInfo() { super(); } /** * Constructor whit parameters * * @param defaultPort * @param identityPublicKey * @param ip * @param lastConnectionTimestamp * @param lateNotificationCounter * @param latitude * @param longitude * @param name * @param offlineCounter * @param registeredTimestamp * @param webServicePort */ public KnownServerCatalogInfo(Integer defaultPort, String identityPublicKey, String ip, Timestamp lastConnectionTimestamp, Integer lateNotificationCounter, Double latitude, Double longitude, String name, Integer offlineCounter, Timestamp registeredTimestamp, Integer webServicePort) { this.defaultPort = defaultPort; this.identityPublicKey = identityPublicKey; this.ip = ip; this.lastConnectionTimestamp = lastConnectionTimestamp; this.lateNotificationCounter = lateNotificationCounter; this.latitude = latitude; this.longitude = longitude; this.name = name; this.offlineCounter = offlineCounter; this.registeredTimestamp = registeredTimestamp; this.webServicePort = webServicePort; } /** * Get the DefaultPort * @return Integer */ public Integer getDefaultPort() { return defaultPort; } /** * Set the DefaultPort * @param defaultPort */ public void setDefaultPort(Integer defaultPort) { this.defaultPort = defaultPort; } /** * Get the IdentityPublicFey * @return String */ public String getIdentityPublicKey() { return identityPublicKey; } /** * Set the IdentityPublicFey * @param identityPublicKey */ public void setIdentityPublicKey(String identityPublicKey) { this.identityPublicKey = identityPublicKey; } /** * Get the Ip * @return String */ public String getIp() { return ip; } /** * Set the Ip * @param ip */ public void setIp(String ip) { this.ip = ip; } /** * Get the LastConnectionTimestamp * @return String */ public Timestamp getLastConnectionTimestamp() { return lastConnectionTimestamp; } /** * Set the LastConnectionTimestamp * @param lastConnectionTimestamp */ public void setLastConnectionTimestamp(Timestamp lastConnectionTimestamp) { this.lastConnectionTimestamp = lastConnectionTimestamp; } /** * Get the LateNotificationCounter * @return Integer */ public Integer getLateNotificationCounter() { return lateNotificationCounter; } /** * Set the LateNotificationCounter * @param lateNotificationCounter */ public void setLateNotificationCounter(Integer lateNotificationCounter) { this.lateNotificationCounter = lateNotificationCounter; } /** * Get the Latitude * @return Double */ public Double getLatitude() { return latitude; } /** * Set the Latitude * @param latitude */ public void setLatitude(Double latitude) { this.latitude = latitude; } /** * Get the Longitude * @return Double */ public Double getLongitude() { return longitude; } /** * Set the Longitude * @param longitude */ public void setLongitude(Double longitude) { this.longitude = longitude; } /** * Get the Name * @return String */ public String getName() { return name; } /** * Set the Name * @param name */ public void setName(String name) { this.name = name; } /** * Get the OfflineCounter * @return Integer */ public Integer getOfflineCounter() { return offlineCounter; } /** * Set the OfflineCounter * @param offlineCounter */ public void setOfflineCounter(Integer offlineCounter) { this.offlineCounter = offlineCounter; } /** * Get the RegisteredTimestamp * @return Timestamp */ public Timestamp getRegisteredTimestamp() { return registeredTimestamp; } /** * Set th RegisteredTimestamp * @param registeredTimestamp */ public void setRegisteredTimestamp(Timestamp registeredTimestamp) { this.registeredTimestamp = registeredTimestamp; } /** * Get the WebServicePort * @return Integer */ public Integer getWebServicePort() { return webServicePort; } /** * Set the WebServicePort * @param webServicePort */ public void setWebServicePort(Integer webServicePort) { this.webServicePort = webServicePort; } /** * (non-javadoc) * @see Object#equals(Object) */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof KnownServerCatalogInfo)) return false; KnownServerCatalogInfo that = (KnownServerCatalogInfo) o; return Objects.equals(getIdentityPublicKey(), that.getIdentityPublicKey()) && Objects.equals(getName(), that.getName()) && Objects.equals(getIp(), that.getIp()) && Objects.equals(getDefaultPort(), that.getDefaultPort()) && Objects.equals(getWebServicePort(), that.getWebServicePort()) && Objects.equals(getLatitude(), that.getLatitude()) && Objects.equals(getLongitude(), that.getLongitude()) && Objects.equals(getLateNotificationCounter(), that.getLateNotificationCounter()) && Objects.equals(getOfflineCounter(), that.getOfflineCounter()) && Objects.equals(getRegisteredTimestamp(), that.getRegisteredTimestamp()) && Objects.equals(getLastConnectionTimestamp(), that.getLastConnectionTimestamp()); } /** * (non-javadoc) * @see Object#hashCode() */ @Override public int hashCode() { return Objects.hash(getIdentityPublicKey(), getName(), getIp(), getDefaultPort(), getWebServicePort(), getLatitude(), getLongitude(), getLateNotificationCounter(), getOfflineCounter(), getRegisteredTimestamp(), getLastConnectionTimestamp()); } /** * (non-javadoc) * @see Object#toString() */ @Override public String toString() { return "KnownServerCatalogInfo{" + "defaultPort=" + defaultPort + ", identityPublicKey='" + identityPublicKey + '\'' + ", name='" + name + '\'' + ", ip='" + ip + '\'' + ", webServicePort=" + webServicePort + ", latitude=" + latitude + ", longitude=" + longitude + ", lateNotificationCounter=" + lateNotificationCounter + ", offlineCounter=" + offlineCounter + ", registeredTimestamp='" + registeredTimestamp + '\'' + ", lastConnectionTimestamp='" + lastConnectionTimestamp + '\'' + '}'; } }
25.917889
288
0.6136
b687b2149d0d3ecefd3af09ced8a2464ed2760c7
18,651
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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 annis.gui.resultview; import annis.CommonHelper; import annis.gui.AnnisUI; import annis.gui.QueryController; import annis.gui.components.OnLoadCallbackExtension; import annis.gui.controlpanel.QueryPanel; import annis.gui.objects.DisplayedResultQuery; import annis.gui.objects.PagedResultQuery; import annis.gui.paging.PagingComponent; import annis.libgui.Helper; import annis.libgui.InstanceConfig; import annis.libgui.PluginSystem; import annis.libgui.ResolverProviderImpl; import annis.model.AnnisConstants; import annis.resolver.ResolverEntry; import annis.resolver.SingleResolverRequest; import annis.service.objects.CorpusConfig; import annis.service.objects.Match; import com.google.common.base.Preconditions; import com.vaadin.server.AbstractClientConnector; import com.vaadin.ui.Alignment; import com.vaadin.ui.CssLayout; import com.vaadin.ui.JavaScript; import com.vaadin.ui.Label; import com.vaadin.ui.MenuBar; import com.vaadin.ui.MenuBar.MenuItem; import com.vaadin.ui.Notification; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; import org.apache.commons.lang3.StringUtils; import org.corpus_tools.salt.common.SCorpusGraph; import org.corpus_tools.salt.common.SDocument; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.common.SaltProject; import org.corpus_tools.salt.core.SFeature; import org.corpus_tools.salt.core.SNode; import org.slf4j.LoggerFactory; /** * * @author thomas */ public class ResultViewPanel extends VerticalLayout implements OnLoadCallbackExtension.Callback { private static final org.slf4j.Logger log = LoggerFactory.getLogger( ResultViewPanel.class); public static final String NULL_SEGMENTATION_VALUE = "tokens (default)"; private final Map<HashSet<SingleResolverRequest>, List<ResolverEntry>> cacheResolver; public static final String FILESYSTEM_CACHE_RESULT = "ResultSetPanel_FILESYSTEM_CACHE_RESULT"; public static final String MAPPING_HIDDEN_ANNOS = "hidden_annos"; private final PagingComponent paging; private final PluginSystem ps; private final MenuItem miTokAnnos; private final MenuItem miSegmentation; private final TreeMap<String, Boolean> tokenAnnoVisible; private final QueryController controller; private final Set<String> segmentationLayerSet = Collections.synchronizedSet(new TreeSet<String>()); private final Set<String> tokenAnnotationLevelSet = Collections.synchronizedSet(new TreeSet<String>()); private final InstanceConfig instanceConfig; private final CssLayout resultLayout; private final List<SingleResultPanel> resultPanelList; private String segmentationName; private int currentResults; private int numberOfResults; private ArrayList<Match> allMatches; private transient BlockingQueue<SaltProject> projectQueue; private PagedResultQuery currentQuery; private final DisplayedResultQuery initialQuery; private final AnnisUI sui; public ResultViewPanel(AnnisUI ui, PluginSystem ps, InstanceConfig instanceConfig, DisplayedResultQuery initialQuery) { this.sui = ui; this.tokenAnnoVisible = new TreeMap<>(); this.ps = ps; this.controller = ui.getQueryController(); this.initialQuery = initialQuery; cacheResolver = Collections.synchronizedMap( new HashMap<HashSet<SingleResolverRequest>, List<ResolverEntry>>()); resultPanelList = Collections.synchronizedList(new LinkedList<SingleResultPanel>()); resultLayout = new CssLayout(); resultLayout.addStyleName("result-view-css"); Panel resultPanel = new Panel(resultLayout); resultPanel.setSizeFull(); resultPanel.addStyleName(ValoTheme.PANEL_BORDERLESS); resultPanel.addStyleName("result-view-panel"); this.instanceConfig = instanceConfig; setSizeFull(); setMargin(false); MenuBar mbResult = new MenuBar(); mbResult.setWidth("100%"); mbResult.addStyleName("menu-hover"); addComponent(mbResult); miSegmentation = mbResult.addItem("Base text", null); miTokAnnos = mbResult.addItem("Token Annotations", null); addComponent(resultPanel); setExpandRatio(mbResult, 0.0f); setExpandRatio(resultPanel, 1.0f); paging = new PagingComponent(); addComponent(paging, 1); setComponentAlignment(paging, Alignment.TOP_CENTER); setExpandRatio(paging, 0.0f); } /** * Informs the user about the searching process. * * @param query Represents a limited query */ public void showMatchSearchInProgress(PagedResultQuery query) { resultLayout.removeAllComponents(); segmentationName = query.getSegmentation(); } public void showNoResult() { resultLayout.removeAllComponents(); currentResults = 0; // nothing to show since we have an empty result Label lblNoResult = new Label("No matches found."); lblNoResult.setWidth("100%"); lblNoResult.addStyleName("result-view-no-content"); resultLayout.addComponent(lblNoResult); showFinishedSubgraphSearch(); } public void showSubgraphSearchInProgress(PagedResultQuery q, float percent) { if (percent == 0.0f) { resultLayout.removeAllComponents(); currentResults = 0; } } /** * Set a new querys in result panel. * * @param queue holds the salt graph * @param q holds the ordinary query * @param allMatches All matches. */ public void setQueryResultQueue(BlockingQueue<SaltProject> queue, PagedResultQuery q, ArrayList<Match> allMatches) { this.projectQueue = queue; this.currentQuery = q; this.numberOfResults = allMatches.size(); this.allMatches = allMatches; paging.setPageSize(q.getLimit(), false); paging.setInfo(q.getQuery()); resultLayout.removeAllComponents(); resultPanelList.clear(); // get the first query result SaltProject first = queue.poll(); Preconditions.checkState(first != null, "There must be already an element in the queue"); addQueryResult(q, Arrays.asList(first)); } private void resetQueryResultQueue() { this.projectQueue = null; this.currentQuery = null; this.currentResults = 0; this.numberOfResults = 0; } private void addQueryResult(PagedResultQuery q, List<SaltProject> subgraphList) { if (q == null) { return; } List<SingleResultPanel> newPanels = new LinkedList<>(); try { if (subgraphList == null || subgraphList.isEmpty()) { Notification.show("Could not get subgraphs", Notification.Type.TRAY_NOTIFICATION); } else { for (SaltProject p : subgraphList) { updateVariables(p); newPanels = createPanels(p, currentResults, q.getOffset() + currentResults); currentResults += newPanels.size(); String strResults = numberOfResults > 1 ? "results" : "result"; sui.getSearchView().getControlPanel().getQueryPanel().setStatus(sui.getSearchView().getControlPanel(). getQueryPanel().getLastPublicStatus(), " (showing " + currentResults + "/" + numberOfResults + " " + strResults + ")"); if (currentResults == numberOfResults) { resetQueryResultQueue(); } for (SingleResultPanel panel : newPanels) { resultPanelList.add(panel); resultLayout.addComponent(panel); panel.setSegmentationLayer(sui.getQueryState().getVisibleBaseText().getValue()); } } if (currentResults == numberOfResults) { showFinishedSubgraphSearch(); if(!initialQuery.getSelectedMatches().isEmpty()) { // scroll to the first selected match JavaScript.eval( "$(\".v-panel-content-result-view-panel\").animate({scrollTop: $(\".selected-match\").offset().top - $(\".result-view-panel\").offset().top}, 1000);"); } } if (projectQueue != null && !newPanels.isEmpty() && currentResults < numberOfResults) { log.debug("adding callback for result " + currentResults); // add a callback so we can load the next single result OnLoadCallbackExtension ext = new OnLoadCallbackExtension(this, 250); ext.extend(newPanels.get(newPanels.size() - 1)); } } } catch (Throwable ex) { log.error(null, ex); } } public void showFinishedSubgraphSearch() { //Search complete, stop progress bar control if (sui.getSearchView().getControlPanel().getQueryPanel().getPiCount() != null) { if (sui.getSearchView().getControlPanel().getQueryPanel().getPiCount().isVisible()) { sui.getSearchView().getControlPanel().getQueryPanel().getPiCount().setVisible(false); sui.getSearchView().getControlPanel().getQueryPanel().getPiCount().setEnabled(false); } } // also remove the info how many results have been fetched QueryPanel qp = sui.getSearchView().getControlPanel().getQueryPanel(); qp.setStatus(qp.getLastPublicStatus()); } private List<SingleResultPanel> createPanels(SaltProject p, int localMatchIndex, long globalOffset) { List<SingleResultPanel> result = new LinkedList<>(); int i = 0; for (SCorpusGraph corpusGraph : p.getCorpusGraphs()) { SDocument doc = corpusGraph.getDocuments().get(0); Match m = new Match(); if(allMatches != null && localMatchIndex >= 0 && localMatchIndex < allMatches.size()) { m = allMatches.get(localMatchIndex); } SingleResultPanel panel = new SingleResultPanel(doc, m, i + globalOffset, new ResolverProviderImpl(cacheResolver), ps, sui, getVisibleTokenAnnos(), segmentationName, controller, instanceConfig, initialQuery); i++; panel.setWidth("100%"); panel.setHeight("-1px"); result.add(panel); } return result; } private void updateVariables(SaltProject p) { segmentationLayerSet.addAll(getSegmentationNames(p)); tokenAnnotationLevelSet.addAll(CommonHelper.getTokenAnnotationLevelSet(p)); Set<String> hiddenTokenAnnos = null; Set<String> corpusNames = CommonHelper.getToplevelCorpusNames(p); for (String corpusName : corpusNames) { CorpusConfig corpusConfig = Helper.getCorpusConfig(corpusName); if (corpusConfig != null && corpusConfig.containsKey(MAPPING_HIDDEN_ANNOS)) { hiddenTokenAnnos = new HashSet<>( Arrays.asList( StringUtils.split( corpusConfig.getConfig(MAPPING_HIDDEN_ANNOS), ",") ) ); } } if (hiddenTokenAnnos != null) { for (String tokenLevel : hiddenTokenAnnos) { if (tokenAnnotationLevelSet.contains(tokenLevel)) { tokenAnnotationLevelSet.remove(tokenLevel); } } } updateSegmentationLayer(segmentationLayerSet); updateVisibleToken(tokenAnnotationLevelSet); } private Set<String> getSegmentationNames(SaltProject p) { Set<String> result = new TreeSet<>(); for (SCorpusGraph corpusGraphs : p.getCorpusGraphs()) { for (SDocument doc : corpusGraphs.getDocuments()) { SDocumentGraph g = doc.getDocumentGraph(); if (g != null) { // collect the start nodes of a segmentation chain of length 1 for (SNode n : g.getNodes()) { SFeature feat = n.getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_FIRST_NODE_SEGMENTATION_CHAIN); if (feat != null && feat.getValue_STEXT() != null) { result.add(feat.getValue_STEXT()); } } } // end if graph not null } } return result; } public void setCount(int count) { paging.setCount(count, false); paging.setStartNumber(initialQuery.getOffset()); } public SortedSet<String> getVisibleTokenAnnos() { TreeSet<String> result = new TreeSet<>(); for (Entry<String, Boolean> e : tokenAnnoVisible.entrySet()) { if (e.getValue().booleanValue() == true) { result.add(e.getKey()); } } return result; } /** * Listens to events on the base text menu and updates the segmentation layer. */ private class MenuBaseTextCommand implements MenuBar.Command { @Override public void menuSelected(MenuItem selectedItem) { // remember old value String oldSegmentationLayer = sui.getQueryState().getVisibleBaseText().getValue(); // set the new selected item String newSegmentationLayer = selectedItem.getText(); if (NULL_SEGMENTATION_VALUE.equals(newSegmentationLayer)) { newSegmentationLayer = null; } for (MenuItem mi : miSegmentation.getChildren()) { mi.setChecked(mi == selectedItem); } if (oldSegmentationLayer != null) { if (!oldSegmentationLayer.equals(newSegmentationLayer)) { setSegmentationLayer(newSegmentationLayer); } } else if (newSegmentationLayer != null) { // oldSegmentation is null, but selected is not setSegmentationLayer(newSegmentationLayer); } //update URL with newly selected segmentation layer sui.getQueryState().getVisibleBaseText().setValue(newSegmentationLayer); sui.getSearchView().updateFragment(sui.getQueryController().getSearchQuery()); } } private void updateSegmentationLayer(Set<String> segLayers) { // clear the menu base text miSegmentation.removeChildren(); // add the default token layer segLayers.add(""); // iterate of all segmentation layers and add them to the menu for (String s : segLayers) { // the new menu entry MenuItem miSingleSegLayer; /** * TODO maybe it would be better, to mark the default text level * corresponding to the corpus.properties. * * There exists always a default text level. */ if (s == null || "".equals(s)) { miSingleSegLayer = miSegmentation.addItem( NULL_SEGMENTATION_VALUE, new MenuBaseTextCommand()); } else { miSingleSegLayer = miSegmentation.addItem(s, new MenuBaseTextCommand()); } // mark as selectable miSingleSegLayer.setCheckable(true); /** * Check if a segmentation item must set checked. If no segmentation layer * is selected, set the default layer as selected. */ final String selectedSegmentationLayer = sui.getQueryState().getVisibleBaseText().getValue(); if ((selectedSegmentationLayer == null && "".equals(s)) || s.equals(selectedSegmentationLayer)) { miSingleSegLayer.setChecked(true); } else { miSingleSegLayer.setChecked(false); } } // end iterate for segmentation layer } public void updateVisibleToken(Set<String> tokenAnnotationLevelSet) { // if no token annotations are there, do not show this mneu if (tokenAnnotationLevelSet == null || tokenAnnotationLevelSet.isEmpty()) { miTokAnnos.setVisible(false); } else { miTokAnnos.setVisible(true); } // add new annotations if (tokenAnnotationLevelSet != null) { for (String s : tokenAnnotationLevelSet) { if (!tokenAnnoVisible.containsKey(s)) { tokenAnnoVisible.put(s, Boolean.TRUE); } } } miTokAnnos.removeChildren(); if (tokenAnnotationLevelSet != null) { for (final String a : tokenAnnotationLevelSet) { MenuItem miSingleTokAnno = miTokAnnos.addItem(a.replaceFirst("::", ":"), new MenuBar.Command() { @Override public void menuSelected(MenuItem selectedItem) { if (selectedItem.isChecked()) { tokenAnnoVisible.put(a, Boolean.TRUE); } else { tokenAnnoVisible.put(a, Boolean.FALSE); } setVisibleTokenAnnosVisible(getVisibleTokenAnnos()); } }); miSingleTokAnno.setCheckable(true); miSingleTokAnno.setChecked(tokenAnnoVisible.get(a).booleanValue()); } } } @Override public boolean onCompononentLoaded(AbstractClientConnector source) { if (source != null) { if (projectQueue != null && currentQuery != null) { LinkedList<SaltProject> subgraphs = new LinkedList<>(); SaltProject p; while ((p = projectQueue.poll()) != null) { log.debug("Polling queue for SaltProject graph"); subgraphs.add(p); } if (subgraphs.isEmpty()) { log.debug("no SaltProject graph in queue"); return false; } log.debug("taken {} SaltProject graph(s) from queue", subgraphs.size()); addQueryResult(currentQuery, subgraphs); return true; } } return true; } private void setVisibleTokenAnnosVisible(SortedSet<String> annos) { for (SingleResultPanel p : resultPanelList) { p.setVisibleTokenAnnosVisible(annos); } } private void setSegmentationLayer(String segmentationLayer) { for (SingleResultPanel p : resultPanelList) { p.setSegmentationLayer(segmentationLayer); } } public PagingComponent getPaging() { return paging; } }
28.518349
165
0.668597
dce02e293203dd8c2d9a04cc329dacccca2f2f63
15,629
/* * Copyright (c) 2015. Qubole 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 io.dblint.dbsecurity.sqlplanner.planner; import io.dblint.dbsecurity.sqlplanner.QanException; import java.sql.Types; import java.util.Arrays; public class Tpcds extends MartSchema { public Tpcds(String name) { super(name); } public void addTables() throws QanException { MartTable customer_demographics = new MartTable(this, "CUSTOMER_DEMOGRAPHICS", Arrays.asList(new MartColumn("cd_demo_sk", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("cd_marital_status", Types.VARCHAR), new MartColumn("cd_education_status", Types.VARCHAR), new MartColumn("cd_purchase_estimate", Types.INTEGER), new MartColumn("cd_credit_rating", Types.VARCHAR), new MartColumn("cd_dep_count", Types.INTEGER), new MartColumn("cd_dep_employed_count", Types.INTEGER), new MartColumn("cd_dep_college_count", Types.INTEGER) )); this.addTable(customer_demographics); MartTable date_dim = new MartTable(this, "DATE_DIM", Arrays.asList( new MartColumn("d_date_sk", Types.INTEGER), new MartColumn("d_date_id", Types.VARCHAR), new MartColumn("d_date", Types.DATE), new MartColumn("d_month_seq", Types.INTEGER), new MartColumn("d_week_seq", Types.INTEGER), new MartColumn("d_quarter_seq", Types.INTEGER), new MartColumn("d_year", Types.INTEGER), new MartColumn("d_dow", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_dom", Types.INTEGER), new MartColumn("d_qoy", Types.INTEGER), new MartColumn("d_fy_year", Types.INTEGER), new MartColumn("d_fy_quarter_seq", Types.INTEGER), new MartColumn("d_fy_week_seq", Types.INTEGER), new MartColumn("d_day_name", Types.VARCHAR), new MartColumn("d_quarter_name", Types.VARCHAR), new MartColumn("d_holiday", Types.VARCHAR), new MartColumn("d_weekend", Types.VARCHAR), new MartColumn("d_following_holiday", Types.VARCHAR), new MartColumn("d_first_dom", Types.INTEGER), new MartColumn("d_last_dom", Types.INTEGER), new MartColumn("d_same_day_ly", Types.INTEGER), new MartColumn("d_same_day_lq", Types.INTEGER), new MartColumn("d_current_day", Types.VARCHAR), new MartColumn("d_current_week", Types.VARCHAR), new MartColumn("d_current_month", Types.VARCHAR), new MartColumn("d_current_quarter", Types.VARCHAR), new MartColumn("d_current_year", Types.VARCHAR) )); this.addTable(date_dim); MartTable time_dim = new MartTable(this, "TIME_DIM", Arrays.asList( new MartColumn("t_time_sk", Types.INTEGER), new MartColumn("t_time_id", Types.VARCHAR), new MartColumn("t_time", Types.INTEGER), new MartColumn("t_hour", Types.INTEGER), new MartColumn("t_minute", Types.INTEGER), new MartColumn("t_second", Types.INTEGER), new MartColumn("t_am_pm", Types.VARCHAR), new MartColumn("t_shift", Types.VARCHAR), new MartColumn("t_sub_shift", Types.VARCHAR), new MartColumn("t_meal_time", Types.VARCHAR) )); this.addTable(time_dim); MartTable item = new MartTable(this, "ITEM", Arrays.asList( new MartColumn("i_item_sk", Types.INTEGER), new MartColumn("i_item_id", Types.VARCHAR), new MartColumn("i_rec_start_date", Types.DATE), new MartColumn("i_rec_end_date", Types.DATE), new MartColumn("i_item_desc", Types.VARCHAR), new MartColumn("i_current_price", Types.DOUBLE), new MartColumn("i_wholesale_cost", Types.DOUBLE), new MartColumn("i_brand_id", Types.INTEGER), new MartColumn("i_brand", Types.VARCHAR), new MartColumn("i_class_id", Types.INTEGER), new MartColumn("i_class", Types.VARCHAR), new MartColumn("i_category_id", Types.INTEGER), new MartColumn("i_category", Types.VARCHAR), new MartColumn("i_manufact_id", Types.INTEGER), new MartColumn("i_manufact", Types.VARCHAR), new MartColumn("i_size", Types.VARCHAR), new MartColumn("i_formulation", Types.VARCHAR), new MartColumn("i_color", Types.VARCHAR), new MartColumn("i_units", Types.VARCHAR), new MartColumn("i_container", Types.VARCHAR), new MartColumn("i_manager_id", Types.INTEGER), new MartColumn("i_product_name", Types.VARCHAR) ), 100.0, "i_item_id"); this.addTable(item); MartTable customer = new MartTable(this, "CUSTOMER", Arrays.asList( new MartColumn("c_customer_sk", Types.INTEGER), new MartColumn("c_customer_id", Types.VARCHAR), new MartColumn("c_current_cdemo_sk", Types.INTEGER), new MartColumn("c_current_hdemo_sk", Types.INTEGER), new MartColumn("c_current_addr_sk", Types.INTEGER), new MartColumn("c_first_shipto_date_sk", Types.INTEGER), new MartColumn("c_first_sales_date_sk", Types.INTEGER), new MartColumn("c_salutation", Types.VARCHAR), new MartColumn("c_first_name", Types.VARCHAR), new MartColumn("c_last_name", Types.VARCHAR), new MartColumn("c_preferred_cust_flag", Types.VARCHAR), new MartColumn("c_birth_day", Types.INTEGER), new MartColumn("c_birth_month", Types.INTEGER), new MartColumn("c_birth_year", Types.INTEGER), new MartColumn("c_birth_country", Types.VARCHAR), new MartColumn("c_login", Types.VARCHAR), new MartColumn("c_email_address", Types.VARCHAR), new MartColumn("c_last_review_date", Types.VARCHAR) )); this.addTable(customer); MartTable web_returns = new MartTable(this, "WEB_RETURNS", Arrays.asList( new MartColumn("wr_returned_date_sk", Types.INTEGER), new MartColumn("wr_returned_time_sk", Types.INTEGER), new MartColumn("wr_item_sk", Types.INTEGER), new MartColumn("wr_refunded_customer_sk", Types.INTEGER), new MartColumn("wr_refunded_cdemo_sk", Types.INTEGER), new MartColumn("wr_refunded_hdemo_sk", Types.INTEGER), new MartColumn("wr_refunded_addr_sk", Types.INTEGER), new MartColumn("wr_returning_customer_sk", Types.INTEGER), new MartColumn("wr_returning_cdemo_sk", Types.INTEGER), new MartColumn("wr_returning_hdemo_sk", Types.INTEGER), new MartColumn("wr_returning_addr_sk", Types.INTEGER), new MartColumn("wr_web_page_sk", Types.INTEGER), new MartColumn("wr_reason_sk", Types.INTEGER), new MartColumn("wr_order_number", Types.INTEGER), new MartColumn("wr_return_quantity", Types.INTEGER), new MartColumn("wr_return_amt", Types.DOUBLE), new MartColumn("wr_return_tax", Types.DOUBLE), new MartColumn("wr_return_amt_inc_tax", Types.DOUBLE), new MartColumn("wr_fee", Types.DOUBLE), new MartColumn("wr_return_ship_cost", Types.DOUBLE), new MartColumn("wr_refunded_cash", Types.DOUBLE), new MartColumn("wr_reversed_charge", Types.DOUBLE), new MartColumn("wr_account_credit", Types.DOUBLE), new MartColumn("wr_net_loss", Types.DOUBLE) )); this.addTable(web_returns); MartTable web_returns_cube = new MartTable(this, "WEB_RETURNS_CUBE", Arrays.asList( new MartColumn("i_item_id", Types.VARCHAR), new MartColumn("d_year", Types.INTEGER), new MartColumn("d_qoy", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_date", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("cd_marital_status", Types.VARCHAR), new MartColumn("cd_education_status", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("total_net_loss", Types.DOUBLE) )); this.addTable(web_returns_cube); MartTable store_sales = new MartTable(this, "STORE_SALES", Arrays.asList( new MartColumn("ss_sold_date_sk", Types.INTEGER), new MartColumn("ss_sold_time_sk", Types.INTEGER), new MartColumn("ss_item_sk", Types.INTEGER), new MartColumn("ss_customer_sk", Types.INTEGER), new MartColumn("ss_cdemo_sk", Types.INTEGER), new MartColumn("ss_hdemo_sk", Types.INTEGER), new MartColumn("ss_addr_sk", Types.INTEGER), new MartColumn("ss_store_sk", Types.INTEGER), new MartColumn("ss_promo_sk", Types.INTEGER), new MartColumn("ss_ticket_number", Types.INTEGER), new MartColumn("ss_quantity", Types.INTEGER), new MartColumn("ss_wholesale_cost", Types.DOUBLE), new MartColumn("ss_list_price", Types.DOUBLE), new MartColumn("ss_sales_price", Types.DOUBLE), new MartColumn("ss_ext_discount_amt", Types.DOUBLE), new MartColumn("ss_ext_sales_price", Types.DOUBLE), new MartColumn("ss_ext_wholesale_cost", Types.DOUBLE), new MartColumn("ss_ext_list_price", Types.DOUBLE), new MartColumn("ss_ext_tax", Types.DOUBLE), new MartColumn("ss_coupon_amt", Types.DOUBLE), new MartColumn("ss_net_paid", Types.DOUBLE), new MartColumn("ss_net_paid_inc_tax", Types.DOUBLE), new MartColumn("ss_net_profit", Types.DOUBLE) )); this.addTable(store_sales); MartTable web_site = new MartTable(this, "WEB_SITE", Arrays.asList( new MartColumn("web_site_sk", Types.INTEGER), new MartColumn("web_site_id", Types.CHAR), new MartColumn("web_rec_start_date", Types.DATE), new MartColumn("web_rec_end_data", Types.DATE), new MartColumn("web_name", Types.VARCHAR), new MartColumn("web_open_date_sk", Types.INTEGER), new MartColumn("web_close_date_sk", Types.INTEGER), new MartColumn("web_class", Types.VARCHAR), new MartColumn("web_manager", Types.VARCHAR), new MartColumn("web_mkt_id", Types.INTEGER), new MartColumn("web_mkt_class", Types.VARCHAR), new MartColumn("web_mkt_desc", Types.VARCHAR), new MartColumn("web_market_manager", Types.VARCHAR), new MartColumn("web_company_id", Types.INTEGER), new MartColumn("web_company_name", Types.CHAR), new MartColumn("web_street_number", Types.CHAR), new MartColumn("web_street_name", Types.VARCHAR), new MartColumn("web_street_type", Types.CHAR), new MartColumn("web_suite_number", Types.CHAR), new MartColumn("web_city", Types.VARCHAR), new MartColumn("web_county", Types.VARCHAR), new MartColumn("web_state", Types.CHAR), new MartColumn("web_zip", Types.CHAR), new MartColumn("web_country", Types.VARCHAR), new MartColumn("web_gmt_offset", Types.DECIMAL), new MartColumn("web_tax_percentage", Types.DECIMAL) )); this.addTable(web_site); MartTable store_sales_cube = new MartTable(this, "STORE_SALES_CUBE", Arrays.asList( new MartColumn("i_item_id", Types.VARCHAR), new MartColumn("c_customer_id", Types.VARCHAR), new MartColumn("d_year", Types.INTEGER), new MartColumn("d_qoy", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_date", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("cd_marital_status", Types.VARCHAR), new MartColumn("cd_education_status", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("sum_sales_price", Types.DOUBLE), new MartColumn("sum_extended_sales_price", Types.DOUBLE) )); this.addTable(store_sales_cube); MartTable store_sales_cube_partial = new MartTable(this, "STORE_SALES_CUBE_PARTIAL", Arrays.asList( new MartColumn("i_item_id", Types.VARCHAR), new MartColumn("c_customer_id", Types.VARCHAR), new MartColumn("d_year", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_dom", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("cd_marital_status", Types.VARCHAR), new MartColumn("cd_education_status", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("sum_sales_price", Types.DOUBLE), new MartColumn("sum_extended_sales_price", Types.DOUBLE) )); this.addTable(store_sales_cube_partial); MartTable store_sales_cube_daily = new MartTable(this, "STORE_SALES_CUBE_DAILY", Arrays.asList( new MartColumn("d_year", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_dom", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("sum_sales_price", Types.DOUBLE), new MartColumn("sum_extended_sales_price", Types.DOUBLE) )); this.addTable(store_sales_cube_daily); MartTable store_sales_cube_weekly = new MartTable(this, "STORE_SALES_CUBE_WEEKLY", Arrays.asList( new MartColumn("d_year", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("d_week_seq", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("sum_sales_price", Types.DOUBLE), new MartColumn("sum_extended_sales_price", Types.DOUBLE) )); this.addTable(store_sales_cube_weekly); MartTable store_sales_cube_monthly = new MartTable(this, "STORE_SALES_CUBE_MONTHLY", Arrays.asList( new MartColumn("d_year", Types.INTEGER), new MartColumn("d_moy", Types.INTEGER), new MartColumn("cd_gender", Types.VARCHAR), new MartColumn("grouping_id", Types.VARCHAR), new MartColumn("sum_sales_price", Types.DOUBLE), new MartColumn("sum_extended_sales_price", Types.DOUBLE) )); this.addTable(store_sales_cube_monthly); MartTable web_site_partition = new MartTable(this, "WEB_SITE_PARTITION", Arrays.asList( new MartColumn("web_site_sk", Types.INTEGER), new MartColumn("web_rec_start_date", Types.DATE), new MartColumn("web_county", Types.VARCHAR), new MartColumn("web_tax_percentage", Types.DECIMAL) )); this.addTable(web_site_partition); } }
46.933934
88
0.652185
85283826f65ee1127211022a658d496e835f1dc5
6,436
package com.fr.swift.cloud.api.info; import com.fr.swift.cloud.api.info.api.CreateTableRequestInfo; import com.fr.swift.cloud.api.info.api.InsertRequestInfo; import com.fr.swift.cloud.api.info.api.TableRequestInfo; import com.fr.swift.cloud.api.info.api.TruncateRequestInfo; import com.fr.swift.cloud.api.rpc.bean.Column; import com.fr.swift.cloud.base.json.JsonBuilder; import com.fr.swift.cloud.db.SwiftDatabase; import com.fr.swift.cloud.source.ListBasedRow; import com.fr.swift.cloud.source.Row; import org.junit.Assert; import org.junit.Test; import java.sql.Types; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; //import com.fr.swift.query.info.bean.element.DimensionBean; //import com.fr.swift.query.info.bean.element.filter.FilterInfoBean; //import com.fr.swift.query.info.bean.element.filter.impl.AllShowFilterBean; //import com.fr.swift.query.info.bean.query.DetailQueryInfoBean; //import com.fr.swift.query.info.bean.query.QueryBeanFactory; //import com.fr.swift.query.info.bean.query.QueryInfoBean; //import com.fr.swift.query.info.bean.type.DimensionType; /** * @author yee * @date 2019-01-03 */ public class RequestInfoTest { @Test public void createTableRequestInfoTest() throws Exception { CreateTableRequestInfo info = new CreateTableRequestInfo(); info.setTable("table"); info.setColumns(Arrays.asList(new Column("id", Types.BIGINT), new Column("name", Types.VARCHAR))); info.setAuthCode("authCode"); info.setDatabase(SwiftDatabase.CUBE); String json = JsonBuilder.writeJsonString(info); CreateTableRequestInfo newInfo = JsonBuilder.readValue(json, CreateTableRequestInfo.class); assertEquals(info.getTable(), newInfo.getTable()); assertEquals(info.getDatabase(), newInfo.getDatabase()); assertEquals(info.getAuthCode(), newInfo.getAuthCode()); List<Column> expect = info.getColumns(); List<Column> real = newInfo.getColumns(); assertEquals(expect.size(), real.size()); for (int i = 0; i < expect.size(); i++) { assertEquals(expect.get(i), real.get(i)); } } @Test public void deleteRequestInfoTest() throws Exception { // FilterBean filterBean = new AllShowFilterBean(); // DeleteRequestInfo info = new DeleteRequestInfo(); // info.setTable("table"); // info.setWhere(JsonBuilder.writeJsonString(filterBean)); // info.setAuthCode("authCode"); // info.setDatabase(SwiftSchema.CUBE); // String json = JsonBuilder.writeJsonString(info); // DeleteRequestInfo newInfo = JsonBuilder.readValue(json, DeleteRequestInfo.class); // assertEquals(info.getTable(), newInfo.getTable()); // assertEquals(info.getDatabase(), newInfo.getDatabase()); // assertEquals(info.getAuthCode(), newInfo.getAuthCode()); // String real = newInfo.getWhere(); // assertTrue(JsonBuilder.readValue(real, FilterInfoBean.class) instanceof AllShowFilterBean); } @Test public void insertRequestInfoTest() throws Exception { InsertRequestInfo info = new InsertRequestInfo(); info.setTable("table"); info.setSelectFields(Arrays.asList("id", "name")); info.setData(Arrays.<Row>asList(new ListBasedRow(1L, "anchor"), new ListBasedRow(2L, "mike"))); info.setAuthCode("authCode"); info.setDatabase(SwiftDatabase.CUBE); String json = JsonBuilder.writeJsonString(info); InsertRequestInfo newInfo = JsonBuilder.readValue(json, InsertRequestInfo.class); assertEquals(info.getTable(), newInfo.getTable()); assertEquals(info.getDatabase(), newInfo.getDatabase()); assertEquals(info.getAuthCode(), newInfo.getAuthCode()); List<Row> expect = info.getData(); List<Row> real = newInfo.getData(); assertEquals(expect.size(), real.size()); for (int i = 0; i < expect.size(); i++) { Row expectRow = expect.get(i); Row realRow = real.get(i); assertEquals(expectRow, realRow); } List<String> expectSelect = info.getSelectFields(); List<String> realSelect = newInfo.getSelectFields(); assertEquals(expectSelect.size(), realSelect.size()); for (int i = 0; i < expectSelect.size(); i++) { assertEquals(expectSelect.get(i), realSelect.get(i)); } } @Test public void queryRequestInfoTest() throws Exception { // QueryRequestInfo info = new QueryRequestInfo(); // DetailQueryInfoBean queryBean = new DetailQueryInfoBean(); // queryBean.setTableName("table"); // DimensionBean bean = new DimensionBean(); // bean.setType(DimensionType.DETAIL_ALL_COLUMN); // queryBean.setDimensions(Arrays.asList(bean)); // info.setAuthCode("authCode"); // info.setDatabase(SwiftSchema.CUBE); // info.setQueryJson(QueryBeanFactory.queryBean2String(queryBean)); // // String json = JsonBuilder.writeJsonString(info); // QueryRequestInfo newInfo = JsonBuilder.readValue(json, QueryRequestInfo.class); // assertEquals(info.getDatabase(), newInfo.getDatabase()); // assertEquals(info.getAuthCode(), newInfo.getAuthCode()); // String real = newInfo.getQueryJson(); // QueryInfoBean queryInfoBean = QueryBeanFactory.create(real); // assertTrue(queryInfoBean instanceof DetailQueryInfoBean); // List<DimensionBean> dimensionBeans = ((DetailQueryInfoBean) queryInfoBean).getDimensions(); // assertEquals(1, dimensionBeans.size()); // DimensionType type = dimensionBeans.get(0).getType(); // Assert.assertEquals(DimensionType.DETAIL_ALL_COLUMN, type); } @Test public void tableRequestInfoTest() throws Exception { TableRequestInfo info = new TruncateRequestInfo(); info.setTable("table"); info.setAuthCode("authCode"); info.setDatabase(SwiftDatabase.CUBE); String json = JsonBuilder.writeJsonString(info); TableRequestInfo newInfo = JsonBuilder.readValue(json, TableRequestInfo.class); assertEquals(info.getTable(), newInfo.getTable()); assertEquals(info.getDatabase(), newInfo.getDatabase()); assertEquals(info.getAuthCode(), newInfo.getAuthCode()); Assert.assertEquals(RequestType.TRUNCATE_TABLE, newInfo.getRequestType()); } }
45.971429
106
0.689403
0a0c9c362d550cd7c4f34dcaf7cecba7000012a6
872
public class Snaiper extends Adventurer{ final int SNIPER_BONUS = 500; //레벨업 final float SNIPER_MAJOR_COEF = 3.1f; //계수로 사용 final float SNIPER_MINOR_COEF = 1.5f; public Snaiper(){ super(); sniperPromotionBonus(); } public void sniperPromotionBonus(){ //레벨업 스탯 계수 pAtk += (SNIPER_BONUS * SNIPER_MAJOR_COEF); str += (MINOR * SNIPER_MINOR_COEF); con += (MINOR * SNIPER_MINOR_COEF); dex += (MAJOR * SNIPER_MAJOR_COEF); agi += (MAJOR * SNIPER_MAJOR_COEF); iq += MINOR; men += MINOR; } public int calcBurstShotDamage (Object target ) { //펜릴 자체를 오브젝트로 만들자자 return (int) (5 * (pAtk - target.pDef) * ( (dex - target.con) * 1.5 + (agi - target.con) * 1.2) ); } //스킬은 하나만 @Override public void qSkill() { } }
22.358974
77
0.556193
fe0300ba79c1296a1fd9c7e379f0563d5cf0688a
1,397
package com.unq.dapp0.c1.comprandoencasa.webservices.dtos; import com.unq.dapp0.c1.comprandoencasa.model.objects.Location; import com.unq.dapp0.c1.comprandoencasa.model.objects.ShoppingList; import com.unq.dapp0.c1.comprandoencasa.model.objects.ShoppingListEntry; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class ShoppingListActiveDTO { public Long id; public Location location; public List<ShoppingListEntryDTO> entries; public BigDecimal total; public BigDecimal totalThreshold; public List<ThresholdDTO> thresholdsByType; public ShoppingListActiveDTO(){} public ShoppingListActiveDTO(ShoppingList shoppingList, BigDecimal totalThreshold, List<ThresholdDTO> thresholdDTOList) { this.id = shoppingList.getId(); this.location = shoppingList.getDeliveryLocation(); this.entries = parseEntries(shoppingList.getEntriesList()); this.total = shoppingList.totalValue(); this.totalThreshold = totalThreshold; this.thresholdsByType = thresholdDTOList; } private List<ShoppingListEntryDTO> parseEntries(List<ShoppingListEntry> entriesList) { List<ShoppingListEntryDTO> returnList = new ArrayList<>(); for (ShoppingListEntry entry : entriesList){ returnList.add(new ShoppingListEntryDTO(entry)); } return returnList; } }
36.763158
125
0.747316
7b789ba3fbec64e9cf5048560a9c4524cf47204d
5,380
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.ui.layout; import com.lightcrafts.ui.toolkit.FadingContainer; import com.lightcrafts.ui.LightZoneSkin; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.*; import java.util.List; /** * Combines a FadingContainer with some toggle buttons that control the * transitions among components. * <p> * FadingTabbedPanelListeners can find out about two particular transitions: * from something selected to nothing selected; and from nothing to something. */ public class FadingTabbedPanel extends JPanel { // The tab button labels can read upwards or downwards public enum Orientation { Up, Down } // When the first tab is opened or the last tab is closed, this is the // opposite transition color. private final static Color FadeAwayColor = LightZoneSkin.Colors.FrameBackground; // Respond to toggle button state changes by swapping components in the // FadingContainer, deselecting other toggle buttons, and making listener // callbacks. class TabListener implements ItemListener { private FadingContainer fader; boolean isDeselecting; public void itemStateChanged(ItemEvent event) { JToggleButton button = (JToggleButton) event.getSource(); String name = button.getName(); if (event.getStateChange() == ItemEvent.SELECTED) { JComponent comp = confs.get(name).comp; if (fader == null) { fader = new FadingContainer(FadeAwayColor); add(fader); panelListener.somethingSelected(); validate(); } fader.nextComponent(comp, null); if (selected != null) { isDeselecting = true; selected.setSelected(false); isDeselecting = false; } selected = button; panelListener.tabSelected(name); } else { if (! isDeselecting) { fader.nextComponent( FadeAwayColor, new ActionListener() { public void actionPerformed(ActionEvent event) { panelListener.nothingSelected(); remove(fader); fader = null; } } ); selected = null; } } } } private Map<String, FadingTabConfiguration> confs; private Collection<JToggleButton> buttons; private JToggleButton selected; private FadingTabbedPanelListener panelListener; private Box buttonBox; public FadingTabbedPanel( FadingTabConfiguration conf, Orientation orient, FadingTabbedPanelListener panelListener ) { this(Collections.singletonList(conf), orient, panelListener); } public JComponent getButtonContainer() { return buttonBox; } public String getSelected() { return (selected != null) ? selected.getName() : null; } public void setSelected(String name) { for (JToggleButton button : buttons) { if (button.getName().equals(name)) { button.setSelected(true); } } } public FadingTabbedPanel( List<FadingTabConfiguration> confs, Orientation orient, FadingTabbedPanelListener panelListener ) { this.panelListener = panelListener; buttons = new LinkedList<JToggleButton>(); buttonBox = Box.createVerticalBox(); // buttonBox.add(Box.createVerticalGlue()); // buttonBox.add(Box.createVerticalStrut(8)); TabListener tabListener = new TabListener(); this.confs = new HashMap<String, FadingTabConfiguration>(); for (FadingTabConfiguration conf : confs) { this.confs.put(conf.name, conf); JToggleButton button = new VerticalToggleButton(conf.name, orient); button.setToolTipText(conf.tip); button.setAlignmentY(.5f); button.setName(conf.name); button.addItemListener(tabListener); buttons.add(button); buttonBox.add(button); } buttonBox.add(Box.createVerticalGlue()); setLayout(new BorderLayout()); } // public Dimension getMinimumSize() { // Dimension min = new Dimension(); // for (JComponent comp : comps.values()) { // Dimension size = comp.getMinimumSize(); // min.width = Math.max(min.width, size.width); // min.height = Math.max(min.height, size.height); // } // return min; // } // // public Dimension getMaximumSize() { // Dimension max = new Dimension(); // for (JComponent comp : comps.values()) { // Dimension size = comp.getMinimumSize(); // max.width = Math.min(max.width, size.width); // max.height = Math.min(max.height, size.height); // } // return max; // } }
33.416149
84
0.586617
fad6eb82ab0607e1f7946dcdd7c0813ca3f44566
1,794
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.userguide.collections; import javax.persistence.Entity; import javax.persistence.Id; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.junit.Test; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; /** * @author Vlad Mihalcea */ public class ArrayTest extends BaseEntityManagerFunctionalTestCase { @Override protected Class<?>[] getAnnotatedClasses() { return new Class<?>[] { Person.class }; } @Test public void testLifecycle() { doInJPA( this::entityManagerFactory, entityManager -> { Person person = new Person( 1L ); String[] phones = new String[2]; phones[0] = "028-234-9876"; phones[1] = "072-122-9876"; person.setPhones( phones ); entityManager.persist( person ); } ); doInJPA( this::entityManagerFactory, entityManager -> { Person person = entityManager.find( Person.class, 1L ); String[] phones = new String[1]; phones[0] = "072-122-9876"; person.setPhones( phones ); } ); } //tag::collections-array-binary-example[] @Entity(name = "Person") public static class Person { @Id private Long id; private String[] phones; //Getters and setters are omitted for brevity //end::collections-array-binary-example[] public Person() { } public Person(Long id) { this.id = id; } public String[] getPhones() { return phones; } public void setPhones(String[] phones) { this.phones = phones; } //tag::collections-array-binary-example[] } //end::collections-array-binary-example[] }
22.708861
94
0.695652
0594a57831d24536575009bd3d402c63595cf4cd
1,243
package com.heaven7.android.util_v1_app; import android.graphics.Color; import android.os.Bundle; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.heaven7.core.util.HighLightTextHelper; import com.heaven7.core.util.MainWorker; public class TestActivity extends AppCompatActivity { TextView mTv; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ac_test_entry); mTv = findViewById(R.id.tv); MainWorker.postDelay(1000, new Runnable() { @Override public void run() { testHighLightText(); // startActivity(new Intent(TestActivity.this, MainActivity.class)); } }); } private void testHighLightText() { CharSequence text = new HighLightTextHelper.Builder() .setDefaultColor(Color.BLACK) .setHighLightColor(Color.RED) .setRawText("ba0aa1aaa2aaa3") .setHighLightText("a*") .setUseRegular(true) .build().getText(); mTv.setText(text); } }
28.906977
83
0.6428
3cead8c0ede8e70576a007865e52913ad097fbe2
142
package cn.huangxulin.cloud; /** * 功能描述: 自定义注解排除 SpringBoot 自动装配的类 * * @author hxulin */ public @interface ExcludeFromComponentScan { }
12.909091
44
0.71831
d057b12f0c1b4a7160220b6241f9811b965ca922
963
package com.hp.model; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * 错误处理结果 * Created by yaoyasong on 2016/5/4. */ public class ErrorResponse { private Integer code; private String message; private Throwable stackInfo; public ErrorResponse() { } public ErrorResponse(Integer code, String message, Throwable stackInfo) { this.code = code; this.message = message; this.stackInfo = stackInfo; } public Integer getCode() { return code; } public String getMessage() { return message; } public Throwable getStackInfo() { return stackInfo; } public String toJson() { try { return new ObjectMapper().writeValueAsString(this); } catch (JsonProcessingException e) { return "{\"msg\":\"Error occured while writing json string\"}"; } } }
21.886364
77
0.63136
d83246c2f23385c633c948e8d2ddddd1d5fc0ec8
5,352
/* * 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 co.edu.uniandes.csw.vivienda.ejb; import co.edu.uniandes.csw.vivienda.entities.UniversidadEntity; import co.edu.uniandes.csw.vivienda.exceptions.BusinessLogicException; import co.edu.uniandes.csw.vivienda.persistence.UniversidadPersistence; import java.util.List; import java.util.Random; import java.util.logging.*; import javax.ejb.Stateless; import javax.inject.Inject; /** * * @author Paula Molina */ @Stateless public class UniversidadLogic { private static final Logger LOGGER = Logger.getLogger(UniversidadLogic.class.getName()); @Inject private UniversidadPersistence universidadPersistence; // Variable para acceder a la persistencia de la aplicación. Es una inyección de dependencias. public UniversidadEntity createUniversidad(UniversidadEntity universidadEntity) throws BusinessLogicException { LOGGER.log(Level.INFO, "Inicia proceso de creación de la universdiad"); // Verifica la regla de negocio que dice que no puede haber dos editoriales con el mismo nombre if (universidadPersistence.findByName(universidadEntity.getNombre()) != null) { throw new BusinessLogicException("Ya existe una Universdiad con el nombre \"" + universidadEntity.getNombre() + "\""); } // Invoca la persistencia para crear la editorial universidadPersistence.create(universidadEntity); LOGGER.log(Level.INFO, "Termina proceso de creación de la universidad"); return universidadEntity; } public List<UniversidadEntity> getUniversidades() { LOGGER.log(Level.INFO, "Inicia proceso de consultar todas las universidades"); List<UniversidadEntity> universidades = universidadPersistence.findAll(); LOGGER.log(Level.INFO, "Termina proceso de consultar todas las universidades"); return universidades; } /** * Obtener una editorial por medio de su id. * * @param universidadId: id de la universidad para ser buscada. * @return la universidad solicitada por medio de su id. */ public UniversidadEntity getUniversidad(Long universidadId) { LOGGER.log(Level.INFO, "Inicia proceso de consultar la universidad con id = {0}", universidadId); UniversidadEntity universidadEntity = universidadPersistence.find(universidadId); if (universidadEntity == null) { LOGGER.log(Level.SEVERE, "La universidad con el id = {0} no existe", universidadId); } LOGGER.log(Level.INFO, "Termina proceso de consultar la universidad con id = {0}", universidadId); return universidadEntity; } /** * Actualizar una universidad. * * @param universidadId: id de la universidad para buscarla en la base de * datos. * @param universidadEntity: universidad con los cambios para ser actualizada, * por ejemplo el nombre. * @return la universidad con los cambios actualizados en la base de datos. */ public UniversidadEntity updateUniversidad(Long universidadId, UniversidadEntity universidadEntity) { LOGGER.log(Level.INFO, "Inicia proceso de actualizar la universidad con id = {0}", universidadId); UniversidadEntity newEntity = universidadPersistence.update(universidadEntity); LOGGER.log(Level.INFO, "Termina proceso de actualizar la universidad con id = {0}", universidadEntity.getId()); return newEntity; } /** * Borrar un universidad * * @param universidadId: id de la editorial a borrar */ public void deleteUniversidad(Long universidadId) { LOGGER.log(Level.INFO, "Inicia proceso de borrar la universidad con id = {0}", universidadId); universidadPersistence.delete(universidadId); LOGGER.log(Level.INFO, "Termina proceso de borrar la universidad con id = {0}", universidadId); } public void generarDatos() { List<UniversidadEntity> universidadesViejas = getUniversidades(); for(UniversidadEntity universidad: universidadesViejas) { deleteUniversidad(universidad.getId()); } Random rand = new Random(); String[] nombresUniversidades = new String[]{"Universidad de Los Andes", "Universidad Javeriana", "Universidad Nacional", "Universidad del Rosario", "Universidad Externado", "Universidad del Bosque", "Universidad de La Sabana", "CESA"}; for (int i = 0; i < nombresUniversidades.length; i++) { UniversidadEntity universidad = new UniversidadEntity(); String nombreUniversidad = nombresUniversidades[i]; universidad.setNombre(nombreUniversidad); universidad.setLongitud(rand.nextFloat()); universidad.setLatitud(rand.nextFloat()); universidad.setImgUrl("assets/img/universidad" + (i + 1) + ".png"); try { createUniversidad(universidad); } catch (Exception e) { LOGGER.log(Level.INFO, "Error en el proceso de crear la universidad"); } } } }
44.6
245
0.676196
476332c40d50fea134584d58079c914178382f73
1,801
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.network.implementation; import com.azure.resourcemanager.network.NetworkManager; import com.azure.resourcemanager.network.fluent.ApplicationSecurityGroupsClient; import com.azure.resourcemanager.network.fluent.inner.ApplicationSecurityGroupInner; import com.azure.resourcemanager.network.models.ApplicationSecurityGroup; import com.azure.resourcemanager.network.models.ApplicationSecurityGroups; import com.azure.resourcemanager.resources.fluentcore.arm.collection.implementation.TopLevelModifiableResourcesImpl; /** Implementation for ApplicationSecurityGroups. */ public class ApplicationSecurityGroupsImpl extends TopLevelModifiableResourcesImpl< ApplicationSecurityGroup, ApplicationSecurityGroupImpl, ApplicationSecurityGroupInner, ApplicationSecurityGroupsClient, NetworkManager> implements ApplicationSecurityGroups { public ApplicationSecurityGroupsImpl(final NetworkManager networkManager) { super(networkManager.inner().getApplicationSecurityGroups(), networkManager); } @Override public ApplicationSecurityGroupImpl define(String name) { return wrapModel(name); } @Override protected ApplicationSecurityGroupImpl wrapModel(String name) { ApplicationSecurityGroupInner inner = new ApplicationSecurityGroupInner(); return new ApplicationSecurityGroupImpl(name, inner, super.manager()); } @Override protected ApplicationSecurityGroupImpl wrapModel(ApplicationSecurityGroupInner inner) { if (inner == null) { return null; } return new ApplicationSecurityGroupImpl(inner.name(), inner, this.manager()); } }
40.022222
116
0.784564
0d8e73109ac96067d533ecc6b021d7f8f9206a82
367
package com.atguigu.gulimall.product.dao; import com.atguigu.gulimall.product.entity.BrandEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 品牌 * * @author yaojunyi * @email [email protected] * @date 2021-04-30 11:20:32 */ @Mapper public interface BrandDao extends BaseMapper<BrandEntity> { }
20.388889
59
0.760218
ab7c22200313171d1dc4e70da09d16673aa584c5
713
package com.regitiny.catiny.service.mapper; import com.regitiny.catiny.GeneratedByJHipster; import com.regitiny.catiny.domain.*; import com.regitiny.catiny.service.dto.FollowGroupDTO; import org.mapstruct.*; /** * Mapper for the entity {@link FollowGroup} and its DTO {@link FollowGroupDTO}. */ @Mapper(componentModel = "spring", uses = { BaseInfoMapper.class, GroupPostMapper.class }) @GeneratedByJHipster public interface FollowGroupMapper extends EntityMapper<FollowGroupDTO, FollowGroup> { @Mapping(target = "baseInfo", source = "baseInfo", qualifiedByName = "id") @Mapping(target = "followGroupDetails", source = "followGroupDetails", qualifiedByName = "id") FollowGroupDTO toDto(FollowGroup s); }
39.611111
96
0.774194
01d2b07ecafd27254fb7c349fb09b977a73325e9
144
package cn.shaojintian.smartordersys.model; import org.omg.CORBA.INITIALIZE; public enum OrderState { INIT,PAID,BREWING,TAKEN,CANCELLED }
18
43
0.791667
5887e683d3cc2f71885eb57802bbdcfa933c59ca
1,911
package au.gov.amsa.detection.behaviour; import java.util.function.Predicate; import au.gov.amsa.detection.Util; import au.gov.amsa.detection.model.Craft; import au.gov.amsa.detection.model.Craft.Events.Create; import au.gov.amsa.detection.model.Craft.Events.Position; import au.gov.amsa.detection.model.CraftIdentifierType; import au.gov.amsa.detection.model.DetectionRule; import au.gov.amsa.detection.model.Region; import xuml.tools.model.compiler.runtime.ArbitraryId; public class CraftBehaviour implements Craft.Behaviour { private final Craft self; // use constructor injection public CraftBehaviour(Craft self) { this.self = self; } @Override public void onEntryCreated(Create event) { self.setId(ArbitraryId.next()); self.setIdentifier(event.getCraftIdentifier()); self.setCraftIdentifierType_R20(CraftIdentifierType .select(CraftIdentifierType.Attribute.name.eq(event.getCraftIdentifierTypeName())) .one().get()); } @Override public void onEntryHasPosition(Position event) { // send the position to all detection rules Region.Events.Position position = Region.Events.Position.builder() .altitudeMetres(event.getAltitudeMetres()).latitude(event.getLatitude()) .longitude(event.getLongitude()).time(event.getTime()) .currentTime(event.getCurrentTime()).craftID(self.getId()).build(); Predicate<DetectionRule> isInTimeRange = dr -> Util.between(position.getTime(), dr.getStartTime(), dr.getEndTime()); DetectionRule.select().many().stream() // .filter(isInTimeRange) // .map(dr -> dr.getRegion_R1()) // .distinct() // .forEach(region -> region.signal(position)); } }
34.745455
98
0.652538
473f32cda578e13b061702e13adebe802daa1351
39,093
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package com.microsoft.sampleandroid; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.ar.core.Pose; import com.google.ar.sceneform.AnchorNode; import com.google.ar.sceneform.ArSceneView; import com.google.ar.sceneform.FrameTime; import com.google.ar.sceneform.Scene; import com.google.ar.sceneform.math.Vector3; import com.google.ar.sceneform.rendering.Color; import com.google.ar.sceneform.rendering.Material; import com.google.ar.sceneform.rendering.MaterialFactory; import com.google.ar.sceneform.rendering.Renderable; import com.google.ar.sceneform.rendering.ShapeFactory; import com.google.ar.sceneform.ux.ArFragment; //third-party lib to pick real path from url import com.hbisoft.pickit.PickiT; import com.hbisoft.pickit.PickiTCallbacks; import com.microsoft.azure.spatialanchors.AnchorLocateCriteria; import com.microsoft.azure.spatialanchors.AnchorLocatedEvent; import com.microsoft.azure.spatialanchors.CloudSpatialAnchor; import com.microsoft.azure.spatialanchors.LocateAnchorStatus; import com.microsoft.azure.spatialanchors.LocateAnchorsCompletedEvent; import com.microsoft.azure.spatialanchors.NearAnchorCriteria; import com.microsoft.azure.spatialanchors.SessionUpdatedEvent; import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; public class AzureSpatialAnchorsActivity extends AppCompatActivity implements PickiTCallbacks { private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 101; private static final int READ_REQUEST_CODE = 102; private static final int MY_PERMISSIONS_REQUEST_SAVE_CONTACTS = 103; private String anchorID; private String startAnchorID; private final ConcurrentHashMap<String, AnchorVisual> anchorVisuals = new ConcurrentHashMap<>(); private boolean basicDemo = true; private AzureSpatialAnchorsManager cloudAnchorManager; private DemoStep currentDemoStep = DemoStep.Start; private boolean enoughDataForSaving; private final Object progressLock = new Object(); private final Object renderLock = new Object(); // Materials private static Material failedColor; private static Material foundColor; private static Material readyColor; private static Material savedColor; private static Material targetColor; // UI Elements private ArFragment arFragment; private Button actionButton; private Button backButton; private TextView scanProgressText; private ArSceneView sceneView; private TextView statusText; private AnchorArrow arrow; //layout element private RadioGroup radioGroup; private RadioButton radioButton; private TextView textView; private Button navigateButton; private Spinner spinner; private final Vector3 camRelPose = new Vector3(0.0f, 0.2f, -1.5f); private final Vector3 boardLocalPos = new Vector3(0.0f, 0.3f, 0.0f); //navigation relevent private float distance; private final float NAVI_LIMIT = 1.0f; private AnchorNode sourceAnchorNode = new AnchorNode(); private boolean navigationInit; private AnchorMap anchorMap; ArrayList<String> optPath = new ArrayList<>(); Stack<String> stack_id = new Stack<>(); private String sourceName = null; private String targetName = null; private PickiT pickit; //back button detector public void exitDemoClicked(View v) { synchronized (renderLock) { destroySession(); finish(); } } @Override @SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"}) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_anchors); basicDemo = getIntent().getBooleanExtra("BasicDemo", true); arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment); sceneView = arFragment.getArSceneView(); Scene scene = sceneView.getScene(); //set arrow arrow = new AnchorArrow(this, camRelPose, arFragment.getTransformationSystem(),scene); scene.getCamera().addChild(arrow); arrow.setEnabled(false); arrow.setTargetEnabled(false); scene.addOnUpdateListener( new Scene.OnUpdateListener() { @Override public void onUpdate(FrameTime Frame) { if (cloudAnchorManager != null) { // Pass frames to Spatial Anchors for processing. cloudAnchorManager.update(sceneView.getArFrame()); } if (currentDemoStep == DemoStep.NavigationStart) { Vector3 cameraPosition = sceneView.getScene().getCamera().getWorldPosition(); Vector3 targetPosition = arrow.getTargetPos(); distance = (float) ( Math.sqrt(targetPosition.x * targetPosition.x + targetPosition.z * targetPosition.z)- Math.sqrt(cameraPosition.x * cameraPosition.x + cameraPosition.z * cameraPosition.z)); if(statusText.getVisibility()==statusText.INVISIBLE) { statusText.setVisibility(View.VISIBLE); } statusText.setText(String.valueOf(distance)); // statusText.setText(String.format("%f, %f, %f",targetPosition.x,targetPosition.y,targetPosition.z)); if (distance < NAVI_LIMIT ) { advanceDemo(); } } } }); backButton = findViewById(R.id.backButton); statusText = findViewById(R.id.statusText); scanProgressText = findViewById(R.id.scanProgressText); actionButton = findViewById(R.id.actionButton); actionButton.setOnClickListener((View v) -> advanceDemo()); radioGroup = findViewById(R.id.radioGroup); textView = findViewById(R.id.anchor_Selected); navigateButton = findViewById(R.id.navigate); spinner = findViewById(R.id.spinner); backButton.setVisibility(View.VISIBLE); navigateButton.setOnClickListener((View v) -> onClickNavigateButton()); MaterialFactory.makeOpaqueWithColor(this, new Color(android.graphics.Color.RED)) .thenAccept(material -> failedColor = material); MaterialFactory.makeOpaqueWithColor(this, new Color(android.graphics.Color.GREEN)) .thenAccept(material -> savedColor = material); MaterialFactory.makeOpaqueWithColor(this, new Color(android.graphics.Color.YELLOW)) .thenAccept(material -> { readyColor = material; foundColor = material; }); MaterialFactory.makeOpaqueWithColor(this, new Color(ContextCompat.getColor(this, R.color.SeaGreen))) .thenAccept(material -> { targetColor=material; }); //set variable to pick real path from url pickit = new PickiT(this, this); } @Override protected void onDestroy() { super.onDestroy(); if (!isChangingConfigurations()) { pickit.deleteTemporaryFile(); } destroySession(); } @Override protected void onResume() { super.onResume(); // ArFragment of Sceneform automatically requests the camera permission before creating the AR session, // so we don't need to request the camera permission explicitly. // This will cause onResume to be called again after the user responds to the permission request. if (!SceneformHelper.hasCameraPermission(this)) { return; } if (sceneView != null && sceneView.getSession() == null) { SceneformHelper.setupSessionForSceneView(this, sceneView); } if (AzureSpatialAnchorsManager.SpatialAnchorsAccountId.equals("Set me") || AzureSpatialAnchorsManager.SpatialAnchorsAccountKey.equals("Set me")) { Toast.makeText(this, "\"Set SpatialAnchorsAccountId and SpatialAnchorsAccountKey in AzureSpatialAnchorsManager.java\"", Toast.LENGTH_LONG) .show(); finish(); } if (currentDemoStep == DemoStep.Start) { startDemo(); } } private void advanceDemo() { switch (currentDemoStep) { case LookForNearbyAnchors: if (anchorVisuals.isEmpty() || !anchorVisuals.containsKey(anchorID)) { runOnUiThread(() -> statusText.setText("Cannot locate nearby. Previous anchor not yet located.")); break; } AnchorLocateCriteria nearbyLocateCriteria = new AnchorLocateCriteria(); NearAnchorCriteria nearAnchorCriteria = new NearAnchorCriteria(); nearAnchorCriteria.setDistanceInMeters(10); nearAnchorCriteria.setSourceAnchor(anchorVisuals.get(anchorID).getCloudAnchor()); nearbyLocateCriteria.setNearAnchor(nearAnchorCriteria); // Cannot run more than one watcher concurrently stopWatcher(); cloudAnchorManager.startLocating(nearbyLocateCriteria); runOnUiThread(() -> { actionButton.setVisibility(View.INVISIBLE); statusText.setText("Locating..."); }); break; case LoadMap: if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } Intent intent = new Intent(Intent.ACTION_GET_CONTENT); String map_path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MixRealityNavi" + File.separator + "Maps" + File.separator; File map_dir = new File(map_path); if (!map_dir.exists()) { map_dir.mkdirs(); Toast.makeText(this, "No Map file found in this device!", Toast.LENGTH_LONG).show(); } intent.addCategory(Intent.CATEGORY_OPENABLE); Uri uri = Uri.parse(map_path); intent.setDataAndType(uri, "*/*"); startActivityForResult(intent, READ_REQUEST_CODE); break; case ChooseStartPoint: ArrayList<Node> nodelist = anchorMap.getNodeList(); ArrayList<String> anchorlist = new ArrayList<String>(); backButton.setVisibility(View.GONE); int n = 0; while (n < nodelist.size()) { anchorlist.add(nodelist.get(n).AnchorName); n++; } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, anchorlist); spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(spinnerAdapter); spinnerAdapter.notifyDataSetChanged(); runOnUiThread(() -> { actionButton.setVisibility(View.INVISIBLE); statusText.setText("Select Start Point"); navigateButton.setVisibility(View.VISIBLE); navigateButton.setText("Confirm"); spinner.setVisibility(View.VISIBLE); }); break; case LookForAnchor: // We need to restart the session to find anchors we created. startNewSession(); AnchorLocateCriteria criteria = new AnchorLocateCriteria(); //criteria.setBypassCache(true); //不规定而是找到最近的anchor //String EMPTY_STRING = ""; criteria.setIdentifiers(new String[]{startAnchorID}); // Cannot run more than one watcher concurrently stopWatcher(); cloudAnchorManager.startLocating(criteria); runOnUiThread(() -> { statusText.setText("Look for anchor at your position, please walk around......"); }); break; case ChooseEndPoint: if(actionButton.getVisibility()==View.VISIBLE) { actionButton.setVisibility(View.INVISIBLE); } navigateButton.setVisibility(View.VISIBLE); navigateButton.setText("Confirm"); spinner.setVisibility(View.VISIBLE); break; case NavigationStart: //test target anchor if(navigationInit) { if (targetName == null) { Toast.makeText(this, "\"ERROR: No target Selected!\"", Toast.LENGTH_LONG) .show(); // re-choose from list runOnUiThread(() -> { statusText.setText("please choose target from the list"); actionButton.setVisibility(View.INVISIBLE); navigateButton.setVisibility(View.VISIBLE); navigateButton.setText("Confirm"); spinner.setVisibility(View.VISIBLE); }); return; } // Get Optimal path for navigation anchorMap.searchSP(sourceName, targetName, optPath); for (int i = optPath.size() - 1; i >= 0; i--) { stack_id.push(anchorMap.getNode(optPath.get(i)).AnchorName); } navigationInit = false; //init arrow target Renderable nodeRenderable = ShapeFactory.makeSphere(0.08f, new Vector3(0.0f, 0.15f, 0.0f), readyColor); arrow.setTargetRenderable(nodeRenderable); // advanceDemo(); // return; } Pose sourceMapPos = anchorMap.getPos(sourceName); Pose sourceAnchorPos = sourceAnchorNode.getAnchor().getPose(); sourceMapPos = sourceMapPos.inverse(); if(!stack_id.isEmpty()){ //compute the position of next anchor String nextTarget = stack_id.pop(); Pose nextAnchorPos = anchorMap.getPos(nextTarget); float[] nextAnchorTranslationMap = nextAnchorPos.getTranslation(); float[] nextAnchorTranslation = sourceAnchorPos.transformPoint(sourceMapPos.transformPoint(nextAnchorTranslationMap)); if(!arrow.isEnabled()) { arrow.setEnabled(true); arrow.setTargetEnabled(true); } arrow.updateTargetPos(new Vector3(nextAnchorTranslation[0],nextAnchorTranslation[1],nextAnchorTranslation[2])); arrow.updateTargetBoard(nextTarget); // render the map next target as sphere and hold it in anchorvisuals // startNewSession(); //use localizer to find the anchor and thus improve the accuracy if(stack_id.isEmpty()) { // Renderable render = ShapeFactory.makeCylinder(0.2f, 0.5f, new Vector3(0.f, 0.25f, 0.f), targetColor); arrow.updateTargetBoard("Your destination: " + nextTarget); arrow.setTargetRenderable(null); arrow.setDestinationRenderable(); } AnchorLocateCriteria nextCriteria = new AnchorLocateCriteria(); //criteria.setBypassCache(true); //不规定而是找到最近的anchor nextCriteria.setIdentifiers(new String[]{anchorMap.getNode(nextTarget).AnchorID}); // Cannot run more than one watcher concurrently stopWatcher(); cloudAnchorManager.startLocating(nextCriteria); break; } else{ // if empty then target is reached //render targetnode //create renderable for target shape if (!arrow.isTargetEnabled()) { arrow.setTargetEnabled(true); } currentDemoStep = DemoStep.NavigationEnd; actionButton.setVisibility(View.VISIBLE); statusText.setText("Target reached! Press to exit navigation"); actionButton.setText("End Navigation"); break; } case NavigationEnd: arrow.setTargetEnabled(false); arrow.setEnabled(false); //no need to continue search stopWatcher(); currentDemoStep = DemoStep.End; if(actionButton.getVisibility()==View.INVISIBLE){ actionButton.setVisibility(View.VISIBLE); } actionButton.setText("Press to Refresh"); break; case End: // for (AnchorVisual toDeleteVisual : anchorVisuals.values()) { // cloudAnchorManager.deleteAnchorAsync(toDeleteVisual.getCloudAnchor()); // } arrow.clear(); destroySession(); anchorMap.destory(); runOnUiThread(() -> { actionButton.setText("Restart"); statusText.setText(""); backButton.setVisibility(View.VISIBLE); }); sourceAnchorNode = new AnchorNode(); optPath = new ArrayList<>(); stack_id = new Stack<>(); sourceName = null; targetName = null; currentDemoStep = DemoStep.Restart; clearVisuals(); break; case Restart: startDemo(); break; } } private void clearVisuals() { for (AnchorVisual visual : anchorVisuals.values()) { arFragment.getArSceneView().getScene().removeChild(visual.getAnchorNode()); visual.getLocalAnchor().detach(); visual.getAnchorNode().setParent(null); visual.destroy(); } anchorVisuals.clear(); } private void destroySession() { if (cloudAnchorManager != null) { cloudAnchorManager.stop(); cloudAnchorManager = null; } clearVisuals(); } @SuppressLint("SetTextI18n") private void onAnchorLocated(AnchorLocatedEvent event) { LocateAnchorStatus status = event.getStatus(); runOnUiThread(() -> { switch (status) { case AlreadyTracked: statusText.setText("AlreadyTracked"); break; case Located: renderLocatedAnchor(event.getAnchor()); if(currentDemoStep==DemoStep.LookForAnchor) { statusText.setText("Source anchor found!"); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { // Actions to do after 10 seconds } }, 2000); } break; case NotLocatedAnchorDoesNotExist: statusText.setText("Anchor does not exist"); break; } }); } //当criteria定义的寻找目标全部完成时调用,不然一直调用onAnchorLocated() private void onLocateAnchorsCompleted(LocateAnchorsCompletedEvent event) { // Here we only look for the source Anchor if (currentDemoStep == DemoStep.LookForAnchor) { // stopWatcher(); runOnUiThread(() -> { statusText.setText("Next choose and confirm the target place"); if(actionButton.getVisibility()==View.INVISIBLE){ actionButton.setVisibility(View.VISIBLE); } //set button temporal invisiable currentDemoStep = DemoStep.ChooseEndPoint; actionButton.setText("choose target place"); navigateButton.setVisibility(View.INVISIBLE); }); return; } if (currentDemoStep == DemoStep.NavigationStart) { // runOnUiThread(() -> { // Toast.makeText(this, "Find one", Toast.LENGTH_SHORT).show(); // }); return; } } @SuppressLint("SetTextI18n") private void onSessionUpdated(SessionUpdatedEvent args) { float progress = args.getStatus().getRecommendedForCreateProgress(); enoughDataForSaving = progress >= 1.0; synchronized (progressLock) { if (currentDemoStep == DemoStep.SaveCloudAnchor) { DecimalFormat decimalFormat = new DecimalFormat("00"); runOnUiThread(() -> { String progressMessage = "Scan progress is " + decimalFormat.format(Math.min(1.0f, progress) * 100) + "%"; scanProgressText.setText(progressMessage); }); if (enoughDataForSaving && actionButton.getVisibility() != View.VISIBLE) { // Enable the save button runOnUiThread(() -> { statusText.setText("Ready to save"); actionButton.setText("Save cloud anchor"); actionButton.setVisibility(View.VISIBLE); }); currentDemoStep = DemoStep.SaveCloudAnchor; } } } } private void renderLocatedAnchor(CloudSpatialAnchor anchor) { if (currentDemoStep == DemoStep.LookForAnchor) { AnchorVisual foundVisual = new AnchorVisual(anchor.getLocalAnchor()); // temptargetAnchor = foundVisual.getAnchorNode(); anchorVisuals.put("", foundVisual); foundVisual.setCloudAnchor(anchor); foundVisual.getAnchorNode().setParent(arFragment.getArSceneView().getScene()); foundVisual.setColor(foundColor); AnchorBoard anchorBoard = new AnchorBoard(this, sourceName, 0.5f, boardLocalPos); anchorBoard.setParent(foundVisual.getAnchorNode()); foundVisual.render(arFragment); //store the source anchor sourceAnchorNode = foundVisual.getAnchorNode(); } else if (currentDemoStep == DemoStep.NavigationStart) { // Render anchors during the navigation process, can be deleted later AnchorVisual foundVisual = new AnchorVisual(anchor.getLocalAnchor()); anchorVisuals.put(anchor.getIdentifier(),foundVisual); float[] nextLocateAnchor = anchor.getLocalAnchor().getPose().getTranslation(); arrow.updateTargetPos(new Vector3(nextLocateAnchor[0],nextLocateAnchor[1],nextLocateAnchor[2])); } else if (currentDemoStep == DemoStep.NavigationEnd) { AnchorVisual foundVisual = new AnchorVisual(anchor.getLocalAnchor()); anchorVisuals.put(anchor.getIdentifier(),foundVisual); float[] nextLocateAnchor = foundVisual.getAnchorNode().getAnchor().getPose().getTranslation(); arrow.updateTargetPos(new Vector3(nextLocateAnchor[0],nextLocateAnchor[1],nextLocateAnchor[2])); } } private void startDemo() { startNewSession(); runOnUiThread(() -> { scanProgressText.setVisibility(View.GONE); actionButton.setVisibility(View.VISIBLE); actionButton.setText("Load Map"); navigateButton.setVisibility(View.INVISIBLE); radioGroup.setVisibility(View.INVISIBLE); textView.setVisibility(View.INVISIBLE); spinner.setVisibility(View.INVISIBLE); }); currentDemoStep = DemoStep.LoadMap; } private void startNewSession() { destroySession(); cloudAnchorManager = new AzureSpatialAnchorsManager(sceneView.getSession()); cloudAnchorManager.addAnchorLocatedListener(this::onAnchorLocated); cloudAnchorManager.addLocateAnchorsCompletedListener(this::onLocateAnchorsCompleted); cloudAnchorManager.addSessionUpdatedListener(this::onSessionUpdated); cloudAnchorManager.start(); } private void stopWatcher() { if (cloudAnchorManager != null) { cloudAnchorManager.stopLocating(); } } private void onClickNavigateButton() { if (currentDemoStep == DemoStep.ChooseStartPoint) { // Use Spinner sourceName = spinner.getSelectedItem().toString(); startAnchorID = anchorMap.getNode(sourceName).AnchorID; runOnUiThread(() -> { actionButton.setVisibility(View.INVISIBLE); spinner.setVisibility(View.INVISIBLE); navigateButton.setVisibility(View.INVISIBLE); }); currentDemoStep = DemoStep.LookForAnchor; advanceDemo(); } else if (currentDemoStep == DemoStep.ChooseEndPoint) { targetName = spinner.getSelectedItem().toString(); runOnUiThread(() -> { statusText.setText("target place selected, navigation start soon"); spinner.setVisibility(View.INVISIBLE); navigateButton.setVisibility(View.INVISIBLE); }); currentDemoStep = DemoStep.NavigationStart; //init navigation process navigationInit =true; advanceDemo(); } } public void checkButton(View v) { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); Toast.makeText(this, "Select" + radioButton.getText(), Toast.LENGTH_SHORT).show(); } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_READ_CONTACTS: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // advanceDemo(); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Toast.makeText(this, "No Read Permission!", Toast.LENGTH_LONG).show(); // permission denied, boo! Disable the // functionality that depends on this permission. finish(); } break; } case MY_PERMISSIONS_REQUEST_SAVE_CONTACTS: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //change for further improvement // advanceDemo(); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Toast.makeText(this, "No Save Permission!", Toast.LENGTH_LONG).show(); // permission denied, boo! Disable the // functionality that depends on this permission. finish(); } break; } } } //************* activity processor for load map function ****************************// public void onActivityResult(int requestCode, int resultCode, Intent resultData) { // The ACTION_OPEN_DOCUMENT intent was sent with the request code // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the // response to some other intent, and the code below shouldn't run at all. if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). if (resultData != null) { pickit.getPath(resultData.getData(), Build.VERSION.SDK_INT); // use pickit callback } else { Toast.makeText(this, "Error: content is Null! please reload!", Toast.LENGTH_SHORT).show(); Log.d("LoadMap", ":selected file is invalid."); return; } } else { Toast.makeText(this, "Error: Intent response failed!", Toast.LENGTH_SHORT).show(); Log.d("LoadMap", ":Load Intent response failed."); } } //@following three functions are override of PickiT that get real path from uri @Override public void PickiTonStartListener() { } @Override public void PickiTonProgressUpdate(int progress) { } @Override public void PickiTonCompleteListener(String path, boolean wasDriveFile, boolean wasUnknownProvider, boolean wasSuccessful, String Reason) { // Check if it was a Drive/local/unknown provider file and display a Toast if (wasDriveFile) { Toast.makeText(this, "Drive file was selected", Toast.LENGTH_LONG).show(); } else if (wasUnknownProvider) { Toast.makeText(this, "File was selected from unknown provider", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Local file was selected", Toast.LENGTH_LONG).show(); } //check if text read successful if (wasSuccessful) { // Set returned path to TextView FileManager file = new FileManager(); AnchorMap LoadMap = file.loadMap(path); if (LoadMap != null) { anchorMap = LoadMap; Toast.makeText(this, "Load map from: " + path, Toast.LENGTH_LONG).show(); // Permission has already been granted currentDemoStep = DemoStep.ChooseStartPoint; //set button temporal invisiable actionButton.setVisibility(View.VISIBLE); actionButton.setText("choose start point"); statusText.setText("Map Loaded"); // Permission has already been granted } } else { Toast.makeText(this, "Cannot read the map file! \n Please check and reload!", Toast.LENGTH_SHORT).show(); Log.d("LoadMapFail", " :" + Toast.LENGTH_LONG); } } //delete temporal files if it is read from unknown sources or provider @Override public void onBackPressed() { pickit.deleteTemporaryFile(); super.onBackPressed(); } enum DemoStep { Start, ///< the start of the demo SaveCloudAnchor, ///< the session will save the cloud anchor LookForAnchor, ///< the session will run the query LookForNearbyAnchors, ///< the session will run a query for nearby anchors LoadMap, ///< load map ChooseStartPoint, ChooseEndPoint, NavigationStart, ///< the session will run for navigation NavigationEnd, ///< the navigation is end End, ///< the end of the demo Restart, ///< waiting to restart } enum NodeType { ///< classify nodes into 3 types Major, ///< node that represents important and meaningful location Minor, ///< node that used for tracking and accuracy improve. Cross, ///< node where new graph branch is generated } } // //for (AnchorVisual visuals : anchorVisuals.values()){ // visuals.getAnchorNode().setOnTapListener(this::onTapListener); // } // break; // ********onLocatedCompelete()*************** // if (!basicDemo && currentDemoStep == DemoStep.LookForAnchor) { // runOnUiThread(() -> { // actionButton.setVisibility(View.VISIBLE); // actionButton.setText("Look for anchors nearby"); // }); // currentDemoStep = DemoStep.LookForNearbyAnchors; // } else { // stopWatcher(); // runOnUiThread(() -> { // actionButton.setVisibility(View.VISIBLE); // //actionButton.setText("Cleanup anchors"); // actionButton.setText("Start Navigation"); // }); // currentDemoStep = DemoStep.NavigationStart; // } // public static Matrix3f getTransformationMatrix(Vector3f vec1, Vector3f vec2) { // // // vec1.normalize(); // // vec2.normalize(); // Vector3f v = new Vector3f(); // v.cross(vec1, vec2); // float sinAngle = v.length(); // float c = vec1.dot(vec2); // // //build matrix // Matrix3f u = new Matrix3f(0.f, -v.z, v.y, v.z, 0.f, -v.x, -v.y, v.x, 0.f); // Matrix3f u2 = new Matrix3f(); // u2.mul(u, u); // // //coeff // float coeff = 1.f / (1 + c); // Matrix3f I = new Matrix3f(); // I.setIdentity(); // u.add(I);//I + u // u2.mul(coeff);//u*c // u.add(u2);//u+u2 // // return u; // } // // public double[][] getTransformationMatrix(Vector3 vec1, Vector3 vec2) { // // Vector3 v = Vector3.cross(vec1, vec2); // float s = (float) Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z); // float c = Vector3.dot(vec1, vec2); // float scale = (float) 1 / (1 + c);//(1-c)/(s*s); // // Matrix3d vx = new Matrix3d(0, -v.z, v.y, v.z, 0, -v.x, -v.y, v.x, 0); // Matrix3d eye = new Matrix3d(1, 0, 0, 0, 1, 0, 0, 0, 1); // Matrix3d vx2 = new Matrix3d(); // vx2.mul(vx, vx); // vx2.mul(scale); // vx.add(vx2); // Matrix3d rotationMatrix = new Matrix3d(); // rotationMatrix.add(eye, vx); // // double[][] R = new double[3][3]; // R[0][0] = 1 + 0 + scale * (-v.z * v.z - v.y * v.y); // R[0][1] = 0 + (-v.z) + scale * (v.x * v.y); // R[0][2] = 0 + v.y + scale * (v.x * v.z); // // R[1][0] = 0 + v.z + scale * (v.x * v.y); // R[1][1] = 1 + 0 + scale * (-v.z * v.z - v.x * v.x); // R[1][2] = 0 + (-v.x) + scale * (v.y * v.z); // // R[2][0] = 0 + (-v.y) + scale * (v.x * v.z); // R[2][1] = 0 + v.x + scale * (v.y * v.z); // R[2][2] = 1 + 0 + scale * (-v.y * v.y - v.x * v.x); // return R; // } // // public Vector3 getTransformedCoordinates(double[][] matrix, Vector3 vec) { // float x = (float) (matrix[0][0] * vec.x + matrix[0][1] * vec.y + matrix[0][2] * vec.z); // float y = (float) (matrix[1][0] * vec.x + matrix[1][1] * vec.y + matrix[1][2] * vec.z); // float z = (float) (matrix[2][0] * vec.x + matrix[2][1] * vec.y + matrix[2][2] * vec.z); //// Vector3d v1 = new Vector3d(); //// Vector3d v2 = new Vector3d(); //// Vector3d v3 = new Vector3d(); //// Vector3d v = new Vector3d(vec.x, vec.y, vec.z); //// matrix.getColumn(0, v1); //// matrix.getColumn(0, v2); //// matrix.getColumn(0, v3); //// float x = (float) v1.dot(v); //// float y = (float) v2.dot(v); //// float z = (float) v3.dot(v); // Vector3 vec_transf = new Vector3(x, y, z); // return vec_transf; // } //case CreateSessionForQuery: // cloudAnchorManager.stop(); // cloudAnchorManager.reset(); // clearVisuals(); // // runOnUiThread(() -> { // statusText.setText(""); // actionButton.setText("Locate anchor"); // }); // // currentDemoStep = DemoStep.LookForAnchor; // // break; // public void LookforAnchor_realtime(String nextAnchorID) { // // Do we need startNewSession? // cloudAnchorManager.stop(); // cloudAnchorManager.reset(); // startNewSession(); // anchorID = nextAnchorID; // AnchorLocateCriteria criteria = new AnchorLocateCriteria(); // //criteria.setBypassCache(true); // //不规定而是找到最近的anchor // //String EMPTY_STRING = ""; // // criteria.setIdentifiers(new String[]{anchorID}); // // Cannot run more than one watcher concurrently // stopWatcher(); // cloudAnchorManager.startLocating(criteria); // runOnUiThread(() -> { // actionButton.setVisibility(View.INVISIBLE); // statusText.setText("Look for anchor"); // }); // }
41.107256
154
0.571535
0bc62633f307b0ea69afe546208ec7a996da3a46
925
package se.cygni.game.worldobject; public class SnakeBody implements SnakePart { private SnakePart nextSnakePart = null; private int position; public SnakeBody() { } public SnakeBody(SnakePart nextSnakePart) { this.nextSnakePart = nextSnakePart; } public SnakeBody(int position) { this.position = position; } @Override public SnakePart getNextSnakePart() { return nextSnakePart; } @Override public void setNextSnakePart(SnakePart nextSnakePart) { this.nextSnakePart = nextSnakePart; } @Override public boolean isHead() { return false; } @Override public boolean isTail() { return getNextSnakePart() == null; } @Override public int getPosition() { return position; } @Override public void setPosition(int position) { this.position = position; } }
18.877551
59
0.631351
f5e8b7a2ae1236dcc3d769eb371ed27cf2d92d60
1,456
package eu.stefanangelov.chatbot.chatservice.service; import org.springframework.stereotype.Service; import org.springframework.web.socket.WebSocketSession; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This service is responsible to handle all operation from web socket * * Created by Stefan Angelov - Delta Source Bulgaria on 26.12.18. */ @Service public class SessionService { private Map<String, List<WebSocketSession>> sessions = new ConcurrentHashMap<>(); /** * Remove web socket from map * @param userIdentificator user identicator */ public void removeSessions(String userIdentificator){ sessions.remove(sessions); } /** * Add web socket with key user identificator * @param webSocketSession current web socket session * @param userIdentificator user identificator */ public void addSession(WebSocketSession webSocketSession, String userIdentificator){ sessions.computeIfAbsent(userIdentificator, value-> new ArrayList<>()).add(webSocketSession); } /** * Find user web socket by user identificator * @param userIdentificator user identificator * @return all open web socket session for specific user */ public List<WebSocketSession> findSessionsByUserIdentificator(String userIdentificator){ return sessions.get(userIdentificator); } }
30.333333
101
0.734203
c9566f2569ef36a80a80e27f718d96efb45ca4a7
6,702
package io.configrd.core.aws.s3; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.util.Date; import java.util.Optional; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.AmazonS3URI; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.StorageClass; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.common.base.Throwables; import com.jsoniter.output.JsonStream; import io.configrd.core.processor.JsonProcessor; import io.configrd.core.processor.ProcessorSelector; import io.configrd.core.processor.PropertiesProcessor; import io.configrd.core.processor.YamlProcessor; import io.configrd.core.source.FileStreamSource; import io.configrd.core.source.PropertyPacket; import io.configrd.core.source.RepoDef; import io.configrd.core.source.StreamPacket; import io.configrd.core.source.StreamSource; import io.configrd.core.util.StringUtils; import io.configrd.core.util.URIBuilder; public class S3StreamSource implements StreamSource, FileStreamSource { private final static Logger logger = LoggerFactory.getLogger(S3StreamSource.class); private final S3RepoDef repoDef; private final URIBuilder builder; private AmazonS3 s3Client; private final String bucketName; private final AWSCredentialsProvider creds; public static final String S3 = "s3"; public S3StreamSource(S3RepoDef repoDef, AWSCredentialsProvider creds) { this.repoDef = repoDef; builder = URIBuilder.create(toURI()); if (this.repoDef.getTrustCert() == null && StringUtils .hasText(System.getProperty(io.configrd.service.SystemProperties.S3_TRUST_CERTS))) { this.repoDef.setTrustCert( Boolean.valueOf(System.getProperty(io.configrd.service.SystemProperties.S3_TRUST_CERTS))); } bucketName = extractBucketName(toURI()); this.creds = creds; } private URI toURI() { URIBuilder builder = URIBuilder.create(URI.create(repoDef.getUri())).setFileNameIfMissing(repoDef.getFileName()); return builder.build(); } @Override public Optional<? extends PropertyPacket> stream(String path) { Optional<StreamPacket> packet = streamFile(path); URI uri = prototypeURI(path); try { if (packet.isPresent()) { packet.get().putAll( ProcessorSelector.process(packet.get().getUri().toString(), packet.get().bytes())); } } catch (IOException e) { logger.error(e.getMessage()); } return packet; } public boolean put(String path, PropertyPacket packet) { long start = System.currentTimeMillis(); CannedAccessControlList acl = CannedAccessControlList.AuthenticatedRead; ObjectMetadata omd = new ObjectMetadata(); omd.setContentType(MediaType.APPLICATION_OCTET_STREAM); omd.setContentDisposition("attachment; filename=" + repoDef.getFileName()); omd.setLastModified(new Date()); PutObjectRequest request = null; boolean success = false; String content = null; try { if (PropertiesProcessor.isPropertiesFile(repoDef.getFileName())) { content = PropertiesProcessor.toText(packet); } else if (YamlProcessor.isYamlFile(repoDef.getFileName())) { content = new YAMLMapper().writeValueAsString(packet); } else if (JsonProcessor.isJsonFile(repoDef.getFileName())) { content = JsonStream.serialize(packet); } } catch (JsonProcessingException e) { // TODO: handle exception } try (ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes())) { omd.setContentLength(content.getBytes().length); request = new PutObjectRequest(bucketName, path, is, omd); request.setStorageClass(StorageClass.ReducedRedundancy); if (acl != null) { request.setCannedAcl(acl); } PutObjectResult result = s3Client.putObject(request); String etag = result.getETag(); if (io.configrd.core.util.StringUtils.hasText(etag)) { success = true; } } catch (IOException e) { // TODO: handle exception } logger.trace( "Amazon Connector Upload of object " + path + " of size " + content.length() / 1048576 + " MB took: " + (System.currentTimeMillis() - start) / 1000 + " seconds."); return success; } protected String extractBucketName(URI location) { AmazonS3URI uri = new AmazonS3URI(location); return uri.getBucket(); } @Override public String getSourceName() { return S3; } @Override public RepoDef getSourceConfig() { return repoDef; } @Override public URI prototypeURI(String path) { return builder.build(path); } @Override public void close() { s3Client.shutdown(); } @Override public void init() { s3Client = AmazonS3ClientBuilder.standard().withRegion("us-east-1") .withForceGlobalBucketAccessEnabled(true).withCredentials(creds).build(); } @Override public Optional<StreamPacket> streamFile(String path) { StreamPacket packet = null; URI uri = prototypeURI(path); long start = System.currentTimeMillis(); String fpath = org.apache.commons.lang3.StringUtils.removeStart(uri.getPath(), "/"); logger.debug("Requesting bucket " + bucketName + ", path: " + fpath); try (S3Object object = s3Client.getObject(bucketName, fpath);) { if (object.getObjectContent() != null) { packet = new StreamPacket(uri, object.getObjectContent(), object.getObjectMetadata().getContentLength()); packet.setETag(object.getObjectMetadata().getETag()); } else { logger.debug("No file found: " + bucketName + " path:" + fpath); } } catch (AmazonS3Exception e) { if (e.getStatusCode() != 404) { logger.error(e.getMessage()); Throwables.propagate(e); } } catch (IOException io) { logger.error(io.getMessage()); Throwables.propagate(io); } logger.trace( "Amazon Connector Took: " + (System.currentTimeMillis() - start) + "ms to fetch " + uri); return Optional.ofNullable(packet); } }
29.012987
100
0.710087
b3a3a0040b639484dc95e76b493503adfe0cf31c
265
package com.hankcs.hanlp.model.bigram; import junit.framework.TestCase; public class BigramDependencyModelTest extends TestCase { public void testLoad() throws Exception { assertEquals("限定", BigramDependencyModel.get("传", "v", "角落", "n")); } }
24.090909
75
0.70566
4bcac2ed71712979efade2636f03867ac5299c04
26,895
package org.github.dtsopensource.admin.dao.dataobject; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ActivityRuleDOExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ActivityRuleDOExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andBizTypeIsNull() { addCriterion("biz_type is null"); return (Criteria) this; } public Criteria andBizTypeIsNotNull() { addCriterion("biz_type is not null"); return (Criteria) this; } public Criteria andBizTypeEqualTo(String value) { addCriterion("biz_type =", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotEqualTo(String value) { addCriterion("biz_type <>", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeGreaterThan(String value) { addCriterion("biz_type >", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeGreaterThanOrEqualTo(String value) { addCriterion("biz_type >=", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeLessThan(String value) { addCriterion("biz_type <", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeLessThanOrEqualTo(String value) { addCriterion("biz_type <=", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeLike(String value) { addCriterion("biz_type like", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotLike(String value) { addCriterion("biz_type not like", value, "bizType"); return (Criteria) this; } public Criteria andBizTypeIn(List<String> values) { addCriterion("biz_type in", values, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotIn(List<String> values) { addCriterion("biz_type not in", values, "bizType"); return (Criteria) this; } public Criteria andBizTypeBetween(String value1, String value2) { addCriterion("biz_type between", value1, value2, "bizType"); return (Criteria) this; } public Criteria andBizTypeNotBetween(String value1, String value2) { addCriterion("biz_type not between", value1, value2, "bizType"); return (Criteria) this; } public Criteria andAppIsNull() { addCriterion("app is null"); return (Criteria) this; } public Criteria andAppIsNotNull() { addCriterion("app is not null"); return (Criteria) this; } public Criteria andAppEqualTo(String value) { addCriterion("app =", value, "app"); return (Criteria) this; } public Criteria andAppNotEqualTo(String value) { addCriterion("app <>", value, "app"); return (Criteria) this; } public Criteria andAppGreaterThan(String value) { addCriterion("app >", value, "app"); return (Criteria) this; } public Criteria andAppGreaterThanOrEqualTo(String value) { addCriterion("app >=", value, "app"); return (Criteria) this; } public Criteria andAppLessThan(String value) { addCriterion("app <", value, "app"); return (Criteria) this; } public Criteria andAppLessThanOrEqualTo(String value) { addCriterion("app <=", value, "app"); return (Criteria) this; } public Criteria andAppLike(String value) { addCriterion("app like", value, "app"); return (Criteria) this; } public Criteria andAppNotLike(String value) { addCriterion("app not like", value, "app"); return (Criteria) this; } public Criteria andAppIn(List<String> values) { addCriterion("app in", values, "app"); return (Criteria) this; } public Criteria andAppNotIn(List<String> values) { addCriterion("app not in", values, "app"); return (Criteria) this; } public Criteria andAppBetween(String value1, String value2) { addCriterion("app between", value1, value2, "app"); return (Criteria) this; } public Criteria andAppNotBetween(String value1, String value2) { addCriterion("app not between", value1, value2, "app"); return (Criteria) this; } public Criteria andAppCnameIsNull() { addCriterion("app_cname is null"); return (Criteria) this; } public Criteria andAppCnameIsNotNull() { addCriterion("app_cname is not null"); return (Criteria) this; } public Criteria andAppCnameEqualTo(String value) { addCriterion("app_cname =", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameNotEqualTo(String value) { addCriterion("app_cname <>", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameGreaterThan(String value) { addCriterion("app_cname >", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameGreaterThanOrEqualTo(String value) { addCriterion("app_cname >=", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameLessThan(String value) { addCriterion("app_cname <", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameLessThanOrEqualTo(String value) { addCriterion("app_cname <=", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameLike(String value) { addCriterion("app_cname like", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameNotLike(String value) { addCriterion("app_cname not like", value, "appCname"); return (Criteria) this; } public Criteria andAppCnameIn(List<String> values) { addCriterion("app_cname in", values, "appCname"); return (Criteria) this; } public Criteria andAppCnameNotIn(List<String> values) { addCriterion("app_cname not in", values, "appCname"); return (Criteria) this; } public Criteria andAppCnameBetween(String value1, String value2) { addCriterion("app_cname between", value1, value2, "appCname"); return (Criteria) this; } public Criteria andAppCnameNotBetween(String value1, String value2) { addCriterion("app_cname not between", value1, value2, "appCname"); return (Criteria) this; } public Criteria andBizTypeNameIsNull() { addCriterion("biz_type_name is null"); return (Criteria) this; } public Criteria andBizTypeNameIsNotNull() { addCriterion("biz_type_name is not null"); return (Criteria) this; } public Criteria andBizTypeNameEqualTo(String value) { addCriterion("biz_type_name =", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameNotEqualTo(String value) { addCriterion("biz_type_name <>", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameGreaterThan(String value) { addCriterion("biz_type_name >", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameGreaterThanOrEqualTo(String value) { addCriterion("biz_type_name >=", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameLessThan(String value) { addCriterion("biz_type_name <", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameLessThanOrEqualTo(String value) { addCriterion("biz_type_name <=", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameLike(String value) { addCriterion("biz_type_name like", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameNotLike(String value) { addCriterion("biz_type_name not like", value, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameIn(List<String> values) { addCriterion("biz_type_name in", values, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameNotIn(List<String> values) { addCriterion("biz_type_name not in", values, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameBetween(String value1, String value2) { addCriterion("biz_type_name between", value1, value2, "bizTypeName"); return (Criteria) this; } public Criteria andBizTypeNameNotBetween(String value1, String value2) { addCriterion("biz_type_name not between", value1, value2, "bizTypeName"); return (Criteria) this; } public Criteria andIsDeletedIsNull() { addCriterion("is_deleted is null"); return (Criteria) this; } public Criteria andIsDeletedIsNotNull() { addCriterion("is_deleted is not null"); return (Criteria) this; } public Criteria andIsDeletedEqualTo(String value) { addCriterion("is_deleted =", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedNotEqualTo(String value) { addCriterion("is_deleted <>", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedGreaterThan(String value) { addCriterion("is_deleted >", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedGreaterThanOrEqualTo(String value) { addCriterion("is_deleted >=", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedLessThan(String value) { addCriterion("is_deleted <", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedLessThanOrEqualTo(String value) { addCriterion("is_deleted <=", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedLike(String value) { addCriterion("is_deleted like", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedNotLike(String value) { addCriterion("is_deleted not like", value, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedIn(List<String> values) { addCriterion("is_deleted in", values, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedNotIn(List<String> values) { addCriterion("is_deleted not in", values, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedBetween(String value1, String value2) { addCriterion("is_deleted between", value1, value2, "isDeleted"); return (Criteria) this; } public Criteria andIsDeletedNotBetween(String value1, String value2) { addCriterion("is_deleted not between", value1, value2, "isDeleted"); return (Criteria) this; } public Criteria andGmtCreatedIsNull() { addCriterion("gmt_created is null"); return (Criteria) this; } public Criteria andGmtCreatedIsNotNull() { addCriterion("gmt_created is not null"); return (Criteria) this; } public Criteria andGmtCreatedEqualTo(Date value) { addCriterion("gmt_created =", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedNotEqualTo(Date value) { addCriterion("gmt_created <>", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedGreaterThan(Date value) { addCriterion("gmt_created >", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedGreaterThanOrEqualTo(Date value) { addCriterion("gmt_created >=", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedLessThan(Date value) { addCriterion("gmt_created <", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedLessThanOrEqualTo(Date value) { addCriterion("gmt_created <=", value, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedIn(List<Date> values) { addCriterion("gmt_created in", values, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedNotIn(List<Date> values) { addCriterion("gmt_created not in", values, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedBetween(Date value1, Date value2) { addCriterion("gmt_created between", value1, value2, "gmtCreated"); return (Criteria) this; } public Criteria andGmtCreatedNotBetween(Date value1, Date value2) { addCriterion("gmt_created not between", value1, value2, "gmtCreated"); return (Criteria) this; } public Criteria andGmtModifiedIsNull() { addCriterion("gmt_modified is null"); return (Criteria) this; } public Criteria andGmtModifiedIsNotNull() { addCriterion("gmt_modified is not null"); return (Criteria) this; } public Criteria andGmtModifiedEqualTo(Date value) { addCriterion("gmt_modified =", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotEqualTo(Date value) { addCriterion("gmt_modified <>", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedGreaterThan(Date value) { addCriterion("gmt_modified >", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedGreaterThanOrEqualTo(Date value) { addCriterion("gmt_modified >=", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedLessThan(Date value) { addCriterion("gmt_modified <", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedLessThanOrEqualTo(Date value) { addCriterion("gmt_modified <=", value, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedIn(List<Date> values) { addCriterion("gmt_modified in", values, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotIn(List<Date> values) { addCriterion("gmt_modified not in", values, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedBetween(Date value1, Date value2) { addCriterion("gmt_modified between", value1, value2, "gmtModified"); return (Criteria) this; } public Criteria andGmtModifiedNotBetween(Date value1, Date value2) { addCriterion("gmt_modified not between", value1, value2, "gmtModified"); return (Criteria) this; } public Criteria andCreatorIsNull() { addCriterion("creator is null"); return (Criteria) this; } public Criteria andCreatorIsNotNull() { addCriterion("creator is not null"); return (Criteria) this; } public Criteria andCreatorEqualTo(String value) { addCriterion("creator =", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotEqualTo(String value) { addCriterion("creator <>", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThan(String value) { addCriterion("creator >", value, "creator"); return (Criteria) this; } public Criteria andCreatorGreaterThanOrEqualTo(String value) { addCriterion("creator >=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThan(String value) { addCriterion("creator <", value, "creator"); return (Criteria) this; } public Criteria andCreatorLessThanOrEqualTo(String value) { addCriterion("creator <=", value, "creator"); return (Criteria) this; } public Criteria andCreatorLike(String value) { addCriterion("creator like", value, "creator"); return (Criteria) this; } public Criteria andCreatorNotLike(String value) { addCriterion("creator not like", value, "creator"); return (Criteria) this; } public Criteria andCreatorIn(List<String> values) { addCriterion("creator in", values, "creator"); return (Criteria) this; } public Criteria andCreatorNotIn(List<String> values) { addCriterion("creator not in", values, "creator"); return (Criteria) this; } public Criteria andCreatorBetween(String value1, String value2) { addCriterion("creator between", value1, value2, "creator"); return (Criteria) this; } public Criteria andCreatorNotBetween(String value1, String value2) { addCriterion("creator not between", value1, value2, "creator"); return (Criteria) this; } public Criteria andModifierIsNull() { addCriterion("modifier is null"); return (Criteria) this; } public Criteria andModifierIsNotNull() { addCriterion("modifier is not null"); return (Criteria) this; } public Criteria andModifierEqualTo(String value) { addCriterion("modifier =", value, "modifier"); return (Criteria) this; } public Criteria andModifierNotEqualTo(String value) { addCriterion("modifier <>", value, "modifier"); return (Criteria) this; } public Criteria andModifierGreaterThan(String value) { addCriterion("modifier >", value, "modifier"); return (Criteria) this; } public Criteria andModifierGreaterThanOrEqualTo(String value) { addCriterion("modifier >=", value, "modifier"); return (Criteria) this; } public Criteria andModifierLessThan(String value) { addCriterion("modifier <", value, "modifier"); return (Criteria) this; } public Criteria andModifierLessThanOrEqualTo(String value) { addCriterion("modifier <=", value, "modifier"); return (Criteria) this; } public Criteria andModifierLike(String value) { addCriterion("modifier like", value, "modifier"); return (Criteria) this; } public Criteria andModifierNotLike(String value) { addCriterion("modifier not like", value, "modifier"); return (Criteria) this; } public Criteria andModifierIn(List<String> values) { addCriterion("modifier in", values, "modifier"); return (Criteria) this; } public Criteria andModifierNotIn(List<String> values) { addCriterion("modifier not in", values, "modifier"); return (Criteria) this; } public Criteria andModifierBetween(String value1, String value2) { addCriterion("modifier between", value1, value2, "modifier"); return (Criteria) this; } public Criteria andModifierNotBetween(String value1, String value2) { addCriterion("modifier not between", value1, value2, "modifier"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
33.162762
103
0.565867
2f67a3c1c6573ca11bf6a28f90c1d8dbe02e9eb4
1,329
package com.example.domain.interactor; import com.example.domain.executor.PostExecutionThread; import com.example.domain.executor.ThreadExecutor; import com.example.domain.model.PillDomain; import com.example.domain.repository.UserDataRepository; import javax.inject.Inject; import rx.Observable; import rx.Subscriber; /** * This class is an implementation of {@link UseCase} that represents a use case for * retrieving a collection. */ public class FavoritePillUseCase extends UseCase { private final UserDataRepository userDataRepository; private PillDomain pillDomain; private boolean toFav; @Inject protected FavoritePillUseCase( PillDomain timmer, boolean fav, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread, UserDataRepository userDataRepository ) { super(threadExecutor, postExecutionThread); this.userDataRepository = userDataRepository; this.toFav = fav; this.pillDomain = timmer; } @Override public void execute(Subscriber useCaseSubscriber) { super.execute(useCaseSubscriber); } @Override protected Observable buildUseCaseObservable() { if(toFav) { return this.userDataRepository.addFavoritePill(this.pillDomain); } else { return this.userDataRepository.removeFavoritePill(this.pillDomain); } } }
27.6875
115
0.772009
b845283e031ae4033e20c05f4471f866027a0759
2,354
package com.avereon.xenon.task; import com.avereon.event.Event; import com.avereon.event.EventHandler; import com.avereon.event.EventType; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeoutException; class TaskWatcher implements EventHandler<TaskManagerEvent> { private static final long DEFAULT_WAIT_TIMEOUT = 2000; private List<TaskManagerEvent> events = new CopyOnWriteArrayList<>(); private Map<EventType<? extends Event>, TaskManagerEvent> eventMap = new ConcurrentHashMap<>(); public List<? extends TaskManagerEvent> getEvents() { return new ArrayList<>( events ); } @Override public synchronized void handle( TaskManagerEvent event ) { events.add( event ); eventMap.put( event.getEventType(), event ); notifyAll(); } private void clearEvent( EventType<? extends Event> type ) { eventMap.remove( type ); } public void waitForEvent( EventType<? extends Event> type ) throws InterruptedException, TimeoutException { waitForEvent( type, DEFAULT_WAIT_TIMEOUT ); } @SuppressWarnings( "unused" ) public void waitForNextEvent( EventType<? extends Event> type ) throws InterruptedException, TimeoutException { waitForNextEvent( type, DEFAULT_WAIT_TIMEOUT ); } public synchronized void waitForEvent( EventType<? extends Event> type, long timeout ) throws InterruptedException, TimeoutException { boolean shouldWait = timeout > 0; long start = System.currentTimeMillis(); long duration = 0; while( shouldWait && eventMap.get( type ) == null ) { wait( timeout - duration ); duration = System.currentTimeMillis() - start; shouldWait = duration < timeout; } duration = System.currentTimeMillis() - start; if( duration >= timeout ) throw new TimeoutException( "Timeout waiting for event " + type ); } @SuppressWarnings( "SameParameterValue" ) private synchronized void waitForNextEvent( EventType<? extends Event> type, long timeout ) throws InterruptedException, TimeoutException { clearEvent( type ); waitForEvent( type, timeout ); } @SuppressWarnings( "unused" ) public synchronized void waitForEventCount( int count, int timout ) throws InterruptedException { while( events.size() < count ) { wait( timout ); } } }
31.386667
140
0.753186
900a5e0a3b14c0fba8ba813e9341a89f7f5c4b01
484
package com.themastergeneral.ctdtweaks.items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BasicGlow extends BasicItem { public BasicGlow(String name) { super(name); } @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack par1ItemStack) { par1ItemStack.setTagInfo("ench", new NBTTagList()); return true; } }
25.473684
54
0.760331
59dbc0f857f0190745f70e15a45839c55bffc448
600
/* * Copyright (C) 2016 LinuxTek, Inc All Rights Reserved. */ package com.linuxtek.kona.rest.exception; import com.linuxtek.kona.rest.AbstractRestException; public abstract class ApiException extends AbstractRestException { private static final long serialVersionUID = 1L; public ApiException() { super(); } public ApiException(final String message, final Throwable cause) { super(message, cause); } public ApiException(final String message) { super(message); } public ApiException(final Throwable cause) { super(cause); } }
22.222222
70
0.686667
11321a0589a66207849d79c146ae019f90cd80a9
1,245
package com.mrclbndr.jms_demo.shipping.adpater.messaging.impl; import com.mrclbndr.jms_demo.shipping.adpater.messaging.api.CustomerNotifier; import com.mrclbndr.jms_demo.shipping.domain.ShippingState; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.inject.Inject; import javax.jms.Destination; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Message; @Stateless public class CustomerNotifierImpl implements CustomerNotifier { @Inject private JMSContext jmsContext; @Resource(lookup = "jms/CustomerNotifications") private Destination customerNotifications; @Override public void shippingStateChanged(String orderId, ShippingState updatedShippingState) { try { Message notification = jmsContext.createMessage(); notification.setStringProperty("orderId", orderId); notification.setStringProperty("updatedShippingState", updatedShippingState.name()); jmsContext.createProducer() .setProperty("notificationType", "SHIPPING_STATE_CHANGED") .send(customerNotifications, notification); } catch (JMSException e) { e.printStackTrace(); } } }
34.583333
96
0.730924
4d7f52085c9476bca4e630669700b7de7dce8fdc
3,819
package com.sqisland.android.advanced_textview; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.SimpleAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView footer = (TextView) LayoutInflater.from(this).inflate( android.R.layout.simple_list_item_1, getListView(), false); footer.setText(R.string.about); getListView().addFooterView(footer); final ArrayList<Demo> demos = new ArrayList<Demo>(); demos.add(new Demo(this, AnimatedCompoundDrawableActivity.class, R.string.animated_compound_drawable, R.string.animated_compound_drawable_desc)); demos.add(new Demo(this, ShadowTextActivity.class, R.string.shadow_text, R.string.shadow_text_desc)); demos.add(new Demo(this, CustomFontActivity.class, R.string.custom_font, R.string.custom_font_desc)); demos.add(new Demo(this, GradientTextActivity.class, R.string.gradient_text, R.string.gradient_text_desc)); demos.add(new Demo(this, PatternedTextActivity.class, R.string.patterned_text, R.string.patterned_text_desc)); demos.add(new Demo(this, FromHtmlActivity.class, R.string.from_html, R.string.from_html_desc)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { demos.add(new Demo(this, FractionActivity.class, R.string.fraction, R.string.fraction_desc)); } demos.add(new Demo(this, StyledStringActivity.class, R.string.styled_string, R.string.styled_string_desc)); demos.add(new Demo(this, AlignmentSpanActivity.class, R.string.alignment_span, R.string.alignment_span_desc)); demos.add(new Demo(this, RainbowSpanActivity.class, R.string.rainbow_span, R.string.rainbow_span_desc)); demos.add(new Demo(this, AnimatedRainbowSpanActivity.class, R.string.animated_rainbow_span, R.string.animated_rainbow_span_desc)); demos.add(new Demo(this, ClickableSpanActivity.class, R.string.clickable_span, R.string.clickable_span_desc)); demos.add(new Demo(this, LinedPaperActivity.class, R.string.lined_paper, R.string.lined_paper_desc)); demos.add(new Demo(this, EmojiActivity.class, R.string.emoji, R.string.emoji_desc)); SimpleAdapter adapter = new SimpleAdapter( this, demos, android.R.layout.simple_list_item_2, new String[]{Demo.KEY_TITLE, Demo.KEY_SUBTITLE}, new int[]{android.R.id.text1, android.R.id.text2}); getListView().setAdapter(adapter); getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { if (position < demos.size()) { Demo demo = demos.get(position); startActivity(new Intent(MainActivity.this, demo.activityClass)); } else { startActivity(new Intent(MainActivity.this, AboutActivity.class)); } } }); } public static class Demo extends HashMap<String, String> { public static final String KEY_TITLE = "title"; public static final String KEY_SUBTITLE = "subtitle"; public final Class<?> activityClass; public Demo(Context context, Class<?> activityClass, int titleId, int subtitleId) { this.activityClass = activityClass; put(KEY_TITLE, context.getString(titleId)); put(KEY_SUBTITLE, context.getString(subtitleId)); } } }
39.78125
93
0.724535
e455e960ec7d4f484ad03579daa941bb6e41eeea
1,147
package com.mtm.demo.collection; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class SortingListDemo { public static void main(String args[]) { // Example 1 (Sorting the elements of List that contains string objects) ArrayList<String> aList1 = new ArrayList<String>(); aList1.add("Viru"); aList1.add("Saurav"); aList1.add("Mukesh"); aList1.add("Tahir"); aList1.add("Tahir"); Collections.sort(aList1); Iterator<String> itr1 = aList1.iterator(); while (itr1.hasNext()) { System.out.println(itr1.next()); } // Example 2 (Sorting the elements of List that contains Wrapper class objects) ArrayList<Integer> al = new ArrayList<Integer>(); al.add(Integer.valueOf(201)); al.add(Integer.valueOf(101)); al.add(230);// internally will be converted into objects as Integer.valueOf(230) Collections.sort(al); Iterator<Integer> itr2 = al.iterator(); while (itr2.hasNext()) { System.out.println(itr2.next()); } } }
29.410256
88
0.615519
bd630794647fafe2f82cd15677b3011e7078e33a
504
package io.github.parubok.text.multiline; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Insets; class MultilineUtils { private MultilineUtils() { } static Dimension toDimension(int width, int height, Insets insets) { return new Dimension(width + insets.right + insets.left, height + insets.top + insets.bottom); } static int getHeightIncrement(FontMetrics fm, float lineSpacing) { return Math.round(fm.getHeight() * lineSpacing); } }
26.526316
102
0.712302
6d5b3926fbc74d05d05d957bc1f76c12e0f403a7
6,285
package org.ekstep.genieservices.commons.network; import org.ekstep.genieservices.auth.AuthHandler; import org.ekstep.genieservices.commons.AppContext; import org.ekstep.genieservices.commons.GenieResponseBuilder; import org.ekstep.genieservices.commons.IParams; import org.ekstep.genieservices.commons.bean.GenieResponse; import org.ekstep.genieservices.commons.utils.GsonUtil; import org.ekstep.genieservices.commons.utils.Logger; import org.ekstep.genieservices.commons.utils.StringUtil; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Created on 4/19/2017. * * @author anil */ public abstract class BaseAPI { private static final String GET = "GET"; private static final String POST = "POST"; private static final String PATCH = "PATCH"; private static final int AUTHENTICATION_FAILURE = 401; private AppContext mAppContext; private IHttpClientFactory httpClientFactory; private Map<String, String> headers; private String url; private String TAG; public BaseAPI(AppContext appContext, String url, String TAG) { this.url = url; this.mAppContext = appContext; this.TAG = TAG; this.httpClientFactory = appContext.getHttpClientFactory(); this.headers = new HashMap<>(); // this.headers.put("Accept-Encoding", "gzip"); this.headers.put("X-Channel-Id", mAppContext.getParams().getString(IParams.Key.CHANNEL_ID)); this.headers.put("X-App-Id", mAppContext.getParams().getString(IParams.Key.PRODUCER_ID)); this.headers.put("X-Device-Id", mAppContext.getDeviceInfo().getDeviceID()); } public GenieResponse get() { return fetchFromServer(GET, true); } public GenieResponse post() { return fetchFromServer(POST, true); } public GenieResponse patch() { return fetchFromServer(PATCH, true); } protected void processAuthFailure(ApiResponse apiResponse) { AuthHandler.resetAuthToken(mAppContext); } private GenieResponse fetchFromServer(String requestType, boolean retryForAuthError) { if (!mAppContext.getConnectionInfo().isConnected()) { return getErrorResponse(NetworkConstants.CONNECTION_ERROR, NetworkConstants.CONNECTION_ERROR_MESSAGE); } try { ApiResponse apiResponse = invokeApi(requestType); if (apiResponse.isSuccessful()) { return getSuccessResponse(apiResponse.getResponseBody()); } else if (apiResponse.getResponseCode() == AUTHENTICATION_FAILURE) { if (retryForAuthError) { processAuthFailure(apiResponse); return fetchFromServer(requestType, false); } else { String error = NetworkConstants.SERVERAUTH_ERROR; String errorMsg = NetworkConstants.SERVERAUTH_ERROR_MESSAGE; if (!StringUtil.isNullOrEmpty(apiResponse.getResponseBody())) { errorMsg = apiResponse.getResponseBody(); } return getErrorResponse(error, errorMsg); } } else { String error = NetworkConstants.SERVER_ERROR; String errorMsg = NetworkConstants.SERVER_ERROR_MESSAGE; if (!StringUtil.isNullOrEmpty(apiResponse.getResponseBody())) { try { Map<String, Object> errorResponseBodyMap = GsonUtil.fromJson(apiResponse.getResponseBody(), Map.class); if (errorResponseBodyMap != null && !errorResponseBodyMap.isEmpty() && errorResponseBodyMap.containsKey("params")) { Map<String, Object> params = (Map<String, Object>) errorResponseBodyMap.get("params"); error = (String) params.get("err"); errorMsg = (String) params.get("errmsg"); } } catch (Exception e) { e.printStackTrace(); } } return getErrorResponse(error, errorMsg); } } catch (IOException e) { Logger.e(TAG, e.getMessage()); return getErrorResponse(NetworkConstants.NETWORK_ERROR, e.getMessage()); } } private ApiResponse invokeApi(String requestType) throws IOException { IHttpClient httpClient = prepareClient(); ApiResponse apiResponse = null; if (GET.equals(requestType)) { apiResponse = httpClient.doGet(); } else if (POST.equals(requestType)) { apiResponse = httpClient.doPost(getRequestBody()); } else if (PATCH.equals(requestType)) { apiResponse = httpClient.doPatch(getRequestBody()); } return apiResponse; } private IHttpClient prepareClient() { IHttpClient httpClient = httpClientFactory.getClient(); httpClient.createRequest(url); if (shouldAuthenticate()) { IHttpAuthenticator authenticator = httpClientFactory.getHttpAuthenticator(); httpClient.setHeaders(authenticator.getAuthHeaders()); } httpClient.setHeaders(headers); httpClient.setHeaders(getRequestHeaders()); return httpClient; } private GenieResponse<String> getSuccessResponse(String responseBody) { GenieResponse<String> response = GenieResponseBuilder.getSuccessResponse("", String.class); response.setResult(responseBody); return response; } private GenieResponse<String> getErrorResponse(String error, String errorMessage) { return GenieResponseBuilder.getErrorResponse(error, errorMessage, TAG, String.class); } protected IRequestBody getRequestBody() { IRequestBody requestBody = new ByteArrayRequestBody(); requestBody.setBody(getRequestData()); return requestBody; } protected boolean shouldAuthenticate() { return true; } protected abstract Map<String, String> getRequestHeaders(); protected byte[] getRequestData() { return createRequestData().getBytes(); } protected abstract String createRequestData(); }
38.558282
127
0.642959
86530db5c7e52a852d6604fb5e0afd7091ab6b12
5,093
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|segment package|; end_package begin_import import|import static name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|commons operator|. name|FixturesHelper operator|. name|Fixture operator|. name|SEGMENT_TAR import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|commons operator|. name|FixturesHelper operator|. name|getFixtures import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assume operator|. name|assumeTrue import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Strings import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|blob operator|. name|cloud operator|. name|azure operator|. name|blobstorage operator|. name|AzureConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|blob operator|. name|cloud operator|. name|azure operator|. name|blobstorage operator|. name|AzureDataStoreUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|blob operator|. name|datastore operator|. name|DataStoreBlobStore import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Properties import|; end_import begin_comment comment|/** * Tests for SegmentNodeStore on AzureDataStore GC */ end_comment begin_class specifier|public class|class name|SegmentAzureDataStoreBlobGCIT extends|extends name|SegmentDataStoreBlobGCIT block|{ specifier|protected name|String name|containerName decl_stmt|; annotation|@ name|BeforeClass specifier|public specifier|static name|void name|assumptions parameter_list|() block|{ name|assumeTrue argument_list|( name|getFixtures argument_list|() operator|. name|contains argument_list|( name|SEGMENT_TAR argument_list|) argument_list|) expr_stmt|; name|assumeTrue argument_list|( name|AzureDataStoreUtils operator|. name|isAzureConfigured argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|protected name|DataStoreBlobStore name|getBlobStore parameter_list|( name|File name|rootFolder parameter_list|) throws|throws name|Exception block|{ name|Properties name|props init|= name|AzureDataStoreUtils operator|. name|getAzureConfig argument_list|() decl_stmt|; name|containerName operator|= name|rootFolder operator|. name|getName argument_list|() expr_stmt|; name|props operator|. name|setProperty argument_list|( name|AzureConstants operator|. name|AZURE_BLOB_CONTAINER_NAME argument_list|, name|containerName argument_list|) expr_stmt|; name|props operator|. name|setProperty argument_list|( literal|"cacheSize" argument_list|, literal|"0" argument_list|) expr_stmt|; return|return operator|new name|DataStoreBlobStore argument_list|( name|AzureDataStoreUtils operator|. name|getAzureDataStore argument_list|( name|props argument_list|, name|rootFolder operator|. name|getAbsolutePath argument_list|() argument_list|) argument_list|) return|; block|} annotation|@ name|After specifier|public name|void name|close parameter_list|() throws|throws name|Exception block|{ if|if condition|( operator|! name|Strings operator|. name|isNullOrEmpty argument_list|( name|containerName argument_list|) condition|) block|{ name|AzureDataStoreUtils operator|. name|deleteContainer argument_list|( name|containerName argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
15.433333
815
0.806401
f51e9680ef9f229024e096d5b7b7daed076c63bc
2,773
package eu.qualimaster.adaptation.platform; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import eu.qualimaster.adaptation.AdaptationConfiguration; import eu.qualimaster.adaptation.external.ClientEndpoint; import eu.qualimaster.adaptation.external.DispatcherAdapter; import eu.qualimaster.adaptation.external.LoggingFilterRequest; import eu.qualimaster.adaptation.external.LoggingMessage; /** * A simple event client for QM specific logging. * * @author Holger Eichelberger */ public class LogClient extends DispatcherAdapter { private static List<String> filterRegEx = new ArrayList<String>(); /** * Listens to events. * * @param args the log filtering regular expressions * @throws IOException in cases of problems */ public static void main(String[] args) throws IOException { if (0 == args.length) { System.out.println("At least on logging filtering regular expression must be given. Terminating."); System.exit(0); } for (String s : args) { try { Pattern.compile(s); filterRegEx.add(s); } catch (PatternSyntaxException e) { System.out.println("Filter regEx syntax: " + e.getMessage()); } } if (filterRegEx.isEmpty()) { System.out.println("No valid filter regEx given. Terminating."); System.exit(0); } Cli.configure(); InetAddress addr = InetAddress.getByName(AdaptationConfiguration.getEventHost()); final ClientEndpoint endpoint = new ClientEndpoint(new LogClient(), addr, AdaptationConfiguration.getAdaptationPort()); endpoint.schedule(new LoggingFilterRequest(filterRegEx, null)); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if (null != endpoint) { endpoint.schedule(new LoggingFilterRequest(null, filterRegEx)); while (endpoint.hasWork()) { try { Thread.sleep(200); } catch (InterruptedException e) { } } endpoint.stop(); } } })); } @Override public void handleLoggingMessage(LoggingMessage msg) { System.out.println(msg.getLevel() + "[" + msg.getThreadName() + "]" + msg.getMessage()); } }
35.101266
112
0.584565
16a0e6c36b5185e2af9eb3c953fcd63d506b7f0a
3,553
/* * Copyright (C) 2008-2017 Matt Gumbley, DevZendo.org http://devzendo.org * * 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.devzendo.commoncode.network; import org.devzendo.commoncode.concurrency.ThreadUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.net.NetworkInterface; import java.util.Arrays; import java.util.List; import static java.util.Collections.list; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.devzendo.commoncode.network.NetworkInterfaceFixture.ethernet; import static org.devzendo.commoncode.network.NetworkInterfaceFixture.local; public class TestCountingInterfaceSupplier { private final NetworkInterface localUp = local(true); private final NetworkInterface ethernetDown = ethernet(false); private final List<NetworkInterface> justLocalUp = singletonList(localUp); private final List<NetworkInterface> bothInterfaces = Arrays.asList(localUp, ethernetDown); private final CountingInterfaceSupplier cis = new CountingInterfaceSupplier(justLocalUp, bothInterfaces); private final Thread waitForExhaustionThread = new Thread(cis::waitForDataExhaustion); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void noCallsAtFirst() { assertThat(cis.numberOfTimesCalled()).isZero(); } @Test public void givesYouTheConstructorSupplies() { assertThat(list(cis.get())).contains(localUp); assertThat(cis.numberOfTimesCalled()).isEqualTo(1); assertThat(list(cis.get())).contains(localUp, ethernetDown); assertThat(cis.numberOfTimesCalled()).isEqualTo(2); } @Test public void calledMoreFrequentlyThanYouHaveDataForCausesThrow() { thrown.expect(IllegalStateException.class); thrown.expectMessage("Interface supplier called more frequently than expected"); cis.get(); cis.get(); cis.get(); // boom } @Test(timeout = 2000) public void waitForExhaustionWaitsIfNotExhausted() { waitForExhaustionThread.start(); ThreadUtils.waitNoInterruption(250); final Thread.State state = waitForExhaustionThread.getState(); try { assertThat(state).isEqualTo(Thread.State.WAITING); } finally { waitForExhaustionThread.interrupt(); } } @Test(timeout = 2000) public void waitForExhaustionReturnsIfExhausted() { waitForExhaustionThread.start(); cis.get(); cis.get(); ThreadUtils.waitNoInterruption(250); final Thread.State state = waitForExhaustionThread.getState(); try { assertThat(state).isEqualTo(Thread.State.TERMINATED); } finally { waitForExhaustionThread.interrupt(); } } }
32.898148
109
0.722488
14338ddd5b48ddd1a8e4451ca65ce3ba301c77d4
740
package hu.fallen.countitbaby.helpers; import java.util.Random; import hu.fallen.countitbaby.model.Settings; public class RandomHelper { // TODO [Postponed] Scale up/down images based on count - maybe introduce scaled-up drawables to avoid programatical scaling? private static final String TAG = RandomHelper.class.getCanonicalName(); private static final Random RANDOM = new Random(); public static int intBetween(int min, int max) { return RANDOM.nextInt(max - min + 1) + min; } public static int generateSolution() { return intBetween(Settings.instance().min(), Settings.instance().max()); } public static int getRandom(int bound) { return RANDOM.nextInt(bound); } }
27.407407
129
0.702703
95d36175a3e660a092f425a2e784079362ae608b
2,440
package app.controllers; import app.data.CoreDBImpl; import app.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.UUID; @RestController @RequestMapping(path = "api/user") public class UserController { String tableName = "user"; @Autowired private CoreDBImpl<User> userHeadDB; @GetMapping public ResponseEntity<List<User>> getAll() { List<User> result = userHeadDB.getAll(tableName); return (result != null && !result.isEmpty()) ? ResponseEntity.ok(result) : ResponseEntity.notFound().build(); } @GetMapping(path = "/{userId}") public ResponseEntity<User> getUser(@PathVariable(value = "userId") UUID userId) { User user = userHeadDB.getById(tableName ,userId); if (user == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(user); } @PostMapping public ResponseEntity<User> createUser(@RequestBody User user) { return isFilled(user) ? ResponseEntity.ok(userHeadDB.create(tableName, user)) : ResponseEntity.notFound().build(); } @PutMapping public ResponseEntity<User> changeUser(@RequestBody User user) { User res = userHeadDB.change(tableName, user); return (isFilled(user) && res != null) ? ResponseEntity.ok(res) : ResponseEntity.notFound().build(); } @DeleteMapping public ResponseEntity<User> deleteUser(@RequestBody User user) { return userHeadDB.delete(tableName, user) ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); } @GetMapping(path = "search") public ResponseEntity<List<User>> searchUser(@RequestParam("inText") String inText) { List<User> userList = userHeadDB.searchAll(tableName, inText); if (userList == null || userList.isEmpty()) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(userList); } public boolean isFilled(User user) { return user != null && user.getName() != null && !user.getName().equals("") && user.getSurname() != null && !user.getSurname().equals(""); } }
30.5
89
0.629918