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
c986b25a9c291980632bef6a3388bfa36605ebb3
4,473
package com.chobocho.minesweeper; import java.util.ArrayList; public class MineSweeperImpl implements MineSweeper, MineSweeperNotifyCallback { private ArrayList<GameObserver> observers; private int boardWidth; private int boardHeight; private int boomCount; private int play_time = 0; private int toolType = 0; Board board; State gameState; State idleState; State playState; State pauseState; State gameOverState; State winState; public MineSweeperImpl(int boardWidth, int boardHeight, int boomCount) { this.boardWidth = boardWidth; this.boardHeight = boardHeight; this.boomCount = boomCount; init(); } public void setBoardInfo(int boardWidth, int boardHeight, int boomCount) { this.boardWidth = boardWidth; this.boardHeight = boardHeight; this.boomCount = boomCount; this.board.setBoardInfo(boardWidth, boardHeight, boomCount); } public void init() { observers = new ArrayList<>(); board = new BoardImpl(boardWidth, boardHeight, boomCount); idleState = new IdleState(); playState = new PlayState(this, board); pauseState = new PauseState(); gameOverState = new GameOverState(); winState = new WinState(); gameState = idleState; play_time = 0; toolType = MineSweeper.FLAG; } private void initGame() { play_time = 0; toolType = MineSweeper.BOOM; board.init(); } public void register(GameObserver gameObserver) { observers.add(gameObserver); gameObserver.Notify(gameState.getState()); } private synchronized void Notify() { for (GameObserver observer:observers) { observer.Notify(gameState.getState()); } } @Override public void open(int x, int y) { gameState.open(x, y); } @Override public void setFlag(int x, int y) { gameState.setFlag(x, y); } @Override public void tick() { play_time++; if (play_time >= 5999) { play_time = 5999; setGameOverState(); } } @Override public int getPlaytime() { return play_time; } public void idle() { gameState = idleState; initGame(); Notify(); } public void play() { gameState = playState; Notify(); } public void pause() { gameState = pauseState; Notify(); } @Override public void setWinState() { gameState = winState; Notify(); } @Override public void setGameOverState() { gameState = gameOverState; Notify(); } @Override public int getUnusedFlagCount() { return board.getUnusedFlagCount(); } @Override public int[][] getBoard() { return board.getBoard(); } @Override public boolean isPlayState() { return gameState == playState; } @Override public void toggleTool() { if (toolType == MineSweeper.FLAG) { toolType = MineSweeper.BOOM; } else { toolType = MineSweeper.FLAG; } } @Override public int getToolType() { return toolType; } @Override public GameInfo getGameInfo() { GameInfo gameInfo = new GameInfo(this.boardWidth, this.boardHeight); if (isPlayState()) { return gameInfo; } gameInfo.setGameSate(gameState.getState()); gameInfo.setPlayTime(this.play_time); this.board.getGameState(gameInfo); return gameInfo; } @Override public void setGameInfo(GameInfo gameInfo) { play_time = gameInfo.getPlayTime(); switch (gameInfo.getGameState()) { case GameObserver.IDLE: idle(); break; case GameObserver.PLAY: // Nothing to do break; case GameObserver.PAUSE: board.setGameState(gameInfo); pause(); break; case GameObserver.GAME_OVER: board.setGameState(gameInfo); setGameOverState(); break; case GameObserver.WIN: board.setGameState(gameInfo); setWinState(); break; default: break; } } }
23.666667
80
0.567404
326e4f7e4cdc400dd4de8d948995adc5be6acb38
24,185
/* * Copyright 2015 Max Schuster. * * 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 eu.maxschuster.vaadin.autocompletetextfield; import com.vaadin.annotations.JavaScript; import com.vaadin.annotations.StyleSheet; import com.vaadin.server.AbstractJavaScriptExtension; import com.vaadin.server.JsonCodec; import com.vaadin.server.Resource; import com.vaadin.shared.Registration; import com.vaadin.ui.AbstractTextField; import com.vaadin.ui.JavaScriptFunction; import elemental.json.Json; import elemental.json.JsonArray; import elemental.json.JsonObject; import elemental.json.JsonValue; import eu.maxschuster.vaadin.autocompletetextfield.shared.AutocompleteTextFieldExtensionState; import eu.maxschuster.vaadin.autocompletetextfield.shared.ScrollBehavior; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; /** * Extends an {@link AbstractTextField} with autocomplete (aka word completion) * functionality. * <p> * Uses a modified version of * <a href="https://goodies.pixabay.com/javascript/auto-complete/demo.html"> * autoComplete</a> originally developed by * <a href="https://pixabay.com/users/Simon/">Simon Steinberger</a> * </p> * <p> * {@code autoComplete} is released under the MIT License. * </p> * * @author Max Schuster * @see <a href="https://github.com/Pixabay/JavaScript-autoComplete"> * https://github.com/Pixabay/JavaScript-autoComplete</a> * @see <a href="https://github.com/maxschuster/JavaScript-autoComplete"> * https://github.com/maxschuster/JavaScript-autoComplete</a> */ @JavaScript({ "vaadin://addons/autocompletetextfield/dist/AutocompleteTextFieldExtension.min.js" }) @StyleSheet({ "vaadin://addons/autocompletetextfield/dist/AutocompleteTextFieldExtension.css" }) public class AutocompleteTextFieldExtension extends AbstractJavaScriptExtension implements AutocompleteEvents.SelectNotifier { private static final long serialVersionUID = 3L; /** * An object that keeps track of all visible suggestions. */ private final AutocompleteSuggestionTracker suggestionTracker = new AutocompleteSuggestionTracker(); /** * The max amount of suggestions send to the client-side. */ private int suggestionLimit = 0; /** * The suggestion provider queried for suggestions. */ protected AutocompleteSuggestionProvider suggestionProvider = null; /** * Construct a new {@link AutocompleteTextFieldExtension}. */ public AutocompleteTextFieldExtension() { this(null); } /** * Construct a new {@link AutocompleteTextFieldExtension} and extends the * given {@link AbstractTextField}. * * @param target The textfield to extend. */ public AutocompleteTextFieldExtension(AbstractTextField target) { addFunctions(); if (target != null) { extend(target); } } /** * Extends the given textfield. * * @param target The textfield to extend. */ public void extend(AbstractTextField target) { super.extend(target); } @Override public AbstractTextField getParent() { return (AbstractTextField) super.getParent(); } @Override protected Class<? extends AbstractTextField> getSupportedParentType() { return AbstractTextField.class; } @Override protected AutocompleteTextFieldExtensionState getState() { return (AutocompleteTextFieldExtensionState) super.getState(); } @Override protected AutocompleteTextFieldExtensionState getState(boolean markAsDirty) { return (AutocompleteTextFieldExtensionState) super.getState(markAsDirty); } @Override public Class<? extends AutocompleteTextFieldExtensionState> getStateType() { return AutocompleteTextFieldExtensionState.class; } /** * Adds all {@link JavaScriptFunction}s */ private void addFunctions() { addFunction("serverQuerySuggestions", this::jsQuerySuggestions); addFunction("serverOnSelect", this::jsOnSelect); addFunction("serverOnCloseSuggestionContainer", this::jsOnCloseSuggestionContainer); } /** * Receives a search term from the client-side, executes the query and sends * the results to the JavaScript method "setSuggestions". * * <p> * <b>Parameters:</b> * <ul> * <li>{@link JsonValue} {@code requestId} - Request id to send back to the * client-side.</li> * <li>{@link String} {@code term} - The search term.</li> * </ul> * * @param arguments Parameters from the client-side. */ private void jsQuerySuggestions(JsonArray arguments) { JsonValue requestId = arguments.get(0); String term = arguments.getString(1); Set<AutocompleteSuggestion> suggestions = querySuggestions(term); JsonValue suggestionsAsJson = suggestionsToJson(suggestions); callFunction("setSuggestions", requestId, suggestionsAsJson); }; /** * Called when the user selects a suggestion. * * <p> * <b>Parameters:</b> * <ul> * <li>{@link String} {@code key} - The suggestion key.</li> * </ul> * * @param arguments Parameters from the client-side. */ private void jsOnSelect(JsonArray arguments) { if (!hasListeners(AutocompleteEvents.SelectEvent.class)) { return; // ignore call } String key = arguments.getString(0); try { fireSelectEvent(key); } catch (NoSuchElementException ex) { Logger.getLogger(AutocompleteTextFieldExtension.class.getName()) .log(Level.SEVERE, "Missing suggestion key '{0}'", key); } } /** * Called when hiding the suggestion container. * * @param arguments Parameters from the client-side. */ private void jsOnCloseSuggestionContainer(JsonArray arguments) { suggestionTracker.clear(); } /** * Creates an {@link AutocompleteQuery} from the given search term and the * internal {@link #suggestionLimit} and executes it. * * Returns a {@link Set} of {@link AutocompleteSuggestion}s with a * predictable iteration order. * * @param term The search term. * @return Result {@link Set} of {@link AutocompleteSuggestion}s with a * predictable iteration order. */ protected Set<AutocompleteSuggestion> querySuggestions(String term) { AutocompleteQuery autocompleteQuery = new AutocompleteQuery(this, term, suggestionLimit); return querySuggestions(autocompleteQuery); } /** * Executes the given {@link AutocompleteQuery} and makes sure the result is * within the boundries of the {@link AutocompleteQuery}'s limit. * <p> * Returns a {@link Set} of {@link AutocompleteSuggestion}s with a * predictable iteration order. * </p> * * @param query The Query. * @return Result {@link Set} of {@link AutocompleteSuggestion}s with a * predictable iteration order. */ protected Set<AutocompleteSuggestion> querySuggestions(AutocompleteQuery query) { if (suggestionProvider == null) { // no suggestionProvider set return Collections.emptySet(); } Collection<AutocompleteSuggestion> suggestions = suggestionProvider.querySuggestions(query); if (suggestions == null) { // suggestionProvider has returned null return Collections.emptySet(); } int limit = query.getLimit(); if (limit > 0 && limit < suggestions.size()) { // suggestionProvider has returned more results than allowed Set<AutocompleteSuggestion> subSet = new LinkedHashSet<>(limit); for (AutocompleteSuggestion suggestion : suggestions) { subSet.add(suggestion); if (subSet.size() >= limit) { // size has reached the limit, ignore the following results // TODO: Should we log a message here? break; } } return subSet; } else { // suggestionProvider has respected the query limit return new LinkedHashSet<>(suggestions); } } /** * Converts the given {@link AutocompleteSuggestion} into a * {@link JsonValue} representation because {@link JsonCodec} can't handle * it itself. * * @param suggestions Suggestions. * @return {@link JsonValue} representation. */ protected JsonValue suggestionsToJson(Set<AutocompleteSuggestion> suggestions) { final boolean hasSelectListeners = hasListeners(AutocompleteEvents.SelectEvent.class); suggestionTracker.clear(); JsonArray array = Json.createArray(); int i = 0; for (AutocompleteSuggestion suggestion : suggestions) { JsonObject object = Json.createObject(); // only track suggestion if someone is listening for select events. if (hasSelectListeners) { String key = suggestionTracker.addSuggestion(suggestion); object.put("key", key); } String value = suggestion.getValue(); String description = suggestion.getDescription(); Resource icon = suggestion.getIcon(); List<String> styleNames = suggestion.getStyleNames(); object.put("value", value != null ? Json.create(value) : Json.createNull()); object.put("description", description != null ? Json.create(description) : Json.createNull()); if (icon != null) { String resourceKey = "icon-" + i; setResource(resourceKey, icon); object.put("icon", resourceKey); } else { object.put("icon", Json.createNull()); } if (styleNames != null) { JsonArray styleNamesArray = Json.createArray(); int s = 0; for (String styleName : styleNames) { if (styleName == null) { continue; } styleNamesArray.set(s++, styleName); } object.put("styleNames", styleNamesArray); } else { object.put("styleNames", Json.createNull()); } array.set(i++, object); } return array; } /** * Gets the active {@link AutocompleteSuggestionProvider}. * * @return The active {@link AutocompleteSuggestionProvider}. */ public AutocompleteSuggestionProvider getSuggestionProvider() { return suggestionProvider; } /** * Sets the active {@link AutocompleteSuggestionProvider}. * * @param suggestionProvider The active * {@link AutocompleteSuggestionProvider}. */ public void setSuggestionProvider(AutocompleteSuggestionProvider suggestionProvider) { this.suggestionProvider = suggestionProvider; } /** * Sets the active {@link AutocompleteSuggestionProvider}. * * @param suggestionProvider The active * {@link AutocompleteSuggestionProvider}. * @return this (for method chaining) * @see * #setSuggestionProvider(eu.maxschuster.vaadin.autocompletetextfield.AutocompleteSuggestionProvider) */ public AutocompleteTextFieldExtension withSuggestionProvider(AutocompleteSuggestionProvider suggestionProvider) { setSuggestionProvider(suggestionProvider); return this; } /** * Gets the maximum number of suggestions that are allowed. * <p> * If the active {@link AutocompleteSuggestionProvider} returns more * suggestions than allowed, the excess suggestions will be ignored! * </p> * <p> * If {@code limit <= 0} the suggestions won't be limited. * </p> * * @return Maximum number of suggestions. */ public int getSuggestionLimit() { return suggestionLimit; } /** * Sets the maximum number of suggestions that are allowed. * <p> * If the active {@link AutocompleteSuggestionProvider} returns more * suggestions than allowed, the excess suggestions will be ignored! * </p> * <p> * If limit &lt;= 0 the suggestions won't be limited. * </p> * * @param suggestionLimit Maximum number of suggestions. */ public void setSuggestionLimit(int suggestionLimit) { this.suggestionLimit = suggestionLimit; } /** * Sets the maximum number of suggestions that are allowed. * <p> * If the active {@link AutocompleteSuggestionProvider} returns more * suggestions than allowed, the excess suggestions will be ignored! * </p> * <p> * If limit &lt;= 0 the suggestions won't be limited. * </p> * * @param suggestionLimit Maximum number of suggestions. * @return this (for method chaining) * @see #setSuggestionLimit(int) */ public AutocompleteTextFieldExtension withSuggestionLimit(int suggestionLimit) { setSuggestionLimit(suggestionLimit); return this; } /** * Checks whether items are rendered as HTML. * <p> * The default is false, i.e. to render that caption as plain text. * </p> * * @return true if the captions are rendered as HTML, false if rendered as * plain text. */ public boolean isItemAsHtml() { return getState(false).itemAsHtml; } /** * Sets whether the items are rendered as HTML. * <p> * If set to true, the items are rendered in the browser as HTML and the * developer is responsible for ensuring no harmful HTML is used. If set to * false, the caption is rendered in the browser as plain text. * </p> * <p> * The default is false, i.e. to render that caption as plain text. * </p> * * @param itemAsHtml true if the items are rendered as HTML, false if * rendered as plain text. */ public void setItemAsHtml(boolean itemAsHtml) { getState().itemAsHtml = itemAsHtml; } /** * Sets whether the items are rendered as HTML. * <p> * If set to true, the items are rendered in the browser as HTML and the * developer is responsible for ensuring no harmful HTML is used. If set to * false, the caption is rendered in the browser as plain text. * </p> * <p> * The default is false, i.e. to render that caption as plain text. * </p> * * @param itemAsHtml true if the items are rendered as HTML, false if * rendered as plain text. * @return this (for method chaining) * @see #setItemAsHtml(boolean) */ public AutocompleteTextFieldExtension withItemAsHtml(boolean itemAsHtml) { setItemAsHtml(itemAsHtml); return this; } /** * Gets the minimum number of characters (&gt;=1) a user must type before a * search is performed. * * @return Minimum number of characters. */ public int getMinChars() { return getState(false).minChars; } /** * Sets the minimum number of characters (&gt;=1) a user must type before a * search is performed. * * @param minChars Minimum number of characters. */ public void setMinChars(int minChars) { getState().minChars = minChars; } /** * Sets the minimum number of characters (&gt;=1) a user must type before a * search is performed. * * @param minChars Minimum number of characters. * @return this (for method chaining) * @see #setMinChars(int) */ public AutocompleteTextFieldExtension withMinChars(int minChars) { getState().minChars = minChars; return this; } /** * Gets the delay in milliseconds between when a keystroke occurs and when a * search is performed. A zero-delay is more responsive, but can produce a * lot of load. * * @return Search delay in milliseconds. */ public int getDelay() { return getState(false).delay; } /** * Sets the delay in milliseconds between when a keystroke occurs and when a * search is performed. A zero-delay is more responsive, but can produce a * lot of load. * * @param delay Search delay in milliseconds. */ public void setDelay(int delay) { getState().delay = delay; } /** * Sets the delay in milliseconds between when a keystroke occurs and when a * search is performed. A zero-delay is more responsive, but can produce a * lot of load. * * @param delay Search delay in milliseconds. * @return this (for method chaining) * @see #setDelay(int) */ public AutocompleteTextFieldExtension withDelay(int delay) { setDelay(delay); return this; } /** * Gets all user-defined CSS style names of the dropdown menu container. If * the component has multiple style names defined, the return string is a * space-separated list of style names. * * @return The style name or a space-separated list of user-defined style * names of the dropdown menu container. */ public String getMenuStyleName() { List<String> styleNames = getState(false).menuStyleNames; String styleName = ""; if (styleNames != null && !styleNames.isEmpty()) { Iterator<String> i = styleNames.iterator(); while (i.hasNext()) { styleName += i.next(); if (i.hasNext()) { styleName += " "; } } } return styleName; } /** * Adds one or more style names to the dropdown menu container. Multiple * styles can be specified as a space-separated list of style names. The * style name will be rendered as a HTML class name, which can be used in a * CSS definition. * * @param styleName The new style to be added to the dropdown menu * container. */ public void addMenuStyleName(String styleName) { List<String> styleNames = getState().menuStyleNames; if (styleName == null || styleName.isEmpty()) { return; } if (styleName.contains(" ")) { StringTokenizer tokenizer = new StringTokenizer(styleName, " "); while (tokenizer.hasMoreTokens()) { addMenuStyleName(tokenizer.nextToken()); } return; } if (styleNames == null) { styleNames = new ArrayList<>(); getState().menuStyleNames = styleNames; } styleNames.add(styleName); } /** * Adds one or more style names to the dropdown menu container. Multiple * styles can be specified as a space-separated list of style names. The * style name will be rendered as a HTML class name, which can be used in a * CSS definition. * * @param styleNames The new styles to be added to the dropdown menu * container. * @return this (for method chaining) * @see #addMenuStyleName(java.lang.String) */ public AutocompleteTextFieldExtension withMenuStyleName(String... styleNames) { for (String styleName : styleNames) { addMenuStyleName(styleName); } return this; } /** * Removes one or more style names from the dropdown menu container. * Multiple styles can be specified as a space-separated list of style * names. * * @param styleName The style name or style names to be removed. */ public void removeMenuStyleName(String styleName) { List<String> styleNames = getState().menuStyleNames; if (styleName == null || styleName.isEmpty() || styleNames == null) { return; } if (styleName.contains(" ")) { StringTokenizer tokenizer = new StringTokenizer(styleName, " "); while (tokenizer.hasMoreTokens()) { styleNames.remove(tokenizer.nextToken()); } } else { styleNames.remove(styleName); } } /** * Gets the {@link ScrollBehavior} that is used when the user scrolls the * page while the suggestion box is open. * * @return The {@link ScrollBehavior}. */ public ScrollBehavior getScrollBehavior() { return getState(false).scrollBehavior; } /** * Sets the {@link ScrollBehavior} that is used when the user scrolls the * page while the suggestion box is open. * * @param scrollBehavior The {@link ScrollBehavior}. */ public void setScrollBehavior(ScrollBehavior scrollBehavior) { getState().scrollBehavior = scrollBehavior; } /** * Sets the {@link ScrollBehavior} that is used when the user scrolls the * page while the suggestion box is open. * * @param scrollBehavior The {@link ScrollBehavior}. * @return this (for method chaining) * @see * #setScrollBehavior(eu.maxschuster.vaadin.autocompletetextfield.shared.ScrollBehavior) */ public AutocompleteTextFieldExtension withScrollBehavior(ScrollBehavior scrollBehavior) { setScrollBehavior(scrollBehavior); return this; } /** * Gets if the fields type is {@code "search"}. * * @return {@code true} the fields type is {@code "search"}. */ public boolean isTypeSearch() { return getState(false).typeSearch; } /** * Sets if the fields type is {@code "search"}. * * @param typeSearch {@code true} will change this fields type to * {@code "search"}. */ public void setTypeSearch(boolean typeSearch) { getState().typeSearch = typeSearch; } /** * Sets if the fields type is {@code "search"}. * * @param typeSearch {@code true} will change this fields type to * {@code "search"}. * @return this (for method chaining) * @see #setTypeSearch(boolean) */ public AutocompleteTextFieldExtension withSearch(boolean typeSearch) { setTypeSearch(typeSearch); return this; } protected void fireSelectEvent(String key) throws NoSuchElementException { fireSelectEvent(suggestionTracker.getSuggestion(key).orElseThrow(() -> new NoSuchElementException("Suggestion key '" + key + "' does not exist!"))); } protected void fireSelectEvent(AutocompleteSuggestion suggestion) { fireEvent(new AutocompleteEvents.SelectEvent(getParent(), suggestion)); } @Override public Registration addSelectListener(AutocompleteEvents.SelectListener listener) { return addListener(AutocompleteEvents.SelectEvent.EVENT_ID, AutocompleteEvents.SelectEvent.class, listener, AutocompleteEvents.SelectListener.METHOD); } @Override public AutocompleteEvents.SelectNotifier withSelectListener(AutocompleteEvents.SelectListener listener) { addSelectListener(listener); return this; } }
33.920056
117
0.634691
f1ea5ac5521014112ba21ce742118e26410ffb8d
693
package com.nexidia.main; import com.nexidia.helper.InputFileHelper; /** * Nexidia Coding Test * 1. Take path to a file as a commandline argument that contains one integer per line. * 2. For each integer in the file, output console a comma-delimited list of integer's prime factors. * The list of integers on each line should multiply to the result of input integer * 3. Include unit tests for the code. */ public class CodingTestMain { /** * Main method, InputFileHelper class is instantiated. * @param args */ public static void main(String[] args) { InputFileHelper input = new InputFileHelper(); input.processInputFile(args); } }
27.72
101
0.698413
cb748d007486b895b6a0bc9e5c66f0d978ce8584
2,171
package urv.olsr.mcast; import org.jgroups.Address; import org.jgroups.stack.IpAddress; import org.jgroups.util.Streamable; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; /** * Class that represents a multicast address of a group * * @author Gerard Paris Aixala * */ public class MulticastAddress implements Serializable,Streamable,Externalizable{ // CLASS FIELDS -- private InetAddress mcastAddress; // CONSTRUCTORS -- public MulticastAddress(){} // OVERRIDDEN METHODS -- public Object clone(){ MulticastAddress newAddr = new MulticastAddress(); newAddr.setValue(this.mcastAddress); return newAddr; } public boolean equals(Object obj){ MulticastAddress addr = (MulticastAddress)obj; return mcastAddress.equals(addr.mcastAddress); } public int hashCode(){ return mcastAddress.hashCode(); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { byte[] b = new byte[4]; in.read(b, 0, 4); this.mcastAddress=InetAddress.getByAddress(b); } public void readFrom(DataInput in) throws IOException, IllegalAccessException, InstantiationException { byte[] a = new byte[4]; // 4 bytes (IPv4) in.readFully(a); this.mcastAddress=InetAddress.getByAddress(a); } public InetAddress toInetAddress(){ return mcastAddress; } public String toString(){ return mcastAddress.toString(); } public void writeExternal(ObjectOutput out) throws IOException { out.write(mcastAddress.getAddress()); } public void writeTo(DataOutput out) throws IOException { byte[] a = mcastAddress.getAddress(); // 4 bytes (IPv4) out.write(a, 0, a.length); } // ACCESS METHODS -- public void setValue(Address multicastAddress){ this.mcastAddress = ((IpAddress)multicastAddress).getIpAddress(); } public InetAddress getMcastAddress() { return mcastAddress; } public void setValue(InetAddress multicastAddress){ this.mcastAddress = multicastAddress; } public void setValue(String multicastAddress){ try { this.mcastAddress = InetAddress.getByName(multicastAddress); } catch (UnknownHostException e) { e.printStackTrace(); } } }
26.156627
104
0.740673
a37b0b41e4119e785f84a2f504837ab3a05aed38
208
package mcjty.hotspots.api; /** * Hot spots of attenuation type RADIATE and RADIATE_BLOCKER will implement this interface in addition to IHotSpot */ public interface IRadiatingHotSpot extends IHotSpot { }
26
114
0.798077
6be55637906571508432838e981a0f29ddd08993
5,919
package com.hdw.api.base.system.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.hdw.common.core.utils.JacksonUtil; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 资源表 * * @author JacksonTu * @date 2018-12-11 11:35:15 */ @ApiModel(value = "资源表") @TableName("t_sys_resource") public class SysResource implements Serializable { /** * 主键 */ @ApiModelProperty(value = "主键") @JsonSerialize(using = ToStringSerializer.class) @TableId(type = IdType.AUTO) private Long id; /** * 父级资源id */ @ApiModelProperty(value = "父级资源Id") @JsonSerialize(using = ToStringSerializer.class) @TableField("parent_id") private Long parentId; /** * 资源名称 */ @ApiModelProperty(value = "资源名称") private String name; /** * 资源路径 */ @ApiModelProperty(value = "资源路径") private String url; /** * 资源介绍 */ @ApiModelProperty(value = "资源介绍") private String description; /** * 资源图标 */ @ApiModelProperty(value = "资源图标") private String icon; /** * 排序 */ @ApiModelProperty(value = "排序") private Integer seq; /** * 资源类别(0:菜单,1:按钮) */ @ApiModelProperty(value = "资源类别(0:菜单,1:按钮)") @TableField("resource_type") private Integer resourceType; /** * 状态(0:开,1:关) */ @ApiModelProperty(value = "状态(0:开,1:关)") private Integer status; /** * 记录创建时间 */ @ApiModelProperty(value = "记录创建时间") @TableField("create_time") private Date createTime; /** * 记录最后修改时间 */ @ApiModelProperty(value = "记录最后修改时间") @TableField("update_time") private Date updateTime; /** * 记录创建用户 */ @ApiModelProperty(value = "记录创建用户") @TableField("create_user") private String createUser; /** * 记录最后修改用户 */ @ApiModelProperty(value = "记录最后修改用户") @TableField("update_user") private String updateUser; /** * 父菜单名称 */ @TableField(exist = false) private String parentName; /** * ztree属性 */ @TableField(exist = false) private Boolean open; @TableField(exist = false) private List<?> list; /** * 获取:主键 */ public Long getId() { return id; } /** * 设置:主键 */ public void setId(Long id) { this.id = id; } /** * 获取:父级资源Id */ public Long getParentId() { return parentId; } /** * 设置:父级资源Id */ public void setParentId(Long parentId) { this.parentId = parentId; } /** * 获取:资源名称 */ public String getName() { return name; } /** * 设置:资源名称 */ public void setName(String name) { this.name = name; } /** * 获取:资源路径 */ public String getUrl() { return url; } /** * 设置:资源路径 */ public void setUrl(String url) { this.url = url; } /** * 获取:资源介绍 */ public String getDescription() { return description; } /** * 设置:资源介绍 */ public void setDescription(String description) { this.description = description; } /** * 获取:资源图标 */ public String getIcon() { return icon; } /** * 设置:资源图标 */ public void setIcon(String icon) { this.icon = icon; } /** * 获取:排序 */ public Integer getSeq() { return seq; } /** * 设置:排序 */ public void setSeq(Integer seq) { this.seq = seq; } /** * 获取:资源类别(0:菜单,1:按钮) */ public Integer getResourceType() { return resourceType; } /** * 设置:资源类别(0:菜单,1:按钮) */ public void setResourceType(Integer resourceType) { this.resourceType = resourceType; } /** * 获取:状态(0:开,1:关) */ public Integer getStatus() { return status; } /** * 设置:状态(0:开,1:关) */ public void setStatus(Integer status) { this.status = status; } /** * 获取:记录创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置:记录创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取:记录最后修改时间 */ public Date getUpdateTime() { return updateTime; } /** * 设置:记录最后修改时间 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * 获取:记录创建用户 */ public String getCreateUser() { return createUser; } /** * 设置:记录创建用户 */ public void setCreateUser(String createUser) { this.createUser = createUser; } /** * 获取:记录最后修改用户 */ public String getUpdateUser() { return updateUser; } /** * 设置:记录最后修改用户 */ public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public Boolean getOpen() { return open; } public void setOpen(Boolean open) { this.open = open; } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } @Override public String toString() { return JacksonUtil.toJson(this); } }
18.100917
65
0.549755
f2eaa7baebd0bd9e6fd8a1c7a22050a95eb76dd0
2,098
/* * Copyright © 2020 Miroslav Pokorny * * 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 test; import com.google.j2cl.junit.apt.J2clTestInput; import org.junit.Assert; import org.junit.Test; import walkingkooka.collect.map.Maps; import walkingkooka.predicate.Predicates; import walkingkooka.route.RouteMappings; import walkingkooka.route.Router; import java.util.Optional; import java.util.function.Predicate; @J2clTestInput(JunitTest.class) public final class JunitTest { // Mostly copied from walkingkooka.route.sample.Sample @Test public void testBasicHttpRouter() { final RouteMappings<String, Integer> mappings = RouteMappings.<String, Integer>empty() .add(Maps.of("protocol", Predicates.is("http"), "host", Predicate.isEqual("example.com")), 12) .add(Maps.of("protocol", Predicates.is("http"), "host", Predicate.isEqual("example2.com")), 34) .add(Maps.of("protocol", Predicates.is("https")), 56); final Router<String, Integer> router = mappings.router(); final Optional<Integer> https = router.route(Maps.of("protocol", "https")); // should return 56 final Optional<Integer> http = router.route(Maps.of("protocol", "http")); // 12 and 34 both match returns nothing. final Optional<Integer> httpExample = router.route(Maps.of("protocol", "http", "host", "example.com")); // should return 12 Assert.assertEquals(Optional.of(56), https); Assert.assertEquals(Optional.empty(), http); Assert.assertEquals(Optional.of(12), httpExample); } }
40.346154
131
0.706387
a1b796185b9cc04974a889f2750971c8791a8236
728
package com.github.zeroone3010.yahueapi; /** * See https://developers.meethue.com/documentation/supported-lights for further specifications. */ public enum LightType { ON_OFF, DIMMABLE, COLOR_TEMPERATURE, COLOR, EXTENDED_COLOR, UNKNOWN; static LightType parseTypeString(final String type) { if (type == null) { return UNKNOWN; } switch (type.toLowerCase()) { case "on/off light": return ON_OFF; case "dimmable light": return DIMMABLE; case "color temperature light": return COLOR_TEMPERATURE; case "color light": return COLOR; case "extended color light": return EXTENDED_COLOR; default: return UNKNOWN; } } }
24.266667
96
0.648352
83b6378de87fbff1f59e0478214d627502898d93
715
package com.terryrao.shiro; import com.terryrao.admin.model.AdminLoginLog; import com.terryrao.admin.model.AdminPermission; import com.terryrao.admin.model.AdminUser; import java.util.List; /** * 登录服务 所有使用 shiro 验证系统的请实现此类 * 2018/4/24 * */ public interface AdminLoginService { /** * 使用登录名称获取用户信息 */ AdminUser findByName(String adminName); /** * 获取所有的权限 */ List<AdminPermission> listPermissionsByRoleId(String roleId); /** * 禁用用户 */ boolean lockAdmin(String adminNo); // // /** // * 登录日志 // */ // boolean saveLoginLog(ShiroUser user, String ip); /** * 系统登录日志 */ boolean saveSysLoginLog(AdminLoginLog loginLog); }
15.543478
65
0.634965
62994250bb8199bc48a33c3b40d1e363c5f08511
461
package com.mall.vo; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; /** * @author ZZH * @date 2018/10/2 0002 16:26 **/ @Getter @Setter public class ProductListVo { private Integer id; private Integer categoryId; private String name; private String subtitle; private String mainImage; private BigDecimal price; private Integer status; private String imageHost; }
15.366667
32
0.659436
86b1483f308eca1ce604ace1077a29150041f36e
777
package org.intermine.web.displayer; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ @SuppressWarnings("serial") class ReportDisplayerNoResultsException extends Exception { String mistake; public ReportDisplayerNoResultsException() { super(); mistake = "The displayer has no results to show"; } public ReportDisplayerNoResultsException(String err) { // a super error... super(err); mistake = err; } public String getError() { return mistake; } }
22.852941
63
0.676963
6f1c3ea829469d47177517d87e06f860915c6cfb
19,090
package seedu.testplanner.logic; import com.google.common.eventbus.Subscribe; import seedu.dailyplanner.commons.core.EventsCenter; import seedu.dailyplanner.commons.events.model.DailyPlannerChangedEvent; import seedu.dailyplanner.commons.events.ui.JumpToListRequestEvent; import seedu.dailyplanner.commons.events.ui.ShowHelpRequestEvent; import seedu.dailyplanner.logic.Logic; import seedu.dailyplanner.logic.LogicManager; import seedu.dailyplanner.logic.commands.*; import seedu.dailyplanner.model.DailyPlanner; import seedu.dailyplanner.model.Model; import seedu.dailyplanner.model.ModelManager; import seedu.dailyplanner.model.ReadOnlyDailyPlanner; import seedu.dailyplanner.model.category.Category; import seedu.dailyplanner.model.category.UniqueCategoryList; import seedu.dailyplanner.model.task.*; import seedu.dailyplanner.storage.StorageManager; import seedu.testplanner.testutil.TaskBuilder; import seedu.testplanner.testutil.TestTask; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.dailyplanner.commons.core.Messages.*; public class LogicManagerTest { /** * See https://github.com/junit-team/junit4/wiki/rules#temporaryfolder-rule */ @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyDailyPlanner latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(DailyPlannerChangedEvent abce) { latestSavedAddressBook = new DailyPlanner(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setup() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new DailyPlanner(model.getDailyPlanner()); // last saved assumed to be up to date before. helpShown = false; targetedJumpIndex = -1; // non yet } @After public void teardown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command and confirms that the result message is correct. * Both the 'address book' and the 'last shown list' are expected to be empty. * @see #assertCommandBehavior(String, String, ReadOnlyDailyPlanner, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new DailyPlanner(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyDailyPlanner expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) throws Exception { //Execute the command CommandResult result = logic.execute(inputCommand); //Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getDailyPlanner()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws Exception { assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generatePerson(1)); model.addTask(helper.generatePerson(2)); model.addTask(helper.generatePerson(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new DailyPlanner(), Collections.emptyList()); } /**@Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior( "add wrong args wrong args", expectedMessage); assertCommandBehavior( "add Valid Name 12345 e/valid@email.butNoPhonePrefix a/valid, address", expectedMessage); assertCommandBehavior( "add Valid Name p/12345 valid@email.butNoPrefix a/valid, address", expectedMessage); assertCommandBehavior( "add Valid Name p/12345 e/valid@email.butNoAddressPrefix valid, address", expectedMessage); } @Test public void execute_add_invalidPersonData() throws Exception { assertCommandBehavior( "add []\\[;] p/12345 e/valid@e.mail a/valid, address", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandBehavior( "add Valid Name p/not_numbers e/valid@e.mail a/valid, address", Date.MESSAGE_PHONE_CONSTRAINTS); assertCommandBehavior( "add Valid Name p/12345 e/notAnEmail a/valid, address", StartTime.MESSAGE_EMAIL_CONSTRAINTS); assertCommandBehavior( "add Valid Name p/12345 e/valid@e.mail a/valid, address t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); }**/ @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); DailyPlanner expectedAB = new DailyPlanner(); expectedAB.addTask(toBeAdded); System.out.println(helper.generateAddCommand(toBeAdded)); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); DailyPlanner expectedAB = new DailyPlanner(); expectedAB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // person already in internal address book // execute command and verify result assertCommandBehavior( helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); } @Test public void execute_list_showsAllPersons() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); DailyPlanner expectedAB = helper.generateAddressBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandBehavior("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord , expectedMessage); //index missing assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single person in the shown list, using visible index. * @param commandWord to test assuming it targets a single person in the last shown list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> personList = helper.generatePersonList(2); // set AB state to 2 persons model.resetData(new DailyPlanner()); for (Task p : personList) { model.addTask(p); } assertCommandBehavior(commandWord + " 3", expectedMessage, model.getDailyPlanner(), personList); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generatePersonList(3); DailyPlanner expectedAB = helper.generateAddressBook(threePersons); helper.addToModel(model, threePersons); assertCommandBehavior("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threePersons.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectPerson() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threePersons = helper.generatePersonList(3); DailyPlanner expectedAB = helper.generateAddressBook(threePersons); expectedAB.removeTask(threePersons.get(1)); helper.addToModel(model, threePersons); assertCommandBehavior("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threePersons.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generatePersonWithName("bla bla KEY bla"); Task pTarget2 = helper.generatePersonWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generatePersonWithName("key key"); Task p1 = helper.generatePersonWithName("sduauo"); List<Task> fourPersons = helper.generatePersonList(pTarget1, p1, pTarget2, pTarget3); DailyPlanner expectedAB = helper.generateAddressBook(fourPersons); List<Task> expectedList = helper.generatePersonList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourPersons); assertCommandBehavior("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ //@@author A0140124B class TestDataHelper{ Task adam() throws Exception { TaskBuilder meetAdamTaskBuilder = new TaskBuilder(); meetAdamTaskBuilder.withName("Meet adam").withStartDate("07/11/2016").withEndDate("08/11/2016").withCompletion(false) .withCategories("meeting") .withPin(false); Task meetAdamTask = meetAdamTaskBuilder.buildAsTask(); System.out.println("Task generated: " + meetAdamTask.toString()); return meetAdamTask; } /** * Generates a valid person using the given seed. * Running this function with the same parameter values guarantees the returned person will have the same state. * Each unique seed will generate a unique Person object. * * @param seed used to generate the person data field values */ Task generatePerson(int seed) throws Exception { TaskBuilder generateTaskBuilder = new TaskBuilder(); generateTaskBuilder.withName("Task " + seed).withStartDateAndTime("today " + Math.abs(seed)+"am") .withEndDateAndTime("tomorrow " + Math.abs(seed)+"pm") .withCompletion(false) .withCategories("tag" + Math.abs(seed)) .withPin(false); return generateTaskBuilder.buildAsTask(); } /** Generates the correct add command based on the person given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" s/").append(p.getStart().toString()); cmd.append(" e/").append(p.getEnd().toString()); UniqueCategoryList tags = p.getCats(); for(Category t: tags){ cmd.append(" c/").append(t.tagName); } return cmd.toString(); } //@@author /** * Generates an AddressBook with auto-generated persons. */ DailyPlanner generateAddressBook(int numGenerated) throws Exception{ DailyPlanner dailyPlanner = new DailyPlanner(); addToAddressBook(dailyPlanner, numGenerated); return dailyPlanner; } /** * Generates an AddressBook based on the list of Persons given. */ DailyPlanner generateAddressBook(List<Task> persons) throws Exception{ DailyPlanner dailyPlanner = new DailyPlanner(); addToAddressBook(dailyPlanner, persons); return dailyPlanner; } /** * Adds auto-generated Person objects to the given AddressBook * @param dailyPlanner The AddressBook to which the Persons will be added */ void addToAddressBook(DailyPlanner dailyPlanner, int numGenerated) throws Exception{ addToAddressBook(dailyPlanner, generatePersonList(numGenerated)); } /** * Adds the given list of Persons to the given AddressBook */ void addToAddressBook(DailyPlanner dailyPlanner, List<Task> personsToAdd) throws Exception{ for(Task p: personsToAdd){ dailyPlanner.addTask(p); } } /** * Adds auto-generated Person objects to the given model * @param model The model to which the Persons will be added */ void addToModel(Model model, int numGenerated) throws Exception{ addToModel(model, generatePersonList(numGenerated)); } /** * Adds the given list of Persons to the given model */ void addToModel(Model model, List<Task> personsToAdd) throws Exception{ for(Task p: personsToAdd){ model.addTask(p); } } /** * Generates a list of Persons based on the flags. */ List<Task> generatePersonList(int numGenerated) throws Exception{ List<Task> persons = new ArrayList<>(); for(int i = 1; i <= numGenerated; i++){ persons.add(generatePerson(i)); } return persons; } List<Task> generatePersonList(Task... persons) { return Arrays.asList(persons); } /** * Generates a Person object with given name. Other fields will have some dummy values. */ Task generatePersonWithName(String name) throws Exception { TaskBuilder generateTaskBuilder = new TaskBuilder(); generateTaskBuilder.withName(name).withStartDateAndTime("today " + "1pm") .withEndDateAndTime("tomorrow " + "1pm") .withCompletion(false) .withCategories("tag") .withPin(false); return generateTaskBuilder.buildAsTask(); } } }
38.959184
129
0.670875
6ea98bb083d57e58932f7b02a7a68c0558d4e942
1,898
package thymeleafsandbox.springsecurity.web.controller; import java.util.Locale; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.server.ServerWebExchange; import org.unbescape.html.HtmlEscape; import reactor.core.publisher.Mono; /** * Application home page and login. */ @Controller public class MainController { @RequestMapping("/") public Mono<String> root(Locale locale) { return Mono.just("redirect:/index.html"); } /** Home page. */ @RequestMapping("/index.html") public Mono<String> index() { return Mono.just("index"); } /** User zone index. */ @RequestMapping("/user/index.html") public Mono<String> userIndex() { return Mono.just("user/index"); } /** Administration zone index. */ @RequestMapping("/admin/index.html") public Mono<String> adminIndex() { return Mono.just("admin/index"); } /** Shared zone index. */ @RequestMapping("/shared/index.html") public Mono<String> sharedIndex() { return Mono.just("shared/index"); } /** Login form. */ @RequestMapping("/login.html") public Mono<String> login() { return Mono.just("login"); } /** Login form with error. */ @RequestMapping("/login-error.html") public Mono<String> loginError(Model model) { model.addAttribute("loginError", true); return Mono.just("login"); } /** Simulation of an exception. */ @RequestMapping("/simulateError.html") public void simulateError() { throw new RuntimeException("This is a simulated error message"); } /** Error page. */ @RequestMapping("/403.html") public Mono<String> forbidden() { return Mono.just("403"); } }
24.973684
72
0.647524
3ade3609e77c4b6365591e2a3cb34e23b1299b65
2,974
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package io.undertow.client; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import io.undertow.util.HttpString; import org.xnio.OptionMap; import org.xnio.Pool; import org.xnio.channels.ConnectedStreamChannel; import io.undertow.util.AbstractAttachable; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public abstract class HttpClientConnection extends AbstractAttachable implements Closeable { private final HttpClient client; protected HttpClientConnection(final HttpClient client) { this.client = client; } public HttpClient getClient() { return client; } /** * Initiate an HTTP request on this connection. * * @param method the HTTP request method to use * @param target the target URI to access * @return the new request, or {@code null} if no more requests can be made on this connection * @throws IOException */ public HttpClientRequest createRequest(final String method, final URI target) throws IOException { return createRequest(new HttpString(method), target); } /** * Initiate an HTTP request on this connection. * * @param method the HTTP request method to use * @param target the target URI to access * @return the new request, or{@code null} if no more request can be made on this connection * @throws IOException */ public abstract HttpClientRequest createRequest(final HttpString method, final URI target); /** * Upgrade this HTTP connection to a raw socket * * @param handshake The handshake class * @param optionMap the channel options * @return the future channel * @throws IOException */ public abstract ConnectedStreamChannel performUpgrade() throws IOException; abstract OptionMap getOptions(); public abstract Pool<ByteBuffer> getBufferPool(); }
34.581395
102
0.720915
9f36101c794f12e1a07ab9297f49709cdbbe1305
2,501
/* * Copyright 2014 al333z. * * 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 asw1013; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that given a username as parameter, returns the profile image */ @WebServlet("/pic") public class DownloadFileServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("username"); if (fileName == null || fileName.equals("")) { throw new ServletException("File Name can't be null or empty"); } // get path to images File file = new File(getServletContext().getRealPath("/WEB-INF/profilepics/"+fileName)); if (!file.exists()) { throw new ServletException("File doesn't exists on server."); } ServletContext ctx = getServletContext(); InputStream fis = new FileInputStream(file); String mimeType = ctx.getMimeType(file.getAbsolutePath()); response.setContentType(mimeType != null ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // write the img to response ServletOutputStream os = response.getOutputStream(); byte[] bufferData = new byte[1024]; int read = 0; while ((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); } os.flush(); os.close(); fis.close(); } }
35.728571
121
0.689324
199a75438e4c06418d563a76e8bdcb83b4cdb46f
4,062
/* * Copyright 2020 Huawei Technologies Co., Ltd. * * 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.mec.emulator.model; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import org.springframework.validation.annotation.Validated; /** * Area information */ @ApiModel(description = "区域信息") @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-06-05T02:11:06.510Z") public class ZoneInfo { @JsonProperty("zoneId") private String zoneId = null; @JsonProperty("numberOfAccessPoints") private Integer numberOfAccessPoints = null; @JsonProperty("numberOfUnserviceableAccessPoints") private Integer numberOfUnserviceableAccessPoints = null; @JsonProperty("numberOfUsers") private Integer numberOfUsers = null; @JsonProperty("resourceURL") private String resourceURL = null; public ZoneInfo zoneId(String zoneId) { this.zoneId = zoneId; return this; } /** * Get zoneId * * @return zoneId **/ @ApiModelProperty(required = true, value = "") @NotNull public String getZoneId() { return zoneId; } public void setZoneId(String zoneId) { this.zoneId = zoneId; } public ZoneInfo numberOfAccessPoints(Integer numberOfAccessPoints) { this.numberOfAccessPoints = numberOfAccessPoints; return this; } /** * Get numberOfAccessPoints * * @return numberOfAccessPoints **/ @ApiModelProperty(required = true, value = "") @NotNull public Integer getNumberOfAccessPoints() { return numberOfAccessPoints; } public void setNumberOfAccessPoints(Integer numberOfAccessPoints) { this.numberOfAccessPoints = numberOfAccessPoints; } public ZoneInfo numberOfUnserviceableAccessPoints(Integer numberOfUnserviceableAccessPoints) { this.numberOfUnserviceableAccessPoints = numberOfUnserviceableAccessPoints; return this; } /** * Get numberOfUnserviceableAccessPoints * * @return numberOfUnserviceableAccessPoints **/ @ApiModelProperty(required = true, value = "") @NotNull public Integer getNumberOfUnserviceableAccessPoints() { return numberOfUnserviceableAccessPoints; } public void setNumberOfUnserviceableAccessPoints(Integer numberOfUnserviceableAccessPoints) { this.numberOfUnserviceableAccessPoints = numberOfUnserviceableAccessPoints; } public ZoneInfo numberOfUsers(Integer numberOfUsers) { this.numberOfUsers = numberOfUsers; return this; } /** * Get numberOfUsers * * @return numberOfUsers **/ @ApiModelProperty(required = true, value = "") @NotNull public Integer getNumberOfUsers() { return numberOfUsers; } public void setNumberOfUsers(Integer numberOfUsers) { this.numberOfUsers = numberOfUsers; } public ZoneInfo resourceURL(String resourceURL) { this.resourceURL = resourceURL; return this; } /** * Get resourceURL * * @return resourceURL **/ @ApiModelProperty(required = true, value = "") @NotNull public String getResourceURL() { return resourceURL; } public void setResourceURL(String resourceURL) { this.resourceURL = resourceURL; } }
27.08
116
0.690054
c5e73abc7c083f8d1e5a6aba12bfba8b8e12bcf1
532
package de.mlessmann.totaleconomy.worker; import org.spongepowered.api.text.channel.MessageChannel; import java.io.File; import java.util.function.Consumer; /** * Created by MarkL4YG on 14-May-18 */ public class ExportWorker extends AbstractWorker { private File outputDir; public ExportWorker(File outputDir, MessageChannel feedback, Consumer<AbstractWorker> onDone) { super(feedback, onDone); this.outputDir = outputDir; } @Override public void run() { internalAbort(); } }
21.28
99
0.710526
f8d31c297fdd4a443a5e428a99787ad0a5bb897b
1,283
package pdytr.example.grpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import pdytr.example.grpc.GreeterGrpc; import pdytr.example.grpc.GreeterGrpc.GreeterBlockingStub; import pdytr.example.grpc.GreeterOuterClass.HelloRequest; import pdytr.example.grpc.GreeterOuterClass.HelloReply; public class Client { public static void main(String[] args) throws Exception { // Channel is the abstraction to connect to a service endpoint // Let's use plaintext communication because we don't have certs final ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8080").usePlaintext(true).build(); // It is up to the client to determine whether to block the call // Here we create a blocking stub, but an async stub, // or an async stub with Future are always possible. GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("Ray").build(); // Finally, make the call using the stub HelloReply response = stub.sayHello(request); String greeting = response.getMessage(); System.out.println("Client received the greeting: " + greeting); // A Channel should be shutdown before stopping the process. channel.shutdownNow(); } }
40.09375
112
0.759158
676126c63f06aa6cec891d51a2cd8a690d09fd90
1,688
package nu.nerd.easyrider.commands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import nu.nerd.easyrider.EasyRider; import nu.nerd.easyrider.PlayerState; // ---------------------------------------------------------------------------- /** * Handles the /horse-bypass command. */ public class HorseBypassExecutor extends ExecutorBase { // ------------------------------------------------------------------------ /** * Default constructor. */ public HorseBypassExecutor() { super("horse-bypass", "help"); } // ------------------------------------------------------------------------ /** * @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, * org.bukkit.command.Command, java.lang.String, java.lang.String[]) */ @Override public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "You must be in game to use this command."); return true; } if (args.length != 0) { return false; } PlayerState state = EasyRider.PLUGIN.getState((Player) sender); state.toggleBypassEnabled(); if (state.isBypassEnabled()) { sender.sendMessage(ChatColor.GOLD + "You can now bypass access permission checks."); } else { sender.sendMessage(ChatColor.GOLD + "You can no longer bypass access permission checks."); } return true; } } // class HorseBypassExecutor
34.44898
102
0.560427
0cb891dfcb3e1306f5931d00ba97238cd3d45c1d
2,570
package com.iqarr.maven.plugin.exception; import org.mozilla.javascript.ErrorReporter; import org.mozilla.javascript.EvaluatorException; import com.iqarr.maven.plugin.support.logger.LoggerFactory; /** * @author * zhangyong */ public class YUIException implements ErrorReporter { private String fileName; /** * <p>Title: </p> * <p>Description: </p> * @param log */ public YUIException(String fileName) { this.fileName=fileName; } /* * <p>Title: error</p> * <p>Description: </p> * @param arg0 * @param arg1 * @param arg2 * @param arg3 * @param arg4 * @see org.mozilla.javascript.ErrorReporter#error(java.lang.String, java.lang.String, int, java.lang.String, int) */ @Override public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { LoggerFactory.error("\n[ERROR] in "+fileName); if (line < 0) { LoggerFactory.error(" " + message); } else { LoggerFactory.error(" " + line + ':' + lineOffset + ':' + message); } } /* * <p>Title: runtimeError</p> * <p>Description: </p> * @param arg0 * @param arg1 * @param arg2 * @param arg3 * @param arg4 * @return * @see org.mozilla.javascript.ErrorReporter#runtimeError(java.lang.String, java.lang.String, int, java.lang.String, int) */ @Override public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { error(message, sourceName, line, lineSource, lineOffset); return new EvaluatorException(message); } /* * <p>Title: warning</p> * <p>Description: </p> * @param arg0 * @param arg1 * @param arg2 * @param arg3 * @param arg4 * @see org.mozilla.javascript.ErrorReporter#warning(java.lang.String, java.lang.String, int, java.lang.String, int) */ @Override public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { LoggerFactory.warn("\n[WARNING] in "+fileName); if (line < 0) { LoggerFactory.warn(" " + message); } else { LoggerFactory.warn(" " + line + ':' + lineOffset + ':' + message); } } }
27.052632
126
0.550973
9b17ab5965db176fd8f5a2d97982a56728278ae8
731
package com.revature.Data; import com.revature.Classes.Employee; import com.revature.Classes.Expense; import com.revature.Classes.Manager; import java.util.List; public interface ExpenseDAO { List<Expense> getExpenses(); List<Expense> getExpenses(Employee employee); List<Expense> getDeclinedExpenses(Employee employee); List<Expense> getPendingExpenses(Employee employee); List<Expense> getPendingExpenses(); List<Expense> getExpensesProcessedBy(Manager manager); Expense getExpense(int id); void saveExpense(Expense expense); void updateExpense(Expense expense); void saveExpenses(List<Expense> expenses); void updateExpenses(List<Expense> expenses); void close(); }
21.5
58
0.751026
b450bfa6f661d8af724d55a54f6dd5945a1b05fb
586
package server.parser; import server.HttpMethod; import server.HttpParser; import server.HttpRequestLine; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * リクエストラインのパーサ */ public class HttpRequestLineParser implements HttpParser<String, HttpRequestLine> { @Override public HttpRequestLine parse(final String line) { List<String> parsed = Stream.of(line.split(" ")).map(String::trim).collect(Collectors.toList()); return new HttpRequestLine(HttpMethod.of(parsed.get(0)), parsed.get(1), parsed.get(2)); } }
26.636364
104
0.738908
837e11040d56ab31c5acd8d9b538e071a1524ece
4,782
package io.jitstatic; /*- * #%L * jitstatic * %% * Copyright (C) 2017 - 2018 H.Hegardt * %% * 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. * #L% */ import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import io.jitstatic.source.ObjectStreamProvider; import io.jitstatic.source.SmallObjectStreamProvider; import io.jitstatic.utils.Functions.ThrowingSupplier; import io.jitstatic.utils.Pair; public class SourceUpdater { private final RepositoryUpdater repositoryUpdater; public SourceUpdater(final RepositoryUpdater repositoryUpdater) { this.repositoryUpdater = repositoryUpdater; } public Pair<Pair<ThrowingSupplier<ObjectLoader, IOException>, String>, String> addKey( final Pair<Pair<String, ObjectStreamProvider>, Pair<String, byte[]>> fileEntry, final CommitMetaData commitMetaData, final String ref) throws IOException { final List<Pair<String, ObjectId>> addedEntry = addEntry(fileEntry, commitMetaData, ref); final Pair<String, ObjectId> file = addedEntry.get(0); final Pair<String, ObjectId> metadata = addedEntry.get(1); return Pair.of(Pair.of(getObjectLoaderFactory(file), file.getRight().name()), metadata.getRight().name()); } public String updateMetaData(final String key, final byte[] data, final CommitMetaData commitMetaData, final String ref) throws IOException { final Pair<String, ObjectId> updateMetaDataEntry = addEntry(Pair.of(Pair.ofNothing(), Pair.of(key, data)), commitMetaData, ref) .get(0); return updateMetaDataEntry.getRight().name(); } public Pair<String, ThrowingSupplier<ObjectLoader, IOException>> updateKey(final String key, final ObjectStreamProvider data, final CommitMetaData commitMetaData, final String ref) throws IOException { final Pair<String, ObjectId> updatedKeyEntry = addEntry(Pair.of(Pair.of(key, data), Pair.ofNothing()), commitMetaData, ref).get(0); return Pair.of(updatedKeyEntry.getRight().name(), getObjectLoaderFactory(updatedKeyEntry)); } private ThrowingSupplier<ObjectLoader, IOException> getObjectLoaderFactory(final Pair<String, ObjectId> updatedKeyEntry) { final Repository repository = repositoryUpdater.getRepository(); final ObjectId objectId = updatedKeyEntry.getRight(); return () -> repository.open(objectId); } private List<Pair<String, ObjectId>> addEntry(final Pair<Pair<String, ObjectStreamProvider>, Pair<String, byte[]>> keyEntry, final CommitMetaData commitMetaData, final String ref) throws IOException { Objects.requireNonNull(keyEntry); final Pair<String, ObjectStreamProvider> file = Objects.requireNonNull(keyEntry.getLeft()); final Pair<String, byte[]> fileMetadata = Objects.requireNonNull(keyEntry.getRight()); if (!file.isPresent() && !fileMetadata.isPresent()) { throw new IllegalArgumentException("No entry data"); } byte[] fileMetaDataArray = fileMetadata.getRight(); return repositoryUpdater.buildDirCache(commitMetaData, List.of(file, Pair.of(fileMetadata.getLeft(), fileMetaDataArray == null ? null : new SmallObjectStreamProvider(fileMetaDataArray))), ref); } public void deleteKey(final String file, final CommitMetaData commitMetaData, final boolean hasKeyMetaFile, final String ref) throws IOException { List<Pair<String, ObjectStreamProvider>> files = (hasKeyMetaFile ? Set.of(file, file + JitStaticConstants.METADATA) : Set.of(file)).stream() .map(f -> Pair.of(f, (ObjectStreamProvider) null)) .collect(Collectors.toList()); repositoryUpdater.buildDirCache(commitMetaData, files, ref); } public void createRef(final String baseRef, final String finalRef) throws IOException { repositoryUpdater.createRef(baseRef, finalRef); } public void deleteRef(final String finalRef) throws IOException { repositoryUpdater.deleteRefs(List.of(finalRef)); } }
45.980769
154
0.719783
0a954db845a09075d35210d98fde196708e1380f
1,613
package com.samsung.sec.dexter.eclipse.ui.action; import com.samsung.sec.dexter.core.config.DexterConfig; import com.samsung.sec.dexter.core.defect.Defect; import com.samsung.sec.dexter.core.exception.DexterRuntimeException; import com.samsung.sec.dexter.eclipse.ui.util.EclipseUtil; import com.samsung.sec.dexter.eclipse.ui.view.PlatzView; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPart; public class PlatzAction implements IObjectActionDelegate { private Defect defect; private IWorkbenchPart part; public PlatzAction() {} @Override public void run(IAction action) { assert defect != null; try { IViewPart platzPart = EclipseUtil.findView(PlatzView.ID); final PlatzView platzView = (PlatzView) platzPart; StringBuilder url = new StringBuilder(1024); url.append(DexterConfig.PLATZ_API_URL); url.trimToSize(); platzView.setUrl(url.toString()); EclipseUtil.showView(PlatzView.ID); } catch (DexterRuntimeException e) { MessageDialog.openError(part.getSite().getShell(), "PLATZ Error", "Cannot open the PLATZ View"); } } @Override public void selectionChanged(IAction action, ISelection selection) {} @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) { part = targetPart; } }
32.918367
77
0.706758
f6dfd80cb1c263a064a4c6337fa85955b688096d
4,629
package org.dataalgorithms.chapB10.friendrecommendation.mapreduce; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; /** * WritableComparable representing a pair of longs. * The elements in the pair are referred to as the left * and right elements. The natural sort order is: first * by the left element, and then by the right element. * * @author Mahmoud Parsian * Adapted from Jimmy Lin's Cloud9 * */ public class PairOfLongs implements WritableComparable<PairOfLongs> { private long left; private long right; /** * Creates a pair of longs. */ public PairOfLongs() { } /** * Creates a pair. * * @param left the left element * @param right the right element */ public PairOfLongs(long left, long right) { set(left, right); } /** * Deserializes this pair. * * @param in source for raw byte representation */ public void readFields(DataInput in) throws IOException { left = in.readLong(); right = in.readLong(); } /** * Serializes this pair. * * @param out where to write the raw byte representation */ public void write(DataOutput out) throws IOException { out.writeLong(left); out.writeLong(right); } /** * Returns the left. * * @return the left */ public long getLeft() { return left; } /** * Returns the right. * * @return the right */ public long getRight() { return right; } /** * Sets the right and left elements of this pair. * * @param left the left * @param right the right */ public void set(long left, long right) { this.left = left; this.right = right; } /** * Checks two pairs for equality. * * @param obj object for comparison * @return <code>true</code> if <code>obj</code> is equal to this object, <code>false</code> * otherwise */ public boolean equals(Object obj) { PairOfLongs pair = (PairOfLongs) obj; return left == pair.getLeft() && right == pair.getRight(); } /** * Defines a natural sort order for pairs. Pairs are sorted first by the left element, * and then by the right element. * * @return a value less than zero, a value greater than zero, or zero if this pair should be * sorted before, sorted after, or is equal to <code>obj</code>. */ public int compareTo(PairOfLongs pair) { long L = pair.getLeft(); long R = pair.getRight(); if (left == L) { if (right < R) { return -1; } if (right > R) { return 1; } return 0; } if (left < L) { return -1; } return 1; } /** * Returns a hash code value for the pair. * * @return hash code for the pair */ public int hashCode() { return (int) left & (int) right; } /** * Generates human-readable String representation of this pair. * * @return human-readable String representation of this pair */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("("); builder.append(left); builder.append(", "); builder.append(right); builder.append(")"); return builder.toString(); } /** * Clones this object. * * @return clone of this object */ public PairOfLongs clone() { return new PairOfLongs(this.left, this.right); } /** Comparator optimized for <code>PairOfLongs</code>. */ public static class Comparator extends WritableComparator { /** * Creates a new Comparator optimized for <code>PairOfLongs</code>. */ public Comparator() { super(PairOfLongs.class); } /** * Optimization hook. */ public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { long thisLeftValue = readLong(b1, s1); long thatLeftValue = readLong(b2, s2); if (thisLeftValue == thatLeftValue) { long thisRightValue = readLong(b1, s1 + 8); long thatRightValue = readLong(b2, s2 + 8); return (thisRightValue < thatRightValue ? -1 : (thisRightValue == thatRightValue ? 0 : 1)); } return (thisLeftValue < thatLeftValue ? -1 : (thisLeftValue == thatLeftValue ? 0 : 1)); } } static { // register this comparator WritableComparator.define(PairOfLongs.class, new Comparator()); } }
23.860825
102
0.597537
995b7cf0b5569ef847589227e4d5a09857870b88
479
package com.deitel.cap16.colecoesgenericas; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Sort2 { public static void main(String[] args) { String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; List<String> list = Arrays.asList(suits); System.out.printf("Array não ordenado: %s%n", list); Collections.sort(list, Collections.reverseOrder()); System.out.printf("Array na ordem inversa: %s%n", list); } }
22.809524
61
0.695198
7f58d53b07582f56d02ab9577bb4ebed4f27253d
3,828
/* * Copyright 2018 Roberto Leinardi. * * 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.stone.notificationfilter.actioner.floatbutton; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Build; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; import androidx.interpolator.view.animation.FastOutSlowInInterpolator; //import androidx.appcompat.view.ViewCompat; //import androidx.view.animation.FastOutSlowInInterpolator; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import com.stone.notificationfilter.R; import static android.view.View.GONE; import static android.view.View.VISIBLE; public class UiUtils { private UiUtils() { } /** * dp转px * @param context * @param dp * @return */ public static int dpToPx(Context context, float dp) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics)); } /** * px转dp * @param px * @return */ public static int pxToDp(float px) { return Math.round(px / Resources.getSystem().getDisplayMetrics().density); } /** * Fade out animation. * * @param view view to animate. */ public static void fadeOutAnim(final View view) { ViewCompat.animate(view).cancel(); view.setAlpha(1F); view.setVisibility(VISIBLE); ViewCompat.animate(view) .alpha(0F) .withLayer() .setDuration(view.getContext().getResources().getInteger(R.integer.sd_close_animation_duration)) .setInterpolator(new FastOutSlowInInterpolator()) .withEndAction(new Runnable() { @Override public void run() { view.setVisibility(GONE); } }) .start(); } /** * Fade out animation. * * @param view view to animate. */ public static void fadeInAnim(final View view) { ViewCompat.animate(view).cancel(); view.setAlpha(0); view.setVisibility(VISIBLE); ViewCompat.animate(view) .alpha(1F) .withLayer() .setDuration(view.getContext().getResources().getInteger(R.integer.sd_open_animation_duration)) .setInterpolator(new FastOutSlowInInterpolator()) .start(); } /** * 获取状态栏高度 * @param context * @return */ public static int getStatusBarHeight(Context context) { Resources resources = context.getResources(); int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); int height = resources.getDimensionPixelSize(resourceId); return height; } }
30.624
112
0.662748
4bcac539159978c49ad47c965be65bc428d0d3e3
2,745
package webapp.tier.service; import java.util.Objects; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.jms.ConnectionFactory; import javax.jms.JMSConsumer; import javax.jms.JMSContext; import javax.jms.Session; import org.eclipse.microprofile.config.inject.ConfigProperty; import webapp.tier.interfaces.Messaging; import webapp.tier.util.CreateId; import webapp.tier.util.MsgBeanUtils; @ApplicationScoped public class ActiveMqService implements Messaging { @Inject ConnectionFactory connectionFactory; @ConfigProperty(name = "common.message") String message; @ConfigProperty(name = "activemq.splitkey") String splitkey; @ConfigProperty(name = "activemq.queue.name") String queuename; @ConfigProperty(name = "activemq.topic.name") String topicname; private static final Logger LOG = Logger.getLogger(ActiveMqService.class.getSimpleName()); @Override public String putMsg() throws Exception { MsgBeanUtils msgbean = new MsgBeanUtils(CreateId.createid(), message); String body = msgbean.createBody(msgbean, splitkey); try (JMSContext context = connectionFactory.createContext(Session.AUTO_ACKNOWLEDGE)) { context.createProducer().send(context.createQueue(queuename), context.createTextMessage(body)); } catch (Exception e) { e.printStackTrace(); throw new Exception("Put Error."); } msgbean.setFullmsgWithType(msgbean, "Put"); LOG.info(msgbean.getFullmsg()); return msgbean.getFullmsg(); } @Override public String getMsg() throws Exception { MsgBeanUtils msgbean = new MsgBeanUtils(); try (JMSContext context = connectionFactory.createContext(Session.AUTO_ACKNOWLEDGE)) { JMSConsumer consumer = context.createConsumer(context.createQueue(queuename)); String resp = consumer.receiveBody(String.class); if (Objects.isNull(resp)) { msgbean.setFullmsg("No Data"); } else { msgbean.setFullmsgWithType(msgbean.splitBody(resp, splitkey), "Get"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Get Error."); } LOG.info(msgbean.getFullmsg()); return msgbean.getFullmsg(); } @Override public String publishMsg() throws Exception { MsgBeanUtils msgbean = new MsgBeanUtils(CreateId.createid(), message); String body = msgbean.createBody(msgbean, splitkey); try (JMSContext context = connectionFactory.createContext(Session.AUTO_ACKNOWLEDGE)) { context.createProducer().send(context.createTopic(topicname), context.createTextMessage(body)); } catch (Exception e) { e.printStackTrace(); throw new Exception("Publish Error."); } msgbean.setFullmsgWithType(msgbean, "Publish"); LOG.info(msgbean.getFullmsg()); return msgbean.getFullmsg(); } }
31.918605
98
0.762477
a9b9ebe1d71877b5557d57d469592c5e3260f60e
629
package engine.player; import java.util.Collection; import java.util.List; /** * Additional methods for a player list interface, specific to this implementaiton * @author Max Smith */ public interface PlayerListInterface { /** * Set the starting position for iteration within the list * @param index index of the player to point to * @return true if that player exists in the list */ boolean pointTo(int index); /** * Fetch all players in the list, using for initial debug * @return all players in the collection (aka at the table) */ Collection<Player> getPlayers(); }
24.192308
82
0.686804
9a69e1f1ba7456561ae809040e0c5a63c39dd0d3
240
package com.app.jagles.networkCallback; /** * Created by Administrator on 2016/10/13. */ public interface OnOSDTextureAvaibleListener { public int OnOSDTextureAvaible(int width, int height, long frame, int length, long utcTime); }
21.818182
96
0.758333
d0e71b634a52bcb2998a681403f8736d62a624ae
1,674
/* * Copyright 2017-2020 Alfresco Software, Ltd. * * 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.activiti.cloud.services.modeling.rest.assembler; import org.activiti.cloud.modeling.api.ModelType; import org.springframework.hateoas.LinkRelation; import org.springframework.hateoas.server.LinkRelationProvider; /** * Rel provider for {@link ModelType} */ public class ModelTypeLinkRelationProvider implements LinkRelationProvider { public static final String COLLECTION_RESOURCE_REL = "model-types"; public static final String ITEM_RESOURCE_REL = "model-type"; public static final LinkRelation collectionResourceRel = LinkRelation.of("model-types"); public static final LinkRelation itemResourceRel = LinkRelation.of("model-type"); @Override public LinkRelation getItemResourceRelFor(Class<?> type) { return itemResourceRel; } @Override public LinkRelation getCollectionResourceRelFor(Class<?> type) { return collectionResourceRel; } @Override public boolean supports(LookupContext delimiter) { return ModelType.class.isAssignableFrom(delimiter.getType()); } }
32.823529
92
0.751493
9e91f8ba2160a925b79c929e3f333ea30a9bb848
652
package com.java.mmzsblog.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author :liuhongjiang * @description:TODO * @date :2020/1/16 16:09 */ @RestController public class testController { // @Resource // private DataSource dataSource; @GetMapping("/query") public void query(){ // System.out.println("查询到的数据源连接池信息是:"+dataSource); // System.out.println("查询到的数据源连接池类型是:"+dataSource.getClass()); // System.out.println("查询到的数据源连接池名字是:"+dataSource.getPoolProperties().getName()); System.out.println(""); } }
26.08
88
0.697853
546cd5c12a843c2290be25877b4e41477fedf682
820
package ru.job4j.array; /** * @author Sergey Shpakovsky (shpaser2@yandex.ru) * @version $Id$ * @since 04.12.2018 */ public class BubbleSort { /** * Sort array by bubble algorithm. * * @param array array to bubble sort. * @return sorted array. */ public int[] sort(int[] array) { int arrayLength = array.length - 1; for (int indexCycle = arrayLength; indexCycle >= 1; indexCycle--) { for (int indexArray = 0; indexArray < indexCycle; indexArray++) { if (array[indexArray] > array[indexArray + 1]) { int buffer = array[indexArray]; array[indexArray] = array[indexArray + 1]; array[indexArray + 1] = buffer; } } } return array; } }
27.333333
77
0.528049
a3441fb0317ae6bd4eed93e5c44524ae0cc49721
1,014
package dataContracts; public class Product { public final boolean isTerminal; public final char symbol; public final long first, second; public Product(char symbol) { this.isTerminal = true; this.symbol = symbol; this.first = this.second = -1; } public Product(long first, long second) { this.isTerminal = false; this.symbol = 0; this.first = first; this.second = second; } @Override public boolean equals(Object object) { if (!(object instanceof Product)) return false; Product other = (Product) object; if (isTerminal != other.isTerminal) return false; if (isTerminal) return symbol == other.symbol; return first == other.first && second == other.second; } @Override public int hashCode() { return isTerminal ? symbol : (int) (first * 997 + second * 1000003); } }
24.142857
77
0.556213
c2bdc7264fc7afeaa63c16b31c779d2f960f3435
7,461
/** * The MIT License * Copyright (c) 2018 Estonian Information System Authority (RIA), * Nordic Institute for Interoperability Solutions (NIIS), Population Register Centre (VRK) * Copyright (c) 2015-2017 Estonian Information System Authority (RIA), Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ee.ria.xroad.common.db; import ee.ria.xroad.common.CodedException; import ee.ria.xroad.common.SystemProperties; import ee.ria.xroad.common.util.PrefixedProperties; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.internal.util.config.ConfigurationHelper; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static ee.ria.xroad.common.ErrorCodes.X_DATABASE_ERROR; /** * Hibernate utility methods. */ @Slf4j public final class HibernateUtil { @Data private static class SessionFactoryCtx { private final SessionFactory sessionFactory; } private HibernateUtil() { } private static Map<String, SessionFactoryCtx> sessionFactoryCache = new HashMap<>(); /** * Returns the session factory for the given session factory name. * If the session factory has not been already created, it is created and stored in the cache. * * @param name the name of the session factory * @return the session factory */ public static synchronized SessionFactory getSessionFactory(String name) { return getSessionFactory(name, null); } /** * Returns the session factory for the given session factory name. * If the session factory has not been already created, it is created and stored in the cache. * * @param name the name of the session factory * @param interceptor the interceptor to use on sessions created with this factory * @return the session factory */ public static synchronized SessionFactory getSessionFactory(String name, Interceptor interceptor) { if (sessionFactoryCache.containsKey(name)) { return sessionFactoryCache.get(name).getSessionFactory(); } else { try { SessionFactoryCtx ctx = createSessionFactoryCtx(name, interceptor); sessionFactoryCache.put(name, ctx); return ctx.getSessionFactory(); } catch (Exception e) { log.error("Failed to create session factory", e); throw new CodedException(X_DATABASE_ERROR, e); } } } /** * Closes the session factory. * * @param name the name of the session factory to close */ public static synchronized void closeSessionFactory(String name) { log.trace("closeSessionFactory({})", name); if (sessionFactoryCache.containsKey(name)) { closeSessionFactory(sessionFactoryCache.get(name)); sessionFactoryCache.remove(name); } } /** * Closes all session factories in the cache. Should be called when the main program exits. */ public static synchronized void closeSessionFactories() { log.trace("closeSessionFactories()"); Collection<SessionFactoryCtx> sessionFactories = new ArrayList<>(sessionFactoryCache.values()); for (SessionFactoryCtx ctx : sessionFactories) { closeSessionFactory(ctx); } sessionFactoryCache.clear(); } private static void closeSessionFactory(SessionFactoryCtx ctx) { try { ctx.getSessionFactory().getCurrentSession().close(); } catch (HibernateException e) { log.error("Error closing session", e); } try { ctx.getSessionFactory().close(); } catch (HibernateException e) { log.error("Error closing session factory", e); } } private static SessionFactoryCtx createSessionFactoryCtx(String name, Interceptor interceptor) throws Exception { log.trace("Creating session factory for '{}'...", name); Configuration configuration = new Configuration(); if (interceptor != null) { configuration.setInterceptor(interceptor); } configuration .configure() .configure(name + ".hibernate.cfg.xml"); applyDatabasePropertyFile(configuration, name); applySystemProperties(configuration, name); SessionFactory sessionFactory = configuration.buildSessionFactory(); return new SessionFactoryCtx(sessionFactory); } private static void applySystemProperties(Configuration configuration, String name) { final String prefix = name + ".hibernate."; for (String key : System.getProperties().stringPropertyNames()) { if (key.startsWith(prefix)) { configuration.setProperty(key.substring(name.length() + 1), System.getProperty(key)); } } } private static void applyDatabasePropertyFile(Configuration configuration, String name) throws IOException { try (InputStream in = new FileInputStream(SystemProperties.getDatabasePropertiesFile())) { final Properties extraProperties = new PrefixedProperties(name + "."); extraProperties.load(in); configuration.addProperties(extraProperties); } } /** * Returns Hibernate batch size value if configured, otherwise the given default value. * * @param session Hibernate session * @param defaultBatchSize default batch size * @return batch size */ public static int getConfiguredBatchSize(Session session, int defaultBatchSize) { final Properties props = ((SessionFactoryImpl) session.getSessionFactory()).getProperties(); int configuredBatchSize = ConfigurationHelper.getInt(Environment.STATEMENT_BATCH_SIZE, props, defaultBatchSize); log.trace("Configured JDBC batch size is {}", configuredBatchSize); return configuredBatchSize; } }
37.119403
120
0.693875
986f3b3b28d779d3bb4b4549a995ebb9026886c2
3,455
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.ml; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; // $example on$ import org.apache.spark.ml.classification.BinaryLogisticRegressionSummary; import org.apache.spark.ml.classification.LogisticRegression; import org.apache.spark.ml.classification.LogisticRegressionModel; import org.apache.spark.ml.classification.LogisticRegressionTrainingSummary; import org.apache.spark.sql.DataFrame; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.functions; // $example off$ public class JavaLogisticRegressionSummaryExample { public static void main(String[] args) { SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionSummaryExample"); JavaSparkContext jsc = new JavaSparkContext(conf); SQLContext sqlContext = new SQLContext(jsc); // Load training data DataFrame training = sqlContext.read().format("libsvm") .load("data/mllib/sample_libsvm_data.txt"); LogisticRegression lr = new LogisticRegression() .setMaxIter(10) .setRegParam(0.3) .setElasticNetParam(0.8); // Fit the model LogisticRegressionModel lrModel = lr.fit(training); // $example on$ // Extract the summary from the returned LogisticRegressionModel instance trained in the earlier // example LogisticRegressionTrainingSummary trainingSummary = lrModel.summary(); // Obtain the loss per iteration. double[] objectiveHistory = trainingSummary.objectiveHistory(); for (double lossPerIteration : objectiveHistory) { System.out.println(lossPerIteration); } // Obtain the metrics useful to judge performance on test data. // We cast the summary to a BinaryLogisticRegressionSummary since the problem is a binary // classification problem. BinaryLogisticRegressionSummary binarySummary = (BinaryLogisticRegressionSummary) trainingSummary; // Obtain the receiver-operating characteristic as a dataframe and areaUnderROC. DataFrame roc = binarySummary.roc(); roc.show(); roc.select("FPR").show(); System.out.println(binarySummary.areaUnderROC()); // Get the threshold corresponding to the maximum F-Measure and rerun LogisticRegression with // this selected threshold. DataFrame fMeasure = binarySummary.fMeasureByThreshold(); double maxFMeasure = fMeasure.select(functions.max("F-Measure")).head().getDouble(0); double bestThreshold = fMeasure.where(fMeasure.col("F-Measure").equalTo(maxFMeasure)) .select("threshold").head().getDouble(0); lrModel.setThreshold(bestThreshold); // $example off$ jsc.stop(); } }
40.647059
100
0.752243
55da6052e78cb62d72f573acbddbbb05f98bf030
478
package com.dl7.mvp.module.video.player; import com.dl7.mvp.local.table.DanmakuInfo; import com.dl7.mvp.local.table.VideoInfo; import com.dl7.mvp.module.base.ILocalPresenter; /** * Created by long on 2016/12/23. * Video Presenter */ public interface IVideoPresenter extends ILocalPresenter<VideoInfo> { /** * 添加一条弹幕到数据库 * @param danmakuInfo */ void addDanmaku(DanmakuInfo danmakuInfo); /** * 清空该视频所有缓存弹幕 */ void cleanDanmaku(); }
19.916667
69
0.690377
9bd1fe89a4665618fdc11f01b92aaf1486f92421
309
package com.l.smartcityuniversalmarket.http; import java.io.InputStream; public class HttpClient implements IHttpClient { @Override public InputStream get(IRequest request) { return null; } @Override public InputStream post(IRequest request) { return null; } }
18.176471
48
0.682848
143dcde61e3cfa6a01f153b5f581917eb9cda0ce
861
package tech.eduardosolano.movietime.Model; import java.io.Serializable; import java.util.ArrayList; import tech.eduardosolano.movietime.Api.Response.Result; public class DiscoverMovie implements Serializable{ private float total_results; private float total_pages; private ArrayList<Result> movies= new ArrayList<Result>(); public float getTotal_results() { return total_results; } public void setTotal_results(float total_results) { this.total_results = total_results; } public float getTotal_pages() { return total_pages; } public void setTotal_pages(float total_pages) { this.total_pages = total_pages; } public ArrayList<Result> getMovies() { return movies; } public void setMovies(ArrayList<Result> movies) { this.movies = movies; } }
22.076923
63
0.696864
5e4e43c83466e2905bb7c60c6aa18ff9c53d0c4e
2,055
package filemanager.harshapp.hm.fileexplorer.cast; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Menu; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import com.google.android.gms.cast.framework.CastButtonFactory; import com.google.android.gms.cast.framework.media.widget.ExpandedControllerActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import filemanager.harshapp.hm.fileexplorer.R; import filemanager.harshapp.hm.fileexplorer.misc.TintUtils; import filemanager.harshapp.hm.fileexplorer.setting.SettingsActivity; /** * Fullscreen media controls */ public class ExpandedControlsActivity extends ExpandedControllerActivity { @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setFitsSystemWindows(true); ImageView imageView = findViewById(R.id.background_place_holder_image_view); Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_root_image); TintUtils.tintDrawable(drawable, Color.WHITE); imageView.setImageDrawable(drawable); int color = SettingsActivity.getAccentColor(); int accentColor = SettingsActivity.getAccentColor(); ProgressBar progressBar = findViewById(R.id.loading_indicator); TintUtils.tintDrawable(progressBar.getIndeterminateDrawable(), accentColor); SeekBar seekBar = findViewById(R.id.seek_bar); TintUtils.tintWidget(seekBar, color); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_cast, menu); CastButtonFactory.setUpMediaRouteButton(this, menu, R.id.casty_media_route_menu_item); return true; } @Override public void onWindowFocusChanged(boolean b) { // super.onWindowFocusChanged(b); } }
34.830508
94
0.758637
e86f5c93bbe672d8f8dce6123b3c76e3e2e6c889
2,054
package org.mapdb; import org.junit.Before; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; /** * JUnit test case which provides JDBM specific staff */ abstract public class StorageTestCase extends TestFile{ Storage engine; @Before public void setUp() throws Exception { engine = openEngine(); } protected Storage openEngine() { return new StorageDirect(fac); } void reopenStore() { engine.close(); engine = openEngine(); } DataInput2 swap(DataOutput2 d){ byte[] b = d.copyBytes(); return new DataInput2(ByteBuffer.wrap(b),0); } int countIndexRecords(){ int ret = 0; final long indexFileSize = engine.index.getLong(StorageDirect.RECID_CURRENT_INDEX_FILE_SIZE*8); for(int pos = StorageDirect.INDEX_OFFSET_START * 8; pos<indexFileSize; pos+=8){ if(0!= engine.index.getLong(pos)){ ret++; } } return ret; } long getIndexRecord(long recid){ return engine.index.getLong(recid*8); } List<Long> getLongStack(long recid){ ArrayList<Long> ret =new ArrayList<Long>(); long pagePhysid = engine.index.getLong(recid*8) & StorageDirect.PHYS_OFFSET_MASK; while(pagePhysid!=0){ final byte numberOfRecordsInPage = engine.phys.getByte((int) (pagePhysid% Volume.BUF_SIZE)); for(int rec = numberOfRecordsInPage; rec>0;rec--){ final long l = engine.phys.getLong((int) (pagePhysid% Volume.BUF_SIZE+ rec*8)); ret.add(l); } //read location of previous page pagePhysid = engine.phys.getLong((int)(pagePhysid% Volume.BUF_SIZE)) & StorageDirect.PHYS_OFFSET_MASK; } return ret; } final List<Long> arrayList(long... vals){ ArrayList<Long> ret = new ArrayList<Long>(); for(Long l:vals){ ret.add(l); } return ret; } }
22.571429
114
0.590555
9d8f320cfb5d963dc3639fffcc4f3364973c0ed9
2,195
package app.hand; import app.card.Ace; import app.card.Card; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class HandTest { private static Hand hand; @Before public void setUp() throws Exception { hand = new Hand(); } @Test public void setValue() { hand.addCard(new Card(9, "SPADES")); hand.addCard(new Card(5, "SPADES")); assertEquals(14, hand.getValue()); assertEquals(14, hand.getLowAceValue()); assertEquals(14, hand.getHighAceValue()); } @Test public void setValueSoftWithAce() { hand.addCard(new Card(9, "SPADES")); hand.addCard(new Ace("SPADES")); assertEquals(20, hand.getValue()); assertEquals(20, hand.getHighAceValue()); assertEquals(10, hand.getLowAceValue()); } @Test public void setValueWithHardAce() { hand.addCard(new Card(9, "SPADES")); hand.addCard(new Card(9, "SPADES")); hand.addCard(new Ace("SPADES")); assertEquals(29, hand.getHighAceValue()); assertEquals(19, hand.getValue()); assertEquals(19, hand.getLowAceValue()); } @Test public void addCard() { } @Test public void getCard() { } @Test public void removeCard() { } @Test public void removeCard1() { } @Test public void getCards() { } @Test public void getValue() { } @Test public void getNumAces() { } @Test public void addAce() { } @Test public void checkBlackJack() { } @Test public void checkBust() { } @Test public void numCards() { } @Test public void isCardHidden() { } @Test public void canSplit() { } @Test public void withSoftAceMessage() { } @Test public void withHardAceMessage() { } @Test public void withoutAceMessage() { } @Test public void hiddenCardMessage() { } // // @Test // public void toString() { // } }
18.140496
50
0.536674
bff0dab03dcf98a258393ff4f91bfc1b315f63b2
13,787
package seedu.fast.logic.parser; import static java.util.Objects.requireNonNull; import static seedu.fast.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.fast.commons.core.Messages.MESSAGE_INVALID_HELP_COMMAND_FORMAT; import static seedu.fast.logic.parser.CliSyntax.PREFIX_INVESTMENT_PLAN_TAG; import static seedu.fast.logic.parser.CliSyntax.PREFIX_PRIORITY_TAG; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import seedu.fast.commons.core.index.Index; import seedu.fast.commons.util.StringUtil; import seedu.fast.logic.commands.HelpCommand; import seedu.fast.logic.parser.exceptions.HelpParseException; import seedu.fast.logic.parser.exceptions.ParseException; import seedu.fast.model.person.Address; import seedu.fast.model.person.Appointment; import seedu.fast.model.person.Email; import seedu.fast.model.person.Name; import seedu.fast.model.person.Phone; import seedu.fast.model.tag.InvestmentPlanTag; import seedu.fast.model.tag.PriorityTag; import seedu.fast.model.tag.Tag; /** * Contains utility methods used for parsing strings in the various *Parser classes. */ public class ParserUtil { public static final String MESSAGE_INVALID_INDEX = "Index is not a non-zero unsigned integer."; public static final String[] COMMAND_LIST = new String[]{"Quick Start", "Add", "Appointment", "Edit Appointment", "Delete Appointment", "Mark Appointment", "Clear", "Delete", "Edit", "Find", "List", "Help", "Remark", "Sort", "Statistics", "Tag", "Investment Plan Tag", "Priority Tag", "Misc"}; /** * Parses {@code oneBasedIndex} into an {@code Index} and returns it. Leading and trailing whitespaces will be * trimmed. * * @throws ParseException if the specified index is invalid (not non-zero unsigned integer). */ public static Index parseIndex(String oneBasedIndex) throws ParseException { String trimmedIndex = oneBasedIndex.trim(); if (!StringUtil.isNonZeroUnsignedInteger(trimmedIndex)) { throw new ParseException(MESSAGE_INVALID_INDEX); } return Index.fromOneBased(Integer.parseInt(trimmedIndex)); } /** * Parses a {@code String name} into a {@code Name}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static Name parseName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_CONSTRAINTS); } trimmedName = capitaliseNamesFirstLetters(trimmedName); return new Name(trimmedName); } /** * Takes in a {@code String trimmedName} and capitalises each letter * after a whitespace. * * @param trimmedName * @return trimmedName with capitalised words. */ private static String capitaliseNamesFirstLetters(String trimmedName) { char[] chars = trimmedName.toLowerCase().toCharArray(); if (Character.isLetter(chars[0])) { chars[0] = Character.toUpperCase(chars[0]); //Capitalise first letter } for (int i = 1; i < chars.length - 1; i++) { char current = chars[i]; char next = chars[i + 1]; if (Character.isWhitespace(current) && Character.isLetter(next)) { chars[i + 1] = Character.toUpperCase(next); } //Capitalise any letter after a whitespace } trimmedName = String.valueOf(chars); return trimmedName; } /** * Parses a {@code String phone} into a {@code Phone}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code phone} is invalid. */ public static Phone parsePhone(String phone) throws ParseException { requireNonNull(phone); String trimmedPhone = phone.trim(); if (!Phone.isValidPhone(trimmedPhone)) { throw new ParseException(Phone.MESSAGE_CONSTRAINTS); } return new Phone(trimmedPhone); } /** * Parses a {@code String address} into an {@code Address}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code address} is invalid. */ public static Address parseAddress(String address) throws ParseException { requireNonNull(address); String trimmedAddress = address.trim(); if (!Address.isValidAddress(trimmedAddress)) { throw new ParseException(Address.MESSAGE_CONSTRAINTS); } return new Address(trimmedAddress); } /** * Parses a {@code String email} into an {@code Email}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code email} is invalid. */ public static Email parseEmail(String email) throws ParseException { requireNonNull(email); String trimmedEmail = email.trim(); if (!Email.isValidEmail(trimmedEmail)) { throw new ParseException(Email.MESSAGE_CONSTRAINTS); } return new Email(trimmedEmail); } /** * Parses a {@code String tag} into a {@code Tag}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code tag} is invalid. */ public static Tag parseTag(String tag) throws ParseException { requireNonNull(tag); String trimmedTag = tag.trim(); if (!Tag.isValidTagTerm(trimmedTag)) { throw new ParseException(Tag.MESSAGE_CONSTRAINTS); } if (Tag.isSpecialTag(trimmedTag)) { throw new ParseException(Tag.MESSAGE_SPECIAL_TAG_ENTERED); } return Tag.createTag(trimmedTag); } /** * Parses {@code Collection<String> tags} into a {@code Set<Tag>}. */ public static Set<Tag> parseTags(Collection<String> tags) throws ParseException { requireNonNull(tags); final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(parseTag(tagName)); } return tagSet; } /** * Parses {@code String tagName} and returns the corresponding priority tag name. * * Input will always be a valid priority tag command, as validated by Tag::createTag * @param tagName The tag term to be parsed. * @return The corresponding tag name. */ public static String parsePriorityTag(String tagName) { String tagTerm = tagName.replace(PREFIX_PRIORITY_TAG.getPrefix(), ""); switch (tagTerm) { case PriorityTag.LowPriority.TERM: return PriorityTag.LowPriority.NAME; case PriorityTag.MediumPriority.TERM: return PriorityTag.MediumPriority.NAME; default: return PriorityTag.HighPriority.NAME; //It is guaranteed that the default case will always be a high priority tag instance. } } /** * Parses {@code String command} and returns the corresponding help command. */ public static String matchArgs(String command) { for (String s : COMMAND_LIST) { if (s.equals(command)) { return s; } } return ""; } /** * Extracts the arguments from a help command. * * @param commandText The input text. * @return The args of the help command, or "" if there is no or invalid args. * @throws HelpParseException if help is not followed by a valid arg */ public static String parseHelp(String commandText) throws HelpParseException { // if there are no args if (commandText.split(" ").length == 1) { return ""; } String arg = commandText.substring(HelpCommand.COMMAND_WORD.length()); String trimmedArgs = arg.trim(); String capitalisedArg = ParserUtil.capitaliseFirstLetters(trimmedArgs); if (!ParserUtil.matchArgs(capitalisedArg).equals("")) { return capitalisedArg; } else { // if the arg does not match a given command, throw exception throw new HelpParseException( String.format(MESSAGE_INVALID_HELP_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } } /** * Capitalise the start of each word in the args */ public static String capitaliseFirstLetters(String inputString) { String[] words = inputString.split(" "); StringBuilder capitalisedWordsBuilder = new StringBuilder(); for (String s : words) { // Capitalises the first letter of the word capitalisedWordsBuilder.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); capitalisedWordsBuilder.append(" "); } return capitalisedWordsBuilder.toString().trim(); } /** * Checks if the retrieved date from user input is valid. * * A valid date input is of the format yyyy-mm-dd. * `mm` is a 2-digit number in the range 01-12, which represents a calendar month. * `dd` is a 2-digit number in the range of 01-31, depending on the number of days in the calendar month. * * If the retrieved date is valid, returns the date in `dd MMM yyyy` format. * Otherwise, it means that the user did not enter the correct input. A ParseException will be thrown. * * @param date Date String retrieved from user input * @return A String representing the date in the specified format if it is valid (for add/update) * @throws ParseException Thrown when the date retrieved is invalid */ public static String parseDateString(String date) throws ParseException { try { checkDate(date); // converts the date to the specified format date = LocalDate.parse(date).format(DateTimeFormatter.ofPattern("dd MMM yyyy")); } catch (DateTimeParseException dtpe) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, Appointment.INVALID_DATE_INPUT), dtpe); } return date.trim(); } /** * Checks if the date input has already passed. * If date input is in the past, date is invalid, throws an error. * * @param date Input date string. * @throws ParseException Date input has passed. */ private static void checkDate(String date) throws ParseException { LocalDate localDate = LocalDate.parse(date); LocalDate now = LocalDate.now(); if (localDate.isBefore(now)) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, Appointment.PREVIOUS_DATE_INPUT)); } } /** * Checks if the retrieved time from user input is valid. * * A valid time input is of the format hh:mm (in 24-hour format). * `hh` is a 2-digit number in the range 00-23, which represents the hour in the 24-hour format. * `mm` is a 2-digit number in the range of 00-59, which represents the minute in the 24-hour format. * * If the retrieved time is valid, returns the time in `HHmm` format. * Otherwise, it means that the user did not enter the correct input. A ParseException will be thrown. * * @param time Time String retrieved from user input * @return A String representing the time in the specified format if it is valid. * @throws ParseException Thrown when the date retrieved is invalid */ public static String parseTimeString(String time) throws ParseException { String validationPattern = "^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$"; if (!time.equals(Appointment.NO_TIME)) { // checks that time only contains HH:mm and nothing else if (!time.matches(validationPattern)) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, Appointment.INVALID_TIME_INPUT)); } // converts the time to the specified format time = LocalTime.parse(time).format(DateTimeFormatter.ofPattern("HHmm")); } return time.trim(); } /** * Parses {@code String tagName} and returns the corresponding investment plan tag name. * * Input will always be a valid investment plan tag command, as validated by Tag::createTag * @param tagName The tag term to be parsed. * @return The corresponding tag name. */ public static String parseInvestmentPlanTag(String tagName) { String tagTerm = tagName.replace(PREFIX_INVESTMENT_PLAN_TAG.getPrefix(), ""); switch (tagTerm) { case InvestmentPlanTag.LifeInsurance.TERM: return InvestmentPlanTag.LifeInsurance.NAME; case InvestmentPlanTag.MotorInsurance.TERM: return InvestmentPlanTag.MotorInsurance.NAME; case InvestmentPlanTag.HealthInsurance.TERM: return InvestmentPlanTag.HealthInsurance.NAME; case InvestmentPlanTag.TravelInsurance.TERM: return InvestmentPlanTag.TravelInsurance.NAME; case InvestmentPlanTag.PropertyInsurance.TERM: return InvestmentPlanTag.PropertyInsurance.NAME; case InvestmentPlanTag.Investment.TERM: return InvestmentPlanTag.Investment.NAME; default: return InvestmentPlanTag.Savings.NAME; //it is guaranteed that the default case will always be an savings investment plan tag. } } }
39.279202
114
0.657503
c44b95f0496f07f67412cf33e83074463d1b4c4a
537
package functions; public class Tools { public int somar(int x, int y){ System.out.println(x + y); return x + y; } public int subtrair(int x, int y){ System.out.println(x - y); return x - y; } public int multiplicar(int x, int y){ System.out.println(x * y); return x * y; } public int dividir(int x, int y){ System.out.println(x / y); return x / y; } public static void main(String[] args){ Tools tools = new Tools(); } }
20.653846
43
0.527002
00f414a755c1efc927a419fcc1afc3d73a1da681
1,161
package com.codingpan.amazon; import edu.princeton.cs.algs4.StdOut; import java.util.*; public class OA20190322 { /** * https://www.1point3acres.com/bbs/thread-501911-1-1.html * * <p>order junction boxes * * <p>input: [ykc 82 */ public static void sortBoxes(List<String> boxList, int numberOfBoxes) { Collections.sort( boxList, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); } public static void main(String[] args) { String[] boxes = { "ykc 82 01", "eo first qpx", "09z cat hamster", "06f 12 25 6", "az0 first qpx", "236 cat dog rabbit snake" }; List<String> boxList = new ArrayList<String>(Arrays.asList(boxes)); // Utility.printList(boxList); sortBoxes(boxList, boxList.size()); for (String box : boxList) { StdOut.println(box); } } }
26.386364
75
0.490956
fc650d5542eadb44d7fd9c3f12e70740e2fd6b1e
4,741
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.platform; import android.graphics.Bitmap; import android.graphics.Rect; import com.facebook.common.references.CloseableReference; import com.facebook.imagepipeline.image.EncodedImage; import javax.annotation.Nullable; public interface PlatformDecoder { /** * Creates a bitmap from encoded bytes. Supports JPEG but callers should use {@link * #decodeJPEGFromEncodedImage} for partial JPEGs. In addition, a region to decode can be supplied * in order to minimize memory usage. NOTE: Not all platform decoders necessarily support * supplying specific regions. * * <p>Note: This needs to be kept because of dependencies issues. * * @param encodedImage the reference to the encoded image with the reference to the encoded bytes * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded * Bitmap * @param regionToDecode optional image region to decode or null to decode the whole image * @return the bitmap * @throws TooManyBitmapsException if the pool is full * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated */ CloseableReference<Bitmap> decodeFromEncodedImage( final EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode); /** * Creates a bitmap from encoded JPEG bytes. Supports a partial JPEG image. In addition, a region * to decode can be supplied in order to minimize memory usage. NOTE: Not all platform decoders * necessarily support supplying specific regions. * * <p>Note: This needs to be kept because of dependencies issues. * * @param encodedImage the reference to the encoded image with the reference to the encoded bytes * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded * Bitmap * @param regionToDecode optional image region to decode or null to decode the whole image. * @param length the number of encoded bytes in the buffer * @return the bitmap * @throws TooManyBitmapsException if the pool is full * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated */ CloseableReference<Bitmap> decodeJPEGFromEncodedImage( EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode, int length); /** * Creates a bitmap from encoded bytes. Supports JPEG but callers should use {@link * #decodeJPEGFromEncodedImage} for partial JPEGs. In addition, a region to decode can be supplied * in order to minimize memory usage. NOTE: Not all platform decoders necessarily support * supplying specific regions. * * @param encodedImage the reference to the encoded image with the reference to the encoded bytes * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded * Bitmap * @param regionToDecode optional image region to decode or null to decode the whole image * @param transformToSRGB whether to allow color space transformation to sRGB at load time * @return the bitmap * @throws TooManyBitmapsException if the pool is full * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated */ CloseableReference<Bitmap> decodeFromEncodedImageWithColorSpace( final EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode, final boolean transformToSRGB); /** * Creates a bitmap from encoded JPEG bytes. Supports a partial JPEG image. In addition, a region * to decode can be supplied in order to minimize memory usage. NOTE: Not all platform decoders * necessarily support supplying specific regions. * * @param encodedImage the reference to the encoded image with the reference to the encoded bytes * @param bitmapConfig the {@link android.graphics.Bitmap.Config} used to create the decoded * Bitmap * @param regionToDecode optional image region to decode or null to decode the whole image. * @param length the number of encoded bytes in the buffer * @param transformToSRGB whether to allow color space transformation to sRGB at load time * @return the bitmap * @throws TooManyBitmapsException if the pool is full * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated */ CloseableReference<Bitmap> decodeJPEGFromEncodedImageWithColorSpace( EncodedImage encodedImage, Bitmap.Config bitmapConfig, @Nullable Rect regionToDecode, int length, final boolean transformToSRGB); }
47.41
100
0.752795
05600456a79ab66722935b7dd6b84a547ee69cbc
88
package com.treehawkmods.agexpreborn; public class ServerProxy extends CommonProxy { }
17.6
46
0.829545
9fa6979569c0fa9bc5be4c613ee472580f46596f
793
package io.logregator.collector.tailer; import io.logregator.Aggregator; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; public class TailCollectorTest { private final Aggregator mockAggregator = mock(Aggregator.class); private final TailCollectorConfig config = TailCollectorConfigBuilder.builder().withPath("data/tailer/test.log").build(); private TailCollector tailer; @Before public void setup() throws IOException { tailer = new TailCollector(mockAggregator, config); } @Test public void testShouldBeWorking() { tailer.start(); assertThat(tailer.isWork(), is(true)); } }
27.344828
125
0.738966
102327ac7eb1732e9cd0a21e775c65e9e3edb42a
585
package com.xkcoding.exception.handler.exception; import com.xkcoding.exception.handler.constant.Status; import lombok.Getter; /** * <p> * 页面异常 * </p> * * @package: com.xkcoding.exception.handler.exception * @description: 页面异常 * @author: yangkai.shen * @date: Created in 2018/10/2 9:18 PM * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */ @Getter public class PageException extends BaseException { public PageException(Status status) { super(status); } public PageException(Integer code, String message) { super(code, message); } }
19.5
54
0.712821
39aa2399beb108a2106b78b51679929038834d1e
811
package com.shuhart.stepview.sample.examples.recyclerview; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.shuhart.stepview.sample.R; public class RecyclerViewExampleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); RecyclerView recyclerView = findViewById(R.id.recycler_view); DummyAdapter adapter = new DummyAdapter(); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); } }
36.863636
69
0.787916
f042e3b40fb9cb453041cbafdf9de2d748295573
20,677
/* * @(#)MonteCarloAlgorithmRefinement.java created 10/09/2006 Trento, Rosa's home * * Copyright (c) 1996-2006 Luca Lutterotti All Rights Reserved. * * This software is the research result of Luca Lutterotti and it is * provided as it is as confidential and proprietary information. * You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you * entered into with the author. * * THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE FOR ANY DAMAGES * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. * */ package it.unitn.ing.rista.comp; import it.unitn.ing.rista.interfaces.Function; import it.unitn.ing.rista.diffr.XRDcat; import it.unitn.ing.rista.diffr.FilePar; import it.unitn.ing.rista.util.Misc; import it.unitn.ing.rista.util.Constants; import it.unitn.ing.rista.awt.JOptionsDialog; import it.unitn.ing.xgridclient.XGridClient; import it.unitn.ing.xgridclient.Client; import javax.swing.*; import java.util.*; import java.awt.*; /** * The MonteCarloAlgorithmRefinement is a method to refine the spectrum * using a MonteCarlo Algorithm * * @author Luca Lutterotti * @version $Revision: 1.2 $, $Date: 2006/12/04 14:30:03 $ * @since JDK1.1 */ public class MonteCarloAlgorithmRefinement extends OptimizationAlgorithm { public static String[] diclistc = {"_riet_montecarlo_trials_number"}; public static String[] diclistcrm = {"Number of Montecarlo trials"}; public static String[] classlistc = {}; public static String[] classlistcs = {}; double[] defParams = null; double[] bestParams = null; double defWSS = 0.0; double bestWSS = 0.0; ec.util.MersenneTwisterFast randomizer = null; public MonteCarloAlgorithmRefinement(XRDcat aobj, String alabel) { super(aobj, alabel); initXRD(); identifier = "MonteCarlo Refinement"; IDlabel = "MonteCarlo Refinement"; description = "select this to use a MonteCarlo approach"; } public MonteCarloAlgorithmRefinement(XRDcat aobj) { this(aobj, "MonteCarlo Refinement"); } public MonteCarloAlgorithmRefinement() { identifier = "MonteCarlo Refinement"; IDlabel = "MonteCarlo Refinement"; description = "select this to use a MonteCarlo approach"; } public void initConstant() { Nstring = 1; Nstringloop = 0; Nparameter = 0; Nparameterloop = 0; Nsubordinate = 0; Nsubordinateloop = 0; } public void initDictionary() { for (int i = 0; i < totsubordinateloop; i++) diclist[i] = diclistc[i]; for (int i = 0; i < totsubordinateloop; i++) diclistRealMeaning[i] = diclistcrm[i]; for (int i = 0; i < totsubordinateloop - totsubordinate; i++) classlist[i] = classlistc[i]; for (int i = 0; i < totsubordinate - totparameterloop; i++) classlists[i] = classlistcs[i]; } public void initParameters() { super.initParameters(); setTrialsNumber("10000"); } public void setTrialsNumber(String value) { // System.out.println("Set trials:" + value) ; stringField[0] = value; } public String getTrialsNumber() { return stringField[0]; } public int getIntTrialsNumber() { return Integer.parseInt(getTrialsNumber()); } int actualThread = 0; Vector results = null; int divideRange = 1; int[] divideValue = null; String filesBase64; int startIndex = 0; boolean started = false; /* public void solveXGRID(launchBasic computation, Function funtionToMinimize) { if (funtionToMinimize instanceof FilePar) { fittingFunction = funtionToMinimize; int iterations = getIntNumberOfPopulations(); setNumberOfPopulations(1); // temporarly fittingFunction.prepareIteration(); nprm = fittingFunction.getNumberOfFreeParameters(); divideRange = ((FilePar) fittingFunction).checkForParRangeToDivide(); filesBase64 = ParallelComputationController.maudEssentialBase64; final String[] filesBase64ToSubmit = new String[2]; if (divideRange == 1) { filesBase64ToSubmit[0] = filesBase64; filesBase64ToSubmit[1] = ((FilePar) fittingFunction).getSavedFileAsBase64String(); } else { iterations = divideRange; } initAll(computation); if (outputframe != null) computation.hideIterationPanel(); if (outputframe != null) { outputframe.getProgressBar().setProgressBarValue(iterations); // computation.hideIterationPanel(); } defParams = new double[nprm]; lbound = new double[nprm]; ubound = new double[nprm]; divideValue = ((FilePar) fittingFunction).getRangeDivision(); for (int i = 0; i < nprm; i++) { defParams[i] = fittingFunction.getFreeParameter(i); lbound[i] = fittingFunction.getLowerBound(i); ubound[i] = fittingFunction.getUpperBound(i); // printf("Parameter, min, max : ", defParams[i], lbound[i], ubound[i]); } printf("Number of populations : ", iterations); actualThread = 0; results = new Vector(0, iterations); if (divideRange == 1) { for (int i = 0; i < iterations; i++) { (new PersistentThread() { public void executeJob() { actualThread++; boolean success = false; while (!success) { String resultData = XGridClient.submitJobAndWait("Maud_analysis", ParallelComputationController.xgridFilenames, filesBase64ToSubmit, ParallelComputationController.javaCommand, ParallelComputationController.javaArguments); if (!resultData.equals(Client.CANCELED) && !resultData.equals(Client.FAILED)) { success = true; StringTokenizer st = new StringTokenizer(resultData, " {}=,;:'\t\r\n"); String token = st.nextToken(); while (!token.equalsIgnoreCase("XGrid") && st.hasMoreTokens()) token = st.nextToken(); if (st.hasMoreTokens()) { token = st.nextToken(); // solution: token = st.nextToken(); double Rwp = Double.parseDouble(token); int i = 0; double[] newparameters = new double[nprm]; while (st.hasMoreTokens()) { token = st.nextToken(); newparameters[i++] = Float.parseFloat(token); } Result result = new Result(Rwp, newparameters); results.add(result); if (outputframe != null) { printf("Rwp = ", Rwp); printout(newparameters, newparameters.length); outputframe.increaseProgressBarValue(); } } } else { try { Thread.sleep(10000); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } } actualThread--; } }).start(); try { Thread.sleep(500); } catch (InterruptedException ie) { } } } else { double[] parameters = new double[nprm]; double[] lBounds = new double[nprm]; double[] uBounds = new double[nprm]; for (int i = 0; i < nprm; i++) { parameters[i] = (double) defParams[i]; lBounds[i] = lbound[i]; uBounds[i] = ubound[i]; // printf("Parameter, min, max : ", defParams[i], lbound[i], ubound[i]); } int boundsIndex = 0; int divideIndex = 0; startIndex = 0; startRecursiveSubmission(parameters, lBounds, uBounds, boundsIndex, divideIndex); } while (actualThread > 0) { try { Thread.sleep(500); } catch (InterruptedException ie) { } } Collections.sort(results, new bestSolution()); Result bestResult = (Result) results.firstElement(); if (outputframe != null) { printf("Best Rwp = ", bestResult.Rwp); printout(bestResult.parameters, bestResult.parameters.length); } fittingFunction.setFreeParameters(bestResult.parameters); if (divideRange > 1) { ((FilePar) fittingFunction).setParametersAndBounds(bestResult.parameters, lbound, ubound); } fittingFunction.computeFirstFit(); setNumberOfPopulations(iterations); // back to the correct value fittingFunction.setDerivate(false); } else solve(computation, fittingFunction); } public void startRecursiveSubmission(final double[] parameters, final double[] lBounds, final double[] uBounds, final int boundsIndex, final int divideIndex) { // for (boundsIndex = 0; boundsIndex < nprm; boundsIndex++) // for (divideIndex = 0; divideIndex < divideValue[boundsIndex]; divideIndex++) { // System.out.println(startIndex); lBounds[boundsIndex] = lbound[boundsIndex] + (ubound[boundsIndex] - lbound[boundsIndex]) * divideIndex / divideValue[boundsIndex]; uBounds[boundsIndex] = lbound[boundsIndex] + (ubound[boundsIndex] - lbound[boundsIndex]) * (divideIndex + 1) / divideValue[boundsIndex]; parameters[boundsIndex] = (double) ((uBounds[boundsIndex] + lBounds[boundsIndex]) / 2.0); // System.out.println(boundsIndex + " " + lbound[boundsIndex] + " " + ubound[boundsIndex] + " " + divideValue[boundsIndex] + " " // + divideIndex); // System.out.println(boundsIndex + " " + lBounds[boundsIndex] + " " + uBounds[boundsIndex] + " " + parameters[boundsIndex]); if (boundsIndex < nprm - 1) { int newBoundsIndex = boundsIndex + 1; if (newBoundsIndex < nprm) { for (int i = 0; i < divideValue[newBoundsIndex]; i++) { startRecursiveSubmission(parameters, lBounds, uBounds, newBoundsIndex, i); } } return; } started = false; (new PersistentThread() { public void executeJob() { actualThread++; String indexName = Integer.toString(startIndex++); String popName = "Maud_population_" + indexName; String resultData = null; ((FilePar) fittingFunction).setParametersAndBounds(parameters, lBounds, uBounds); String[] filesBase64ToSubmit = new String[2]; filesBase64ToSubmit[0] = filesBase64; filesBase64ToSubmit[1] = ((FilePar) fittingFunction).getSavedFileAsBase64String(); boolean first = true; boolean success = false; while (!success) { System.out.println("Submitting: " + popName); String clientName = "XGridClient_" + indexName; String jobId = XGridClient.submitJob(clientName, popName, ParallelComputationController.xgridFilenames, filesBase64ToSubmit, ParallelComputationController.javaCommand, ParallelComputationController.javaArguments); // we wait a little before starting retrieve the data if (!jobId.equals(Client.FAILED)) { if (first) { started = true; first = false; } while (!ParallelComputationController.retrieveData) { try { Thread.sleep(1000); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } resultData = XGridClient.getResults(clientName, jobId); System.out.println(resultData); if (!resultData.equals(Client.CANCELED) && !resultData.equals(Client.FAILED)) { success = true; StringTokenizer st = new StringTokenizer(resultData, " {}=,;'\t\r\n"); String token = st.nextToken(); while (!token.equalsIgnoreCase("XGrid") && st.hasMoreTokens()) token = st.nextToken(); if (st.hasMoreTokens()) { token = st.nextToken(); // solution: token = st.nextToken(); double Rwp = Double.parseDouble(token); int i = 0; double[] newparameters = new double[nprm]; while (st.hasMoreTokens()) { token = st.nextToken(); newparameters[i++] = Float.parseFloat(token); } Result result = new Result(Rwp, newparameters); results.add(result); if (outputframe != null) { printf("Rwp = ", Rwp); printout(newparameters, nprm); outputframe.increaseProgressBarValue(); } } } else { try { Thread.sleep(10000); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } } else { try { Thread.sleep(10000); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } } actualThread--; } }).start(); while (!started) { try { Thread.sleep(500); } catch (InterruptedException ie) { ie.printStackTrace(System.err); } } // } }*/ private class Result { public double Rwp = 1.0E33; public double[] parameters = null; public Result(double rwp, double[] pars) { Rwp = rwp; parameters = pars; } } class bestSolution implements Comparator { public int compare(Object obj1, Object obj2) { double Rwp1 = ((Result) obj1).Rwp; double Rwp2 = ((Result) obj2).Rwp; if (Rwp2 == Rwp1) { return 0; } else if (Rwp1 < Rwp2) return -1; return 1; } } public void solve(launchBasic computation, Function funtionTominimize) { setIterations(getIntTrialsNumber()); fittingFunction = funtionTominimize; int iterat = getIterations(); if (outputframe != null) computation.setIterationSliderValue(iterat); printf("Number of trials : ", iterat); // Init the randomizer for random number generation initAll(computation); // Generate the starting solution configuration generateStartingSolutions(); for (int i = 0; i < iterat; i++) { if (i > getIterations()) { printf("Iterations stopped!"); break; } if (computation != null && computation.shouldStop()) { endOfIterations(); fittingFunction.setDerivate(false); return; } computeSolution(); } endOfIterations(); fittingFunction.setDerivate(false); } int dataNumber = 0; /* double dta[] = null; double wgt[] = null; double fit[] = null; */ int nprm = 0; double lbound[] = null; double ubound[] = null; void initAll(launchBasic computation) { // getFilePar().prepareComputation(); fittingFunction.prepareIteration(); if (outputframe != null) { outputframe.getProgressBar().setProgressBarValue(getIntTrialsNumber()); // computation.hideIterationPanel(); } dataNumber = fittingFunction.getNumberOfData(); fittingFunction.computeFirstFit(); fittingFunction.getFit(); /* dta = new double[dataNumber]; wgt = new double[dataNumber]; fit = new double[dataNumber]; */ if (computation != null && computation.shouldStop()) { return; } /* for (int i = 0; i < dataNumber; i++) { dta[i] = fittingFunction.getData(i); wgt[i] = fittingFunction.getWeight(i); wgt[i] *= wgt[i]; fit[i] = fittingFunction.getFit(i); } */ defWSS = fittingFunction.getWSS(); nprm = fittingFunction.getNumberOfFreeParameters(); defParams = new double[nprm]; lbound = new double[nprm]; ubound = new double[nprm]; for (int i = 0; i < nprm; i++) { defParams[i] = fittingFunction.getFreeParameter(i); lbound[i] = fittingFunction.getLowerBound(i); ubound[i] = fittingFunction.getUpperBound(i); // System.out.println("Parameter, min, max : " + defParams[i] + " " + lbound[i] + " " + ubound[i]); printf("Parameter, min, max : ", defParams[i], lbound[i], ubound[i]); } printf("Wss = ", defWSS); if (computation != null && computation.shouldStop()) { return; } // fittingFunction.setDerivate(true); if (computation != null && computation.shouldStop()) { return; } bestParams = new double[defParams.length]; bestWSS = 1.0E50; for (int i = 0; i < bestParams.length; i++) bestParams[i] = defParams[i]; int time = (int) System.currentTimeMillis(); // safe because we're getting low-order bits randomizer = new ec.util.MersenneTwisterFast(time); } double randomGenerator() { double random = randomizer.nextDouble(); // while (random == 1.0) // escluding 1.0 // random = randomizer.nextDouble(); return random; } /** * return value between min and max excluded * * @param min * @param max * @return */ double randomGenerator(double min, double max) { return min + (max - min) * randomGenerator(); } void generateStartingSolutions() { } void computeSolution() { double[] pars = new double[nprm]; for (int i = 0; i < nprm; i++) { pars[i] = randomGenerator(lbound[i], ubound[i]); } double wss = getFitness(pars); } void endOfIterations() { if (bestWSS < defWSS) { fittingFunction.setFreeParameters(bestParams); fittingFunction.saveparameters(); fittingFunction.computeFit(); fittingFunction.getFit(); double wss = fittingFunction.getWSS(); if (fittingFunction instanceof FilePar) ((FilePar) fittingFunction).updatePlot(); System.out.println("Final chi :" + wss); } else { fittingFunction.setFreeParameters(defParams); fittingFunction.saveparameters(); fittingFunction.computeFit(); fittingFunction.getFit(); double wss = fittingFunction.getWSS(); if (fittingFunction instanceof FilePar) ((FilePar) fittingFunction).updatePlot(); System.out.println("Final chi :" + wss); } // structureFactorList = null; fittingFunction.computeFirstFit(); fittingFunction.getRefinementIndexes(); defParams = null; bestParams = null; } public double getFitness(double[] params) { fittingFunction.setFreeParameters(params); fittingFunction.computeFirstFit(); fittingFunction.getFit(); double wss = fittingFunction.getWSS(); if (outputframe != null) outputframe.increaseProgressBarValue(); if (wss < bestWSS) { bestWSS = wss; printf("Parameters values:"); printout(params, nprm); printf("Actual best wss :", wss); for (int i = 0; i < bestParams.length; i++) { bestParams[i] = params[i]; } if (fittingFunction instanceof FilePar) ((FilePar) fittingFunction).updatePlot(); } return wss; } public JOptionsDialog getOptionsDialog(Frame parent) { return new JMCSDPDOptionsD(parent, this); } public class JMCSDPDOptionsD extends JOptionsDialog { JTextField[] parsTF = null; JComboBox crossTypeCB = null; public JMCSDPDOptionsD(Frame parent, XRDcat obj) { super(parent, obj); principalPanel.setLayout(new BorderLayout(6, 6)); JPanel tfPanel = new JPanel(); tfPanel.setLayout(new GridLayout(0, 2, 3, 3)); principalPanel.add(BorderLayout.CENTER, tfPanel); String[] labels = { "Number of trials: "}; int numberFields = labels.length; parsTF = new JTextField[numberFields]; for (int i = 0; i < numberFields; i++) { tfPanel.add(new JLabel(labels[i])); tfPanel.add(parsTF[i] = new JTextField(12)); } setTitle("MonteCarlo refinement options panel"); initParameters(); pack(); } public void initParameters() { for (int i = 0; i < parsTF.length; i++) { // System.out.println(i); // System.out.println(parsTF[i]); // System.out.println(stringField[i]); parsTF[i].setText(stringField[i]); } } public void retrieveParameters() { for (int i = 0; i < parsTF.length; i++) stringField[i] = parsTF[i].getText(); } } }
33.242765
131
0.607438
491427e664d4dd7865c6a9904745bb0cd66a1baa
917
package com.example.user.ted_app_assignment_sly_v3.data.vo; import com.google.gson.annotations.SerializedName; public class TedSearchVO { @SerializedName("search_result_id") private int searchId; @SerializedName("title") private String title; @SerializedName("description") private String description; @SerializedName("imageUrl") private String imageUrl; @SerializedName("result_type") private String resultType; @SerializedName("result_id") private int resultId; public int getSearchId() { return searchId; } public String getTitle() { return title; } public String getDescription() { return description; } public String getImageUrl() { return imageUrl; } public String getResultType() { return resultType; } public int getResultId() { return resultId; } }
18.34
59
0.65867
63f62fee97f96851124b8a138a66966784dc2744
81
package examples.junit.serviceclass.categories; public interface Category1 { }
13.5
47
0.814815
83726eac8f57f977b7720b38182478d95b71b052
6,647
/* * Copyright 2019, Momentum Ideas Co. * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: structs/labtesting/TestResults.proto package io.opencannabis.schema.product.struct.testing; /** * <pre> * Enumerates taste or aroma notes, either based on subjective product testing or quantitative/empirical terpene * compound testing. * </pre> * * Protobuf enum {@code opencannabis.structs.labtesting.TasteNote} */ public enum TasteNote implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * No particular taste or aroma preference or value. * </pre> * * <code>NO_TASTE_PREFERENCE = 0;</code> */ NO_TASTE_PREFERENCE(0), /** * <pre> * "Sweet" taste/aroma note. * </pre> * * <code>SWEET = 1;</code> */ SWEET(1), /** * <pre> * "Sour" taste/aroma note. * </pre> * * <code>SOUR = 2;</code> */ SOUR(2), /** * <pre> * "Spice" taste/aroma note. * </pre> * * <code>SPICE = 3;</code> */ SPICE(3), /** * <pre> * "Smooth" taste/aroma note. * </pre> * * <code>SMOOTH = 4;</code> */ SMOOTH(4), /** * <pre> * "Citrus" taste/aroma note. * </pre> * * <code>CITRUS = 5;</code> */ CITRUS(5), /** * <pre> * "Pine" taste/aroma note. * </pre> * * <code>PINE = 6;</code> */ PINE(6), /** * <pre> * "Fruit" taste/aroma note. * </pre> * * <code>FRUIT = 7;</code> */ FRUIT(7), /** * <pre> * "Tropics" taste/aroma note. * </pre> * * <code>TROPICS = 8;</code> */ TROPICS(8), /** * <pre> * "Floral" taste/aroma note. * </pre> * * <code>FLORAL = 9;</code> */ FLORAL(9), /** * <pre> * "Herbal" taste/aroma note. * </pre> * * <code>HERB = 10;</code> */ HERB(10), /** * <pre> * "Earthy" taste/aroma note. * </pre> * * <code>EARTH = 11;</code> */ EARTH(11), UNRECOGNIZED(-1), ; /** * <pre> * No particular taste or aroma preference or value. * </pre> * * <code>NO_TASTE_PREFERENCE = 0;</code> */ public static final int NO_TASTE_PREFERENCE_VALUE = 0; /** * <pre> * "Sweet" taste/aroma note. * </pre> * * <code>SWEET = 1;</code> */ public static final int SWEET_VALUE = 1; /** * <pre> * "Sour" taste/aroma note. * </pre> * * <code>SOUR = 2;</code> */ public static final int SOUR_VALUE = 2; /** * <pre> * "Spice" taste/aroma note. * </pre> * * <code>SPICE = 3;</code> */ public static final int SPICE_VALUE = 3; /** * <pre> * "Smooth" taste/aroma note. * </pre> * * <code>SMOOTH = 4;</code> */ public static final int SMOOTH_VALUE = 4; /** * <pre> * "Citrus" taste/aroma note. * </pre> * * <code>CITRUS = 5;</code> */ public static final int CITRUS_VALUE = 5; /** * <pre> * "Pine" taste/aroma note. * </pre> * * <code>PINE = 6;</code> */ public static final int PINE_VALUE = 6; /** * <pre> * "Fruit" taste/aroma note. * </pre> * * <code>FRUIT = 7;</code> */ public static final int FRUIT_VALUE = 7; /** * <pre> * "Tropics" taste/aroma note. * </pre> * * <code>TROPICS = 8;</code> */ public static final int TROPICS_VALUE = 8; /** * <pre> * "Floral" taste/aroma note. * </pre> * * <code>FLORAL = 9;</code> */ public static final int FLORAL_VALUE = 9; /** * <pre> * "Herbal" taste/aroma note. * </pre> * * <code>HERB = 10;</code> */ public static final int HERB_VALUE = 10; /** * <pre> * "Earthy" taste/aroma note. * </pre> * * <code>EARTH = 11;</code> */ public static final int EARTH_VALUE = 11; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TasteNote valueOf(int value) { return forNumber(value); } public static TasteNote forNumber(int value) { switch (value) { case 0: return NO_TASTE_PREFERENCE; case 1: return SWEET; case 2: return SOUR; case 3: return SPICE; case 4: return SMOOTH; case 5: return CITRUS; case 6: return PINE; case 7: return FRUIT; case 8: return TROPICS; case 9: return FLORAL; case 10: return HERB; case 11: return EARTH; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<TasteNote> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< TasteNote> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<TasteNote>() { public TasteNote findValueByNumber(int number) { return TasteNote.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return io.opencannabis.schema.product.struct.testing.LabTesting.getDescriptor().getEnumTypes().get(4); } private static final TasteNote[] VALUES = values(); public static TasteNote valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TasteNote(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:opencannabis.structs.labtesting.TasteNote) }
21.37299
112
0.589288
d938dc710623086a76cc9fe837223d9104e38cee
484
package ru.atott.combiq.data.commands; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.ExitShellRequest; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.stereotype.Component; @Component public class ShellExitCommands implements CommandMarker { @CliCommand(value={"exit", "quit"}, help="Exits the shell") public ExitShellRequest quit() { return ExitShellRequest.NORMAL_EXIT; } }
30.25
63
0.789256
2f3c6da81dafdcf644f85161a649cf888fe33623
1,298
package com.vaani.leetcode.greedy; import java.util.Arrays; import java.util.PriorityQueue; /** * https://leetcode.com/problems/minimum-cost-to-connect-sticks/ * You have some sticks with positive integer lengths. * <p> * You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining. * <p> * Return the minimum cost of connecting all the given sticks into one stick in this way. * <p> * Example 1: * Input: sticks = [2,4,3] * Output: 14 * Explanation = 2 + 3 = 5 =>5, 5 + 4 = 14 * <p> * Example 2: * Input: sticks = [1,8,3,5] * Output: 30 * Explanation: 1 + 3 => 4, 4 + 5 = 13 => 13, 9 + 8 = 30 * <p> * Constraints: * <p> * 1 <= sticks.length <= 10^4 * 1 <= sticks[i] <= 10^4 */ public class MinimumCostToConnectSticks { public int connectSticks(int[] sticks) { if (sticks == null || sticks.length < 2) { return 0; } PriorityQueue<Integer> minHeap = new PriorityQueue<>(); Arrays.stream(sticks).forEach(minHeap::add); int cost = 0; while (minHeap.size() > 1) { int merge = minHeap.poll() + minHeap.poll(); cost += merge; minHeap.add(merge); } return cost; } }
26.489796
154
0.593991
88fcde771249517f24fdf3cc7ec8de459ae160a1
1,078
package ru.liahim.mist.client.renderer.entity; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.ResourceLocation; import ru.liahim.mist.client.model.entity.ModelWoodlouse; import ru.liahim.mist.common.Mist; import ru.liahim.mist.entity.EntityWoodlouse; public class RenderWoodlouse extends RenderLiving<EntityWoodlouse> { private static final ResourceLocation textureLoc[] = new ResourceLocation[] { new ResourceLocation(Mist.MODID, "textures/entity/woodlouse/woodlouse_1.png"), //0 new ResourceLocation(Mist.MODID, "textures/entity/woodlouse/woodlouse_2.png"), //1 new ResourceLocation(Mist.MODID, "textures/entity/woodlouse/woodlouse_3.png"), //2 new ResourceLocation(Mist.MODID, "textures/entity/woodlouse/woodlouse_4.png") //3 }; public RenderWoodlouse(RenderManager manager) { super(manager, new ModelWoodlouse(), 0.4375F); } @Override protected ResourceLocation getEntityTexture(EntityWoodlouse entity) { return textureLoc[entity.getColorType()]; } }
39.925926
85
0.798701
d0c1173646554a3687fab7de95c03e984639223a
838
package ch.awae.mytools.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfiguration implements WebMvcConfigurer { private final AuthorityRefreshingInterceptor authorityRefreshingInterceptor; @Autowired public WebConfiguration(AuthorityRefreshingInterceptor authorityRefreshingInterceptor) { this.authorityRefreshingInterceptor = authorityRefreshingInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authorityRefreshingInterceptor).addPathPatterns("/**"); } }
36.434783
92
0.825776
f9bb01b4d9b12f989144cefc469bc0c3187de303
1,584
package org.gradle.profiler.studio; import java.nio.file.Path; import java.util.List; import java.util.Map; public class LaunchConfiguration { private final Path javaCommand; private final List<Path> classPath; private final Map<String, String> systemProperties; private final String mainClass; private final Path agentJar; private final Path supportJar; private final List<Path> sharedJars; public LaunchConfiguration(Path javaCommand, List<Path> classPath, Map<String, String> systemProperties, String mainClass, Path agentJar, Path supportJar, List<Path> sharedJars) { this.javaCommand = javaCommand; this.classPath = classPath; this.systemProperties = systemProperties; this.mainClass = mainClass; this.agentJar = agentJar; this.supportJar = supportJar; this.sharedJars = sharedJars; } public Path getJavaCommand() { return javaCommand; } public List<Path> getClassPath() { return classPath; } public Map<String, String> getSystemProperties() { return systemProperties; } public String getMainClass() { return mainClass; } public Path getAgentJar() { return agentJar; } public Path getSupportJar() { return supportJar; } public List<Path> getSharedJars() { return sharedJars; } }
26.4
68
0.595328
54d09fdc8db1245608d7e94ca3dcc4b6a18bdfa3
1,620
package org.springframework.scheduling; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.quartz.QuartzJobBean; import java.lang.reflect.Method; public class MyDetailQuartzJobBean extends QuartzJobBean { protected final Log logger = LogFactory.getLog(getClass()); private String targetObject; private String targetMethod; private ApplicationContext ctx; protected void executeInternal(JobExecutionContext context) throws JobExecutionException { try { logger.info("execute [" + targetObject + "] at once>>>>>>"); Object oTargetObject = ctx.getBean(targetObject); Method m = null; try { m = oTargetObject.getClass().getMethod(targetMethod, new Class[]{}); m.invoke(oTargetObject, new Object[]{}); } catch (SecurityException e) { logger.error(e); } catch (NoSuchMethodException e) { logger.error(e); } } catch (Exception e) { throw new JobExecutionException(e); } } public void setApplicationContext(ApplicationContext applicationContext) { this.ctx = applicationContext; } public void setTargetObject(String targetObject) { this.targetObject = targetObject; } public void setTargetMethod(String targetMethod) { this.targetMethod = targetMethod; } }
32.4
94
0.672222
833f29cae88ae78997990ca0081374b69ee7347e
6,241
package Sort; import Util.MySqlUtil.mySqlJDBC; import net.librec.common.LibrecException; import net.librec.conf.Configuration; import net.librec.data.DataModel; import net.librec.data.model.JDBCDataModel; import net.librec.eval.EvalContext; import net.librec.eval.RecommenderEvaluator; import net.librec.eval.ranking.AUCEvaluator; import net.librec.eval.ranking.AveragePrecisionEvaluator; import net.librec.eval.ranking.NormalizedDCGEvaluator; import net.librec.eval.ranking.PrecisionEvaluator; import net.librec.recommender.Recommender; import net.librec.recommender.RecommenderContext; import net.librec.recommender.cf.BUCMRecommender; import net.librec.recommender.item.RecommendedItem; import net.librec.similarity.CosineSimilarity; import net.librec.similarity.RecommenderSimilarity; import org.apache.thrift.TException; import org.apache.thrift.transport.TTransportException; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.*; public class BUCM implements Sort { @Override public void train() { } @Override public Map<String, Double> predict(String paper_id) { return null; } public static void saveResult(List<RecommendedItem> recommendedList) throws LibrecException, IOException, ClassNotFoundException, TException, SQLException { Map<String, List<String>> uid2items = new HashMap<>(); if (recommendedList != null && recommendedList.size() > 0) { // convert itemList to string StringBuilder sb = new StringBuilder(); for (RecommendedItem recItem : recommendedList) { String userId = recItem.getUserId(); String itemId = recItem.getItemId(); List<String> tmp = null; if (!uid2items.containsKey(userId)) { //进行初始化 tmp = new ArrayList<>(); } else { tmp = uid2items.get(userId); } tmp.add(itemId); uid2items.put(userId, tmp); } for (String uid : mySqlJDBC.getInstance().getUserIds()) { List<String> papers = uid2items.get(uid); String item_ids = String.join(",", papers.toArray(new String[0])); String sql = String.format("UPDATE user_rec SET dnn_sort = \"%s\" WHERE user_id = %s;\n", item_ids, uid); mySqlJDBC.getInstance().write(sql); } } } @Override public void run() throws IOException, LibrecException { InputStream inputStream = new FileInputStream("src/main/resources/config.properties"); Properties properties = new Properties(); properties.load(inputStream); String URL = properties.getProperty("jdbc.url"); String DRIVER = properties.getProperty("jdbc.driver"); String USER = properties.getProperty("jdbc.username"); String PASSWORD = properties.getProperty("jdbc.password"); Configuration conf = new Configuration(); conf.set("data.convert.jbdc.driverName", DRIVER); conf.set("data.convert.jbdc.URL", URL); conf.set("data.convert.jbdc.user", USER); conf.set("data.convert.jbdc.password", PASSWORD); conf.set("data.convert.jbdc.tableName", "click_log"); conf.set("data.convert.jbdc.userColName", "u_id"); conf.set("data.convert.jbdc.itemColName", "item_id"); conf.set("data.convert.jbdc.ratingColName", "event_type"); conf.set("data.column.format", "UIR"); conf.set("data.model.splitter", "ratio"); conf.set("data.splitter.trainset.ratio", "0.8"); conf.set("data.splitter.ratio", "rating"); DataModel dataModel = new JDBCDataModel(conf); dataModel.buildDataModel(); RecommenderContext context = new RecommenderContext(conf, dataModel); // build similarity,没有相似度的模型,不需要设置这些 conf.set("rec.recommender.similarity.key", "item"); conf.setBoolean("rec.recommender.isranking", true); conf.setInt("rec.similarity.shrinkage", 10); RecommenderSimilarity similarity = new CosineSimilarity(); similarity.buildSimilarityMatrix(dataModel); context.setSimilarity(similarity); // bulid recommender,需要用什么模型,这里就new什么模型,设置相应的参数 conf.set("rec.neighbors.knn.number", "200"); Recommender recommender = new BUCMRecommender(); recommender.setContext(context); // train,进行训练 recommender.train(context); // evaluate result,评估结果 EvalContext evalContext = new EvalContext(conf, recommender, dataModel.getTestDataSet()); RecommenderEvaluator ndcgEvaluator = new NormalizedDCGEvaluator(); ndcgEvaluator.setTopN(10); double ndcgValue = ndcgEvaluator.evaluate(evalContext); System.out.println("NDCG:" + ndcgValue); RecommenderEvaluator aucEvaluator = new AUCEvaluator(); aucEvaluator.setTopN(10); double auc = aucEvaluator.evaluate(evalContext); System.out.println("AUC:" + auc); RecommenderEvaluator precisionEvaluator = new PrecisionEvaluator(); precisionEvaluator.setTopN(10); double pre = precisionEvaluator.evaluate(evalContext) ; System.out.println("Precision:" + pre); RecommenderEvaluator APEvaluator = new AveragePrecisionEvaluator(); APEvaluator.setTopN(10); double AP = APEvaluator.evaluate(evalContext); System.out.println("AP:" + AP); List<RecommendedItem> recommendedItemList = recommender.getRecommendedList(recommender.recommendRank());//得到原来的推荐结果 //保存过滤后的结果 try { saveResult(recommendedItemList); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } catch (TTransportException e) { e.printStackTrace(); } catch (TException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public static void main(String[] args) throws IOException, LibrecException { BUCM fm = new BUCM(); fm.run(); } }
39.751592
160
0.660151
50174301021b2f746590828363615d80917ba997
2,232
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Pacote br.faetec.model.dao @author Antonio Cassiano **/ package br.faetec.model.dao; import br.faetec.model.dto.CargoDTO; import java.util.List; import javax.persistence.Query; import org.eclipse.persistence.config.HintValues; import org.eclipse.persistence.config.QueryHints; /** * Implementa os métodos para manipulação da tabela cargo no banco de dados. @author Antonio Cassiano **/ public class CargoDAO { /** * Recupera todos os registros da tabela cargo. @author Antonio Cassiano @return List - Lista preenchida com cargos. **/ public List listar() { Query query = Database.manager.createNamedQuery("CargoDTO.findAll"); query.setHint(QueryHints.MAINTAIN_CACHE, HintValues.FALSE);// evita consulta em cache List lista = query.getResultList(); return lista; } /** * Recupera um registro da tabela cargo, com base no valor da chave primária. @author Antonio Cassiano @param cargoDTO @return CargoDTO - preenchido com o registro selecionado. **/ public CargoDTO selecionar(CargoDTO cargoDTO) { return (CargoDTO) Database.manager.find(CargoDTO.class, cargoDTO.getIdCargo()); } /** * Grava um registro na tabela cargo se Idcargo igual a zero, caso contrario atualiza o registro. @author Antonio Cassiano @param cargoDTO **/ public void gravar(CargoDTO cargoDTO) { Database.manager.getTransaction().begin(); if (cargoDTO.getIdCargo() == 0) { Database.manager.persist(cargoDTO); // gravar } else { Database.manager.merge(cargoDTO); // atualizar } Database.manager.getTransaction().commit(); } /** * Exclui um registro da tabela cargo, com base no valor da chave primária. @author Antonio Cassiano @param cargoDTO **/ public void excluir(CargoDTO cargoDTO) { Database.manager.getTransaction().begin(); Database.manager.remove(Database.manager.find(CargoDTO.class, cargoDTO.getIdCargo())); Database.manager.getTransaction().commit(); } }
30.575342
101
0.667563
0cdc630fc32a52fcd8eeca4f5eb83e28b22b7841
1,464
package com.jpattern.gwt.client.communication.direct; import com.jpattern.gwt.client.IApplicationProvider; import com.jpattern.gwt.client.communication.AProxy; import com.jpattern.gwt.client.communication.ICallbackAction; import com.jpattern.gwt.client.logger.ILogger; import com.jpattern.shared.result.facade.ICommandFacadeResult; /** * * @author Francesco Cina' * * @param <T> */ public class PutProxy<T extends ICommandFacadeResult<?>,Z> extends AProxy<T> { private final String url; private final Z data; private final IServerCallPutAction serverCallPostAction; private final Class<T> resultClass; private final Class<Z> dataClass; public PutProxy(IServerCallPutAction serverCallPostAction, Class<T> resultClass, Class<Z> dataClass, ICallbackAction<T> callbackAction, String url, Z data, IApplicationProvider provider) { super(callbackAction, provider); this.serverCallPostAction = serverCallPostAction; this.resultClass = resultClass; this.dataClass = dataClass; this.url=url; this.data = data; } @Override protected void execute(ICallbackAction<T> callbackAction, IApplicationProvider provider) throws Exception { ILogger logger = provider.getLoggerService().getLogger(this.getClass()); logger.info("execute", "Begin execute - call URL " + url); try { callbackAction.onSuccess( serverCallPostAction.put(resultClass, dataClass, url, data), 0); } catch (Exception e) { callbackAction.onError(e ,0); } } }
31.826087
189
0.771858
19da9c96914f89f19c86c0db3d2542a60bc41f1a
196
package com.excilys.db.exception; public class ComputerNameStrangeException extends Exception { /** * */ private static final long serialVersionUID = 5203450451940926398L; }
17.818182
70
0.719388
e6daea4023231277c269a7eef9d294fc1edff46f
513
package com.sciatta.openmall.shared.pojo.enums; /** * Created by yangxiaoyu on 2021/8/10<br> * All Rights Reserved(C) 2017 - 2021 SCIATTA<br><p/> * OrderStatus */ public enum OrderStatus { WAIT_PAY(10, "待付款"), WAIT_DELIVER(20, "已付款,待发货"), WAIT_RECEIVE(30, "已发货,待收货"), SUCCESS(40, "交易成功"), CLOSE(50, "交易关闭"); public final Integer type; public final String value; OrderStatus(Integer type, String value) { this.type = type; this.value = value; } }
22.304348
53
0.619883
36294beafeb94560224e5e71702df1efc4095aa7
4,933
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.trinidadinternal.ui.collection; import org.apache.myfaces.trinidadinternal.ui.MutableUINode; import org.apache.myfaces.trinidadinternal.ui.UIXRenderingContext; import org.apache.myfaces.trinidadinternal.ui.UINode; import org.apache.myfaces.trinidad.logging.TrinidadLogger; /** * UINodeList that retrieves its list of children from a UINode. * <p> * @version $Name: $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/ui/collection/UINodeUINodeList.java#0 $) $Date: 10-nov-2005.18:57:37 $ * @deprecated This class comes from the old Java 1.2 UIX codebase and should not be used anymore. */ @Deprecated public abstract class UINodeUINodeList implements UINodeList { protected abstract UINode getUINode(UIXRenderingContext context); protected UIXRenderingContext getRenderingContext(UIXRenderingContext context) { return context; } protected MutableUINode getMutableUINode() { UINode node = getUINode(null); if (node instanceof MutableUINode) { return (MutableUINode)node; } else { return null; } } public int size( UIXRenderingContext context ) { UINode node = getUINode(context); if (node != null) { context = getRenderingContext(context); return node.getIndexedChildCount(context); } else { return 0; } } public UINode getUINode( UIXRenderingContext context, int index ) { UINode node = getUINode(context); if (node != null) { context = getRenderingContext(context); return node.getIndexedChild(context, index); } else { return null; } } public UINode setUINode( int index, UINode node ) { MutableUINode mutableNode = getMutableUINode(); if (mutableNode != null) { UINode returnNode = mutableNode.getIndexedChild(null, index); mutableNode.replaceIndexedChild(index, node); return returnNode; } else { throw new UnsupportedOperationException(_LOG.getMessage( "ILLEGAL_TO_SET_CHILDREN", _getClassName())); } } public void addUINode( int index, UINode node ) { MutableUINode mutableNode = getMutableUINode(); if (mutableNode != null) { mutableNode.addIndexedChild(index, node); } else { throw new UnsupportedOperationException(_LOG.getMessage( "ILLEGAL_TO_ADD_CHILDREN", _getClassName())); } } public void addUINode( UINode node ) { MutableUINode mutableNode = getMutableUINode(); if (mutableNode != null) { mutableNode.addIndexedChild(node); } else { throw new UnsupportedOperationException(_LOG.getMessage( "ILLEGAL_TO_ADD_CHILDREN", _getClassName())); } } public UINode removeUINode( int index ) { MutableUINode mutableNode = getMutableUINode(); if (mutableNode != null) { return mutableNode.removeIndexedChild(index); } else { throw new UnsupportedOperationException(_LOG.getMessage( "ILLEGAL_TO_REMOVE_CHILDREN", _getClassName())); } } public void clearUINodes() { MutableUINode mutableNode = getMutableUINode(); if (mutableNode != null) { mutableNode.clearIndexedChildren(); } else { throw new UnsupportedOperationException(_LOG.getMessage( "ILLEGAL_TO_REMOVE_CHILDREN", _getClassName())); } } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException cnse) { // this should never happen throw new InternalError(); } } private String _getClassName() { String name = getClass().getName(); int indexOfPeriod = name.lastIndexOf('.'); if (indexOfPeriod < 0) return name; return name.substring(indexOfPeriod + 1); } private static final TrinidadLogger _LOG = TrinidadLogger.createTrinidadLogger( UINodeUINodeList.class); }
23.716346
175
0.667342
0854d6228d3ffa58de524732f5b3e5b5fd598777
4,361
/* * Copyright 2016 OPEN TONE 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 jp.co.opentone.bsol.linkbinder.dto; import java.util.Date; import jp.co.opentone.bsol.framework.core.dao.VersioningEntity; import jp.co.opentone.bsol.framework.core.util.CloneUtil; /** * 承認フローテンプレートユーザー. * * @author opentone * */ public class WorkflowTemplateUser extends AbstractDto implements VersioningEntity { /** * serialVersionUID. */ private static final long serialVersionUID = 3308969234758594196L; /** * ID. */ private Long id; /** * プロジェクトID. */ private String projectId; /** * ユーザー. */ private User user; /** * テンプレート名. */ private String name; /** * 作成者名. */ private User createdBy; /** * 作成日. */ private Date createdAt; /** * 更新者. */ private User updatedBy; /** * 更新日. */ private Date updatedAt; /** * バージョンナンバー. */ private Long versionNo; /** * 削除ナンバー. */ private Long deleteNo; /** * IDを返す. * @return ID */ public Long getId() { return id; } /** * IDを設定する. * @param id ID */ public void setId(Long id) { this.id = id; } /** * プロジェクトIDを返す. * @return the projectId */ public String getProjectId() { return projectId; } /** * プロジェクトIDを設定する. * @param projectId プロジェクトID */ public void setProjectId(String projectId) { this.projectId = projectId; } /** * ユーザー. * @return ユーザー */ public User getUser() { return user; } /** * ユーザーを設定する. * @param user ユーザー */ public void setUser(User user) { this.user = user; } /** * テンプレート名を返す. * @return テンプレート名 */ public String getName() { return name; } /** * テンプレート名を設定する. * @param name テンプレート名 */ public void setName(String name) { this.name = name; } /** * 作成者を返す. * @return 作成者 */ public User getCreatedBy() { return createdBy; } /** * 作成者を設定する. * @param createdBy 作成者 */ public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } /** * 作成日を返す. * @return 作成日 */ public Date getCreatedAt() { return CloneUtil.cloneDate(createdAt); } /** * 作成日を設定する. * @param createdAt 作成日 */ public void setCreatedAt(Date createdAt) { this.createdAt = CloneUtil.cloneDate(createdAt); } /** * 更新者を返す. * @return 更新者 */ public User getUpdatedBy() { return updatedBy; } /** * 更新者を設定する. * @param updatedBy 更新者 */ public void setUpdatedBy(User updatedBy) { this.updatedBy = updatedBy; } /** * 更新日を返す. * @return the updatedAt */ public Date getUpdatedAt() { return CloneUtil.cloneDate(updatedAt); } /** * 更新日を設定する. * @param updatedAt the updatedAt to set */ public void setUpdatedAt(Date updatedAt) { this.updatedAt = CloneUtil.cloneDate(updatedAt); } /** * バージョンナンバーを返す. * @return the versionNo */ public Long getVersionNo() { return versionNo; } /** * バージョンナンバーを設定する. * @param versionNo バージョンナンバー */ public void setVersionNo(Long versionNo) { this.versionNo = versionNo; } /** * 削除ナンバーを返す. * @return 削除ナンバー */ public Long getDeleteNo() { return deleteNo; } /** * 削除ナンバーを設定する. * @param deleteNo 削除ナンバー */ public void setDeleteNo(Long deleteNo) { this.deleteNo = deleteNo; } }
17.584677
83
0.550791
ffe8781fd5c2a0c1fcf49c507486b14e0e4cec40
406
package br.com.centralit.citquestionario.util; public class DynamicFormJavascriptBean { private String functionName; private String corpo; public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public String getCorpo() { return corpo; } public void setCorpo(String corpo) { this.corpo = corpo; } }
21.368421
51
0.761084
485300abb86426ba260afc88871bfe76b49a92c1
1,479
package com.enonic.harvest.harvestclient.models; import com.enonic.harvest.harvestclient.exceptions.HarvestClientException; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @XmlRootElement(name = "users") @XmlAccessorType(XmlAccessType.NONE) public class UserCollection implements Iterable<User> { @XmlElement(name = "user") private List<User> list = new ArrayList<User>(); public List<User> getList() { return list; } public void setList(List<User> list) { this.list = list; } public static UserCollection fromInputStream(final InputStream xml) throws HarvestClientException { try { JAXBContext context = JAXBContext.newInstance(UserCollection.class); Unmarshaller unmarshaller = context.createUnmarshaller(); return (UserCollection) unmarshaller.unmarshal(xml); } catch (Exception e) { throw new HarvestClientException("Unable to parse XML into UserCollection.", e); } } @Override public Iterator<User> iterator() { return this.list.iterator(); } }
26.410714
92
0.69236
2ee99fed15ba2305b5f93d0f01e75f0bc5eeb736
453
package com.autentia.example.micronaut.todo; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; class TodoTest { private static final LocalDateTime TS = LocalDateTime.now(); @Test void equals() { final var todo1 = new Todo(1, "title", TS, null); final var todo2 = new Todo(1, "title", TS, null); assertEquals(todo1, todo2); } }
20.590909
64
0.677704
b6e462e186eb552d6e8e5b722a50bbbe34862bd5
1,182
package com.qa.JavaInterviewPrograms; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * Count occurances of a character in String * by using HashMap & toCharArray() - similar approach as in DuplicateCharacterInString.java * by using for loop & charAt(int index) * by using toCharArray & for loop */ public class OccuranceOfCharacterInString { //Initialize Log4j instance private static final Logger log = LogManager.getLogger(OccuranceOfCharacterInString.class); public static void test() { duplicate("Hi, this is a test message to test the program", 't'); } public static void duplicate(String s, char c) { int count=0, counter=0; if(s==null) return; if(s.isEmpty()) return; for(int i=0; i<s.length(); i++){ if(s.charAt(i) == c){ count++; } } System.out.println(c + " : " + count); char chs[] = s.toCharArray(); for(Character ch : chs){ if(ch == c){ counter++; } } System.out.println(c + " : " + counter); } }
24.122449
93
0.576988
2769288ce2853ae70412abbc749815e65f30b937
726
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:paascloud快速搭建企业级分布式微服务平台 * 类名称:OAuth2ClientProperties.java * 创建人:刘兆明 * 联系方式:paascloud.net@gmail.com * 开源地址: https://github.com/paascloud * 博客地址: http://blog.paascloud.net * 项目官网: http://paascloud.net */ package com.paascloud.config.properties; import lombok.Data; /** * 认证服务器注册的第三方应用配置项 * * @author paascloud.net @gmail.com */ @Data public class OAuth2ClientProperties { /** * 第三方应用appId */ private String clientId; /** * 第三方应用appSecret */ private String clientSecret; /** * 针对此应用发出的token的有效时间 */ private int accessTokenValidateSeconds = 7200; private int refreshTokenValiditySeconds = 2592000; private String scope; }
17.285714
57
0.717631
3bcbf8f66a1d31d1ca3e5ccba40a9dbaaea3f3bc
440
package test1.objective02.exercise11; public class Test11 { private Object o; void doSomething(Object s){ o = s; } public static void main(String[] args) { Object obj = new Object(); // 1 Test11 tc = new Test11(); //2 tc.doSomething(obj); //3 obj = new Object(); //4 obj = null; //5 tc.doSomething(obj); //6 Before this line the object (Object) is being pointed to by at least one variable. } }
25.882353
112
0.625
01ede0a11540482d64463a445590e401f5686647
1,600
/* * Copyright © 2021 Cask Data, 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.cdap.cdap.support.module; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import io.cdap.cdap.common.conf.Constants.SupportBundle; import io.cdap.cdap.support.task.factory.SupportBundlePipelineInfoTaskFactory; import io.cdap.cdap.support.task.factory.SupportBundleSystemLogTaskFactory; import io.cdap.cdap.support.task.factory.SupportBundleTaskFactory; /** * Support bundle module to bind factories */ public class SupportBundleModule extends AbstractModule { @Override protected void configure() { Multibinder<SupportBundleTaskFactory> supportBundleTaskFactoryMultibinder = Multibinder.newSetBinder( binder(), SupportBundleTaskFactory.class, Names.named(SupportBundle.TASK_FACTORY)); supportBundleTaskFactoryMultibinder.addBinding().to(SupportBundlePipelineInfoTaskFactory.class); supportBundleTaskFactoryMultibinder.addBinding().to(SupportBundleSystemLogTaskFactory.class); } }
40
105
0.79625
10ef7b6835420278086c9bc768d009f4a168f257
485
package TranslateTTS; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; public class TextToSpeech { private String VoiceName ;// "kevin"; public void speak(String word,String name){ this.VoiceName = name; Voice voice = VoiceManager.getInstance().getVoice(VoiceName); voice.allocate(); try{ voice.speak(word); }catch(Exception ex){ System.out.println(ex); } } }
22.045455
69
0.62268
92ba50e1411a205c138669a8f07b481b68e66706
3,834
package com.github.ocraft.s2client.protocol.spatial; /*- * #%L * ocraft-s2client-protocol * %% * Copyright (C) 2017 - 2018 Ocraft Project * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import SC2APIProtocol.Common; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import static com.github.ocraft.s2client.protocol.Constants.nothing; import static com.github.ocraft.s2client.protocol.Fixtures.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class Size2dITest { @Test void throwsExceptionWhenSc2ApiSize2dIIsNull() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Size2dI.from(nothing())) .withMessage("sc2api size2dI is required"); } @Test void convertsAllFieldsFromSc2ApiSize2dI() { assertThatAllFieldsAreConverted(Size2dI.from(sc2ApiSize2dI())); } private void assertThatAllFieldsAreConverted(Size2dI size2dI) { assertThat(size2dI.getX()).as("size2dI: x").isEqualTo(SCREEN_SIZE_X); assertThat(size2dI.getY()).as("size2dI: y").isEqualTo(SCREEN_SIZE_Y); } @Test void throwsExceptionWhenXIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Size2dI.from(without( () -> sc2ApiSize2dI().toBuilder(), Common.Size2DI.Builder::clearX).build())) .withMessage("x is required"); } @Test void throwsExceptionWhenYIsNotProvided() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Size2dI.from(without( () -> sc2ApiSize2dI().toBuilder(), Common.Size2DI.Builder::clearY).build())) .withMessage("y is required"); } @Test void serializesToSc2ApiSize2dI() { Common.Size2DI sc2ApiSize2dI = Size2dI.of(10, 20).toSc2Api(); assertThat(sc2ApiSize2dI.getX()).as("sc2api size2di: x").isEqualTo(10); assertThat(sc2ApiSize2dI.getY()).as("sc2api size2di: Y").isEqualTo(20); } @Test void throwsExceptionWhenSize2dIIsNotInValidRange() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Size2dI.of(-1, 1)) .withMessage("size2di [x] has value -1 and is lower than 0"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> Size2dI.of(1, -1)) .withMessage("size2di [y] has value -1 and is lower than 0"); } @Test void fulfillsEqualsContract() { EqualsVerifier.forClass(Size2dI.class).verify(); } }
39.525773
80
0.68362
83d8a113b65d669a1fc79f722746b4f8c1ede544
923
package com.blossomproject.autoconfigure.ui.common.privileges; import com.blossomproject.core.common.utils.privilege.Privilege; import com.blossomproject.core.common.utils.privilege.SimplePrivilege; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FileManagerPrivilegesConfiguration { @Bean public Privilege fileManagerReadPrivilegePlugin() { return new SimplePrivilege("content", "filemanager", "read"); } @Bean public Privilege fileManagerWritePrivilegePlugin() { return new SimplePrivilege("content", "filemanager", "write"); } @Bean public Privilege fileManagerCreatePrivilegePlugin() { return new SimplePrivilege("content", "filemanager", "create"); } @Bean public Privilege fileManagerDeletePrivilegePlugin() { return new SimplePrivilege("content", "filemanager", "delete"); } }
29.774194
70
0.780065
fd4c2d2c7f200bd26b12d38c7ccacbe6a315b39b
14,779
package com.lhstack.controller.permission; import com.github.pagehelper.PageInfo; import com.lhstack.aspect.permission.DynAuthority; import com.lhstack.aspect.permission.InitAuthority; import com.lhstack.config.security.LogoutHandler; import com.lhstack.config.security.holder.SecurityContextHolder; import com.lhstack.controller.excontroller.RegistryException; import com.lhstack.entity.layui.LayuiResut; import com.lhstack.entity.layui.LayuiTableResult; import com.lhstack.entity.permission.Role; import com.lhstack.entity.permission.User; import com.lhstack.entity.permission.UserExampleDTO; import com.lhstack.service.mail.IMailService; import com.lhstack.service.mail.MailConst; import com.lhstack.service.permission.IRoleService; import com.lhstack.service.permission.IUserService; import com.lhstack.utils.PasswordEncoderUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; @RestController @RequestMapping("user") public class UserController { public final static String ROLE_ADMIN = "ROLE_ADMIN"; @Autowired private IUserService userService; @Autowired private IRoleService roleService; @Autowired private IMailService mailService; @Autowired private PasswordEncoderUtils passwordEncoderUtils; @Autowired private LogoutHandler logoutHandler; @PostMapping("/pass/reset/valid") public ResponseEntity<LayuiResut<Boolean>> validResetPass(@RequestParam(value = "to",required = true) String to, @RequestParam(value = "validCode",required = true) String validCode, WebSession session){ String valid = session.getAttribute(MailConst.MAIL_RESET + to).toString(); if(!StringUtils.equals(valid,validCode)){ throw new RuntimeException("验证码不正确"); } return ResponseEntity.ok(LayuiResut.buildSuccess(true)); } @PutMapping("update/info") public ResponseEntity<LayuiResut<Boolean>> updateUserInfo(@RequestBody User user) throws Exception { User principal = (User) SecurityContextHolder.get().getPrincipal(); User result = userService.findByUsername(principal.getUsername()); result.setNickName(user.getNickName()) .setIcon(user.getIcon()); userService.update(result.getId(), result); return ResponseEntity.ok(LayuiResut.buildSuccess(true).setMsg("用户信息更新成功")); } /** * @param map validCode 验证码,邮箱收到的验证码 * oldPass 原始密码 * newPass 新密码 * @param session * @return */ @PostMapping("editPass") public ResponseEntity<LayuiResut<Object>> changePass(@RequestBody Map<String, Object> map, WebSession session, ServerWebExchange exchange) throws Exception { if (StringUtils.isEmpty(map.get("validCode").toString()) || StringUtils.isEmpty(map.get("oldPass").toString()) || StringUtils.isEmpty(map.get("newPass").toString())) { throw new NullPointerException("请传入正确的参数"); } User principal = (User) SecurityContextHolder.get().getPrincipal(); String code = (String) session.getAttributes().get(MailConst.EDIT_MAIL_PREFIX + principal.getEmail()); if (!StringUtils.equals(code, map.get("validCode").toString())) { throw new NullPointerException("验证码不正确,请重新输入"); } User user = userService.findByUsername(principal.getUsername()); String oldPass = (String) map.get("oldPass"); String newPass = (String) map.get("newPass"); Boolean matches = passwordEncoderUtils.matches(user.getSalt(), oldPass, user.getPassword()); if (!matches) { throw new NullPointerException("原始密码输入有误,请重新输入"); } String password = passwordEncoderUtils.genPass(user.getSalt(), newPass); user.setPassword(password); userService.update(user.getId(), user); logout(exchange, session); return ResponseEntity.ok(LayuiResut.buildSuccess(null).setMsg("密码修改成功,请重新登录")); } /** * 退出登录 * * @param exchange */ private void logout(ServerWebExchange exchange, WebSession session) { logoutHandler.clearRedisToken(exchange); logoutHandler.clearSession(session); logoutHandler.clearCookie(exchange.getResponse()); } /** * @param map validCode 验证码 * newEmail 新邮箱 * @param session * @return * @throws Exception */ @PostMapping("changeEmail") public ResponseEntity<LayuiResut<User>> changeEmail(@RequestBody Map<String, Object> map, WebSession session) throws Exception { if (StringUtils.isEmpty(map.get("validCode").toString()) || StringUtils.isEmpty(map.get("newEmail").toString())) { throw new NullPointerException("请传入正确的参数"); } String validCode = map.get("validCode").toString(); String newEmail = map.get("newEmail").toString(); String code = (String) session.getAttributes().get(MailConst.EDIT_MAIL_PREFIX + newEmail); if (!StringUtils.equals(validCode, code)) { throw new NullPointerException("验证码不正确,请重新输入"); } session.getAttributes().remove(MailConst.EDIT_MAIL_PREFIX + newEmail); User principal = (User) SecurityContextHolder.get().getPrincipal(); User user = userService.findByUsername(principal.getUsername()); user.setEmail(newEmail); userService.update(user.getId(), user); user.setSalt(null) .setPassword(null); return ResponseEntity.ok(LayuiResut.buildSuccess(user).setMsg("更新邮箱成功")); } @PostMapping("reset/pass") public ResponseEntity<LayuiResut<Boolean>> reset(@RequestBody Map<String,String> info,WebSession session) throws Exception { System.out.println(info); if(isExistsField(info,"email") && isExistsField(info,"validCode") && isExistsField(info,"newPass")){ String email = info.get("email"); String validCode = info.get("validCode"); String valid = session.getAttribute(MailConst.MAIL_RESET + email).toString(); if(!StringUtils.equals(valid,validCode)){ throw new RuntimeException("验证码不正确,请重新输入"); } User user = userService.findByEmail(email); user.setSalt(passwordEncoderUtils.salt()) .setPassword(passwordEncoderUtils.genPass(user.getSalt(),info.get("newPass"))); session.getAttributes().remove(MailConst.MAIL_RESET + email); return ResponseEntity.ok(LayuiResut.buildSuccess(userService.update(user.getId(),user) != null)); } throw new RuntimeException("提交数据不合法"); } private boolean isExistsField(Map<String, String> info, String field) { return StringUtils.isNotBlank(info.get(field)); } /** * 修改密码,发送验证码 * * @param to * @param session * @return */ @PostMapping("changePassValid") public ResponseEntity<LayuiResut<Object>> sendPassValid(@RequestParam("to") String to, WebSession session) throws Exception { int random = (int) (Math.random() * 100000); session.getAttributes().put(MailConst.EDIT_MAIL_PREFIX + to, random + ""); mailService.sendHtmlMail(MailConst.VALID_CODE_HTML_TEMPLATE.replace("@", random + ""), "PerSys邮箱验证", to); return ResponseEntity.ok(LayuiResut.buildSuccess(null).setMsg("验证码发送成功,请登陆邮箱进行查看")); } /** * 修改邮箱,发送验证码 * * @param to * @param session * @return */ @PostMapping("changeSendValid") public ResponseEntity<LayuiResut<Object>> sendValid(@RequestParam("to") String to, WebSession session) throws Exception { User user = userService.findByEmail(to); if (user != null) { return ResponseEntity.ok(LayuiResut.buildError("邮箱已存在,请重新更换邮箱进行绑定", 403)); } int random = (int) (Math.random() * 100000); session.getAttributes().put(MailConst.EDIT_MAIL_PREFIX + to, random + ""); mailService.sendHtmlMail(MailConst.VALID_CODE_HTML_TEMPLATE.replace("@", random + ""), "PerSys邮箱验证", to); return ResponseEntity.ok(LayuiResut.buildSuccess(null).setMsg("验证码发送成功,请登陆邮箱进行查看")); } /** * 复杂查询 * * @param examples * @return */ @PostMapping("page") @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_QUERY)") @DynAuthority public Mono<LayuiTableResult<User>> findAll(UserExampleDTO examples) { LayuiTableResult<User> layuiTableResult = new LayuiTableResult<>(); initExample(examples); PageInfo<User> userPageInfo = userService.findByNotExistThisAndExample(examples); layuiTableResult.setCount(userPageInfo.getTotal()) .setMsg("获取列表成功") .setCode(0) .setData(userPageInfo.getList()); return Mono.just(layuiTableResult); } /** * 初始化findByNotExistThisAndExample查询条件 * * @param example */ private void initExample(UserExampleDTO example) { Authentication authentication = SecurityContextHolder.get(); User user = (User) authentication.getPrincipal(); if (user == null) { throw new NullPointerException("请先登录"); } example.setUserId(user.getId()); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); example.setIsAdmin(authorities.stream().anyMatch(item -> ((GrantedAuthority) item).getAuthority().equals(ROLE_ADMIN))); example.setIgnoreRoleNames(Arrays.asList("ADMIN")); example.setIgnorePermissionNames(Arrays.asList("ADMIN_USER_QUERY")); } @DeleteMapping("del/{id}") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_DELETE)") public Mono<ResponseEntity<LayuiResut<Object>>> del(@PathVariable("id") Long id) { Long count = userService.deleteByIdAndRole(id); if (count > 0) { return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(null) .setMsg("删除成功") )); } return Mono.just(ResponseEntity.badRequest() .body(LayuiResut.buildSuccess(null) .setMsg("删除失败") .setCode(403))); } @DeleteMapping("del/all/{ids}") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_DELETE)") public Mono<ResponseEntity<LayuiResut<Object>>> delAll(@PathVariable("ids") List<Long> ids) { Long count = userService.deleteByIdsAndRole(ids); return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(null).setMsg("删除成功"))); } @GetMapping("role/{uid}") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_QUERY)") public Mono<ResponseEntity<LayuiResut<List<Role>>>> findByUidRole(@PathVariable("uid") Long uid) { LayuiResut<List<Role>> layuiResut = LayuiResut .buildSuccess(roleService.findByUid(uid)) .setMsg("查询角色成功") .setCode(0); return Mono.just(ResponseEntity.ok(layuiResut)); } @GetMapping("roles") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_QUERY)") public Mono<ResponseEntity<LayuiResut<List<Role>>>> findByRoles() { LayuiResut<List<Role>> layuiResut = LayuiResut .buildSuccess(roleService.findAllByIgnoreRoleNames("ADMIN", "USER_ADMIN")) .setMsg("查询角色成功") .setCode(0); return Mono.just(ResponseEntity.ok(layuiResut)); } @PostMapping("update") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_UPDATE)") public Mono<ResponseEntity<LayuiResut<User>>> updateUser(User user, @RequestParam(value = "rids", required = false) List<Long> rids) { User result = userService.updateAndRole(user, rids); return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(result).setMsg("更新用户信息成功"))); } @PostMapping("add") @DynAuthority @InitAuthority("anyAuthority(ROLE_ADMIN,PERMISSION_ADMIN_USER_ADD)") public Mono<ResponseEntity<LayuiResut<User>>> addUser(User user, @RequestParam(value = "rids", required = false) List<Long> rids) { return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(userService.saveUserAndRole(user, rids)).setMsg("添加用户成功"))); } /** * 注册用户 * * @param user * @param session * @return */ @PostMapping("reg") public Mono<ResponseEntity<LayuiResut<User>>> registry(@RequestBody User user, @RequestParam("code") String code, WebSession session) { String validCode = (String) session.getAttributes().get(MailConst.EDIT_MAIL_PREFIX + user.getEmail()); if (!StringUtils.equals(code, validCode)) { throw new RegistryException("验证码不正确"); } String username = user.getUsername(); User u = userService.findByUsername(username); if (u != null) { throw new RegistryException("用户名已存在"); } User u1 = userService.findByNickName(user.getNickName()); if (u1 != null) { throw new RegistryException("用户名已存在"); } User result = userService.registry(user); session.getAttributes().remove(MailConst.MAIL_PREFIX + user.getEmail()); return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(result) .setMsg("注册用户成功"))); } /** * 获取用户信息 * * @return */ @GetMapping("info") public Mono<ResponseEntity<LayuiResut<User>>> loadUserInfo() { User user = (User) SecurityContextHolder.get().getPrincipal(); User result = userService.findByUsername(user.getUsername()); result.setPassword(null) .setSalt(null); return Mono.just(ResponseEntity.ok(LayuiResut.buildSuccess(result).setMsg("获取用户信息成功"))); } }
41.397759
138
0.654171
e87cd54fb8b0b6bede95ef67fe2bb7e2ad2bfe01
330
package ch.admin.bag.covidcode.authcodegeneration.api; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @AllArgsConstructor @NoArgsConstructor(access = AccessLevel.PROTECTED) public class AuthorizationCodeOnsetResponseDto { private String onset; }
22
54
0.836364
84775067543cbdfa3ecd73d92d7c42281394fb15
3,416
package com.jqhee.latte.core.net; import android.content.Context; import com.jqhee.latte.core.net.callback.IError; import com.jqhee.latte.core.net.callback.IFailure; import com.jqhee.latte.core.net.callback.IRequest; import com.jqhee.latte.core.net.callback.ISuccess; import com.jqhee.latte.core.ui.loader.LoaderStyle; import java.io.File; import java.util.WeakHashMap; import okhttp3.MediaType; import okhttp3.RequestBody; public class RestClientBuilder { // 建造者模式 private String mUrl = null; private static final WeakHashMap<String, Object> PARAMS = RestCreator.getParams(); /// 文件下载 // 文件目录 private String mDownloadDir; private String mExtension; private String mName; private IRequest mIRequest = null; private ISuccess mISuccess = null; private IFailure mIFailure = null; private IError mIError = null; private RequestBody mBody = null; private File mFile = null; private LoaderStyle mLoaderStyple = null; // 为了创建 dialog private Context mContext = null; // 只允许 RestClientBuilder new RestClientBuilder() { } public final RestClientBuilder url(String url) { this.mUrl = url; // 全局修改BaseURL // RetrofitUrlManager.getInstance().setGlobalDomain("your BaseUrl"); return this; } public final RestClientBuilder params(WeakHashMap<String, Object> params) { PARAMS.putAll(params); return this; } public final RestClientBuilder params(String key, Object object) { this.PARAMS.put(key, object); return this; } /** * json 方式提交数据 */ public final RestClientBuilder raw(String raw) { this.mBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), raw); return this; } public final RestClientBuilder success(ISuccess iSuccess) { this.mISuccess = iSuccess; return this; } public final RestClientBuilder failure(IFailure iFailure) { this.mIFailure = iFailure; return this; } public final RestClientBuilder error(IError iError) { this.mIError = iError; return this; } public final RestClientBuilder onRequest(IRequest iRequest) { this.mIRequest = iRequest; return this; } public final RestClientBuilder loader(Context context) { this.mContext = context; this.mLoaderStyple = LoaderStyle.BallClipRotatePulseIndicator; return this; } public final RestClientBuilder file(File file) { this.mFile = file; return this; } public final RestClientBuilder file(String filePath) { this.mFile = new File(filePath); return this; } public final RestClientBuilder downloadSetting(String downloadDir, String extension, String name) { this.mDownloadDir = downloadDir; this.mExtension = extension; this.mName = name; return this; } // RestClient 发起网络请求参数配置 public final RestClient builder() { return new RestClient(mUrl, PARAMS, mDownloadDir, mExtension, mName, mIRequest, mISuccess, mIFailure, mIError, mBody, mFile, mLoaderStyple, mContext ); } }
26.076336
103
0.634368
8ac33369c14f600dbf52b72525b56a7a8004bd76
2,532
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the repository root. package com.microsoft.tfs.core.clients.versioncontrol.conflicts; import com.microsoft.tfs.core.Messages; import com.microsoft.tfs.core.clients.versioncontrol.conflicts.resolutions.ConflictResolution; import com.microsoft.tfs.core.clients.versioncontrol.conflicts.resolutions.CoreConflictResolution; import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Conflict; import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Resolution; import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace; import com.microsoft.tfs.core.clients.versioncontrol.specs.ItemSpec; /** * @since TEE-SDK-10.1 */ public abstract class DeletedConflictDescription extends VersionConflictDescription { protected DeletedConflictDescription( final Workspace workspace, final Conflict conflict, final ItemSpec[] conflictItemSpecs) { super(workspace, conflict, conflictItemSpecs); } /** * For deleted conflicts, the change summary cannot be determined (since the * target does not exist.) * * {@inheritDoc} */ @Override public boolean showChangeDescription() { return false; } /** * Deleted conflicts do not have change descriptions. Since * showChangeDescription() always returns false, this method should never be * called. * * {@inheritDoc} */ @Override public String getChangeDescription() { return Messages.getString("DeletedConflictDescription.ChangeDescription"); //$NON-NLS-1$ } /** * Deleted conflicts do not analyze (they're missing a file critical in * analyzing the conflict.) * * {@inheritDoc} */ @Override public boolean analyzeConflict() { return false; } /** * {@inheritDoc} */ @Override public boolean isResolutionEnabled(final ConflictResolution resolution) { if (getConflict() == null) { return true; } /* * Visual Studio's UI *shows* all resolutions (automerge and external * merge) even though they're disabled. Mimic that behavior by only * enabling core conflict resolution options that aren't automerge. */ return (resolution instanceof CoreConflictResolution && ((CoreConflictResolution) resolution).getResolution() != Resolution.ACCEPT_MERGE); } }
32.883117
98
0.695498
98b3c4c04680919b6d9257d6c114ef35c5142506
660
package com.andrognito.kerningviewsapp; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.andrognito.kerningview.KerningTextView; public class SampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample); KerningTextView text3 = (KerningTextView) findViewById(R.id.text3); /** * Dynamically setting the kerning factor on a {@link KerningTextView} */ if (text3 != null) { text3.setKerningFactor(3.5f); } } }
27.5
78
0.693939
15c047ab6851a647e283eba6db4e67406ce957b0
1,751
/* * Copyright (c) 2016 DreamLiner Studio * 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.dreamliner.lib.dropdownmenu.widget; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; /** * @author chenzj * @Title: Draw * @Description: 类的描述 - 字体图标 * @date 2016/5/14 11:43 * @email admin@chenzhongjin.cn */ public class FontIcon extends TextView { public FontIcon(Context context) { super(context); init(); } public FontIcon(Context context, AttributeSet attrs) { super(context, attrs); init(); } public FontIcon(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void init() { Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "icon.ttf"); setTypeface(typeFace); } @SuppressWarnings("unused") public void setFontIconColor(int textColor) { this.setTextColor(textColor); } @SuppressWarnings("unused") public void setFontIconColor(ColorStateList colors) { this.setTextColor(colors); } }
27.793651
91
0.695031
5974800de20a88716441a3fdff8e57973c257e34
17,560
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 DECL|package|org.apache.hadoop.io.file.tfile package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|file operator|. name|tfile package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Random import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FSDataOutputStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|BytesWritable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|file operator|. name|tfile operator|. name|TFile operator|. name|Reader import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|file operator|. name|tfile operator|. name|TFile operator|. name|Writer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|file operator|. name|tfile operator|. name|TFile operator|. name|Reader operator|. name|Scanner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|test operator|. name|GenericTestUtils import|; end_import begin_class DECL|class|TestTFileSplit specifier|public class|class name|TestTFileSplit block|{ DECL|field|ROOT specifier|private specifier|static name|String name|ROOT init|= name|GenericTestUtils operator|. name|getTestDir argument_list|() operator|. name|getAbsolutePath argument_list|() decl_stmt|; DECL|field|BLOCK_SIZE specifier|private specifier|final specifier|static name|int name|BLOCK_SIZE init|= literal|64 operator|* literal|1024 decl_stmt|; DECL|field|KEY specifier|private specifier|static specifier|final name|String name|KEY init|= literal|"key" decl_stmt|; DECL|field|VALUE specifier|private specifier|static specifier|final name|String name|VALUE init|= literal|"value" decl_stmt|; DECL|field|fs specifier|private name|FileSystem name|fs decl_stmt|; DECL|field|conf specifier|private name|Configuration name|conf decl_stmt|; DECL|field|path specifier|private name|Path name|path decl_stmt|; DECL|field|random specifier|private name|Random name|random init|= operator|new name|Random argument_list|() decl_stmt|; DECL|field|comparator specifier|private name|String name|comparator init|= literal|"memcmp" decl_stmt|; DECL|field|outputFile specifier|private name|String name|outputFile init|= literal|"TestTFileSplit" decl_stmt|; DECL|method|createFile (int count, String compress) name|void name|createFile parameter_list|( name|int name|count parameter_list|, name|String name|compress parameter_list|) throws|throws name|IOException block|{ name|conf operator|= operator|new name|Configuration argument_list|() expr_stmt|; name|path operator|= operator|new name|Path argument_list|( name|ROOT argument_list|, name|outputFile operator|+ literal|"." operator|+ name|compress argument_list|) expr_stmt|; name|fs operator|= name|path operator|. name|getFileSystem argument_list|( name|conf argument_list|) expr_stmt|; name|FSDataOutputStream name|out init|= name|fs operator|. name|create argument_list|( name|path argument_list|) decl_stmt|; name|Writer name|writer init|= operator|new name|Writer argument_list|( name|out argument_list|, name|BLOCK_SIZE argument_list|, name|compress argument_list|, name|comparator argument_list|, name|conf argument_list|) decl_stmt|; name|int name|nx decl_stmt|; for|for control|( name|nx operator|= literal|0 init|; name|nx operator|< name|count condition|; name|nx operator|++ control|) block|{ name|byte index|[] name|key init|= name|composeSortedKey argument_list|( name|KEY argument_list|, name|count argument_list|, name|nx argument_list|) operator|. name|getBytes argument_list|() decl_stmt|; name|byte index|[] name|value init|= operator|( name|VALUE operator|+ name|nx operator|) operator|. name|getBytes argument_list|() decl_stmt|; name|writer operator|. name|append argument_list|( name|key argument_list|, name|value argument_list|) expr_stmt|; block|} name|writer operator|. name|close argument_list|() expr_stmt|; name|out operator|. name|close argument_list|() expr_stmt|; block|} DECL|method|readFile () name|void name|readFile parameter_list|() throws|throws name|IOException block|{ name|long name|fileLength init|= name|fs operator|. name|getFileStatus argument_list|( name|path argument_list|) operator|. name|getLen argument_list|() decl_stmt|; name|int name|numSplit init|= literal|10 decl_stmt|; name|long name|splitSize init|= name|fileLength operator|/ name|numSplit operator|+ literal|1 decl_stmt|; name|Reader name|reader init|= operator|new name|Reader argument_list|( name|fs operator|. name|open argument_list|( name|path argument_list|) argument_list|, name|fs operator|. name|getFileStatus argument_list|( name|path argument_list|) operator|. name|getLen argument_list|() argument_list|, name|conf argument_list|) decl_stmt|; name|long name|offset init|= literal|0 decl_stmt|; name|long name|rowCount init|= literal|0 decl_stmt|; name|BytesWritable name|key decl_stmt|, name|value decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|numSplit condition|; operator|++ name|i operator|, name|offset operator|+= name|splitSize control|) block|{ name|Scanner name|scanner init|= name|reader operator|. name|createScannerByByteRange argument_list|( name|offset argument_list|, name|splitSize argument_list|) decl_stmt|; name|int name|count init|= literal|0 decl_stmt|; name|key operator|= operator|new name|BytesWritable argument_list|() expr_stmt|; name|value operator|= operator|new name|BytesWritable argument_list|() expr_stmt|; while|while condition|( operator|! name|scanner operator|. name|atEnd argument_list|() condition|) block|{ name|scanner operator|. name|entry argument_list|() operator|. name|get argument_list|( name|key argument_list|, name|value argument_list|) expr_stmt|; operator|++ name|count expr_stmt|; name|scanner operator|. name|advance argument_list|() expr_stmt|; block|} name|scanner operator|. name|close argument_list|() expr_stmt|; name|assertTrue argument_list|( name|count operator|> literal|0 argument_list|) expr_stmt|; name|rowCount operator|+= name|count expr_stmt|; block|} name|assertEquals argument_list|( name|rowCount argument_list|, name|reader operator|. name|getEntryCount argument_list|() argument_list|) expr_stmt|; name|reader operator|. name|close argument_list|() expr_stmt|; block|} comment|/* Similar to readFile(), tests the scanner created * by record numbers rather than the offsets. */ DECL|method|readRowSplits (int numSplits) name|void name|readRowSplits parameter_list|( name|int name|numSplits parameter_list|) throws|throws name|IOException block|{ name|Reader name|reader init|= operator|new name|Reader argument_list|( name|fs operator|. name|open argument_list|( name|path argument_list|) argument_list|, name|fs operator|. name|getFileStatus argument_list|( name|path argument_list|) operator|. name|getLen argument_list|() argument_list|, name|conf argument_list|) decl_stmt|; name|long name|totalRecords init|= name|reader operator|. name|getEntryCount argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|numSplits condition|; name|i operator|++ control|) block|{ name|long name|startRec init|= name|i operator|* name|totalRecords operator|/ name|numSplits decl_stmt|; name|long name|endRec init|= operator|( name|i operator|+ literal|1 operator|) operator|* name|totalRecords operator|/ name|numSplits decl_stmt|; if|if condition|( name|i operator|== name|numSplits operator|- literal|1 condition|) block|{ name|endRec operator|= name|totalRecords expr_stmt|; block|} name|Scanner name|scanner init|= name|reader operator|. name|createScannerByRecordNum argument_list|( name|startRec argument_list|, name|endRec argument_list|) decl_stmt|; name|int name|count init|= literal|0 decl_stmt|; name|BytesWritable name|key init|= operator|new name|BytesWritable argument_list|() decl_stmt|; name|BytesWritable name|value init|= operator|new name|BytesWritable argument_list|() decl_stmt|; name|long name|x init|= name|startRec decl_stmt|; while|while condition|( operator|! name|scanner operator|. name|atEnd argument_list|() condition|) block|{ name|assertEquals argument_list|( literal|"Incorrect RecNum returned by scanner" argument_list|, name|scanner operator|. name|getRecordNum argument_list|() argument_list|, name|x argument_list|) expr_stmt|; name|scanner operator|. name|entry argument_list|() operator|. name|get argument_list|( name|key argument_list|, name|value argument_list|) expr_stmt|; operator|++ name|count expr_stmt|; name|assertEquals argument_list|( literal|"Incorrect RecNum returned by scanner" argument_list|, name|scanner operator|. name|getRecordNum argument_list|() argument_list|, name|x argument_list|) expr_stmt|; name|scanner operator|. name|advance argument_list|() expr_stmt|; operator|++ name|x expr_stmt|; block|} name|scanner operator|. name|close argument_list|() expr_stmt|; name|assertTrue argument_list|( name|count operator|== operator|( name|endRec operator|- name|startRec operator|) argument_list|) expr_stmt|; block|} comment|// make sure specifying range at the end gives zero records. name|Scanner name|scanner init|= name|reader operator|. name|createScannerByRecordNum argument_list|( name|totalRecords argument_list|, operator|- literal|1 argument_list|) decl_stmt|; name|assertTrue argument_list|( name|scanner operator|. name|atEnd argument_list|() argument_list|) expr_stmt|; block|} DECL|method|composeSortedKey (String prefix, int total, int value) specifier|static name|String name|composeSortedKey parameter_list|( name|String name|prefix parameter_list|, name|int name|total parameter_list|, name|int name|value parameter_list|) block|{ return|return name|String operator|. name|format argument_list|( literal|"%s%010d" argument_list|, name|prefix argument_list|, name|value argument_list|) return|; block|} DECL|method|checkRecNums () name|void name|checkRecNums parameter_list|() throws|throws name|IOException block|{ name|long name|fileLen init|= name|fs operator|. name|getFileStatus argument_list|( name|path argument_list|) operator|. name|getLen argument_list|() decl_stmt|; name|Reader name|reader init|= operator|new name|Reader argument_list|( name|fs operator|. name|open argument_list|( name|path argument_list|) argument_list|, name|fileLen argument_list|, name|conf argument_list|) decl_stmt|; name|long name|totalRecs init|= name|reader operator|. name|getEntryCount argument_list|() decl_stmt|; name|long name|begin init|= name|random operator|. name|nextLong argument_list|() operator|% operator|( name|totalRecs operator|/ literal|2 operator|) decl_stmt|; if|if condition|( name|begin operator|< literal|0 condition|) name|begin operator|+= operator|( name|totalRecs operator|/ literal|2 operator|) expr_stmt|; name|long name|end init|= name|random operator|. name|nextLong argument_list|() operator|% operator|( name|totalRecs operator|/ literal|2 operator|) decl_stmt|; if|if condition|( name|end operator|< literal|0 condition|) name|end operator|+= operator|( name|totalRecs operator|/ literal|2 operator|) expr_stmt|; name|end operator|+= operator|( name|totalRecs operator|/ literal|2 operator|) operator|+ literal|1 expr_stmt|; name|assertEquals argument_list|( literal|"RecNum for offset=0 should be 0" argument_list|, literal|0 argument_list|, name|reader operator|. name|getRecordNumNear argument_list|( literal|0 argument_list|) argument_list|) expr_stmt|; for|for control|( name|long name|x range|: operator|new name|long index|[] block|{ name|fileLen block|, name|fileLen operator|+ literal|1 block|, literal|2 operator|* name|fileLen block|} control|) block|{ name|assertEquals argument_list|( literal|"RecNum for offset>=fileLen should be total entries" argument_list|, name|totalRecs argument_list|, name|reader operator|. name|getRecordNumNear argument_list|( name|x argument_list|) argument_list|) expr_stmt|; block|} for|for control|( name|long name|i init|= literal|0 init|; name|i operator|< literal|100 condition|; operator|++ name|i control|) block|{ name|assertEquals argument_list|( literal|"Locaton to RecNum conversion not symmetric" argument_list|, name|i argument_list|, name|reader operator|. name|getRecordNumByLocation argument_list|( name|reader operator|. name|getLocationByRecordNum argument_list|( name|i argument_list|) argument_list|) argument_list|) expr_stmt|; block|} for|for control|( name|long name|i init|= literal|1 init|; name|i operator|< literal|100 condition|; operator|++ name|i control|) block|{ name|long name|x init|= name|totalRecs operator|- name|i decl_stmt|; name|assertEquals argument_list|( literal|"Locaton to RecNum conversion not symmetric" argument_list|, name|x argument_list|, name|reader operator|. name|getRecordNumByLocation argument_list|( name|reader operator|. name|getLocationByRecordNum argument_list|( name|x argument_list|) argument_list|) argument_list|) expr_stmt|; block|} for|for control|( name|long name|i init|= name|begin init|; name|i operator|< name|end condition|; operator|++ name|i control|) block|{ name|assertEquals argument_list|( literal|"Locaton to RecNum conversion not symmetric" argument_list|, name|i argument_list|, name|reader operator|. name|getRecordNumByLocation argument_list|( name|reader operator|. name|getLocationByRecordNum argument_list|( name|i argument_list|) argument_list|) argument_list|) expr_stmt|; block|} for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|1000 condition|; operator|++ name|i control|) block|{ name|long name|x init|= name|random operator|. name|nextLong argument_list|() operator|% name|totalRecs decl_stmt|; if|if condition|( name|x operator|< literal|0 condition|) name|x operator|+= name|totalRecs expr_stmt|; name|assertEquals argument_list|( literal|"Locaton to RecNum conversion not symmetric" argument_list|, name|x argument_list|, name|reader operator|. name|getRecordNumByLocation argument_list|( name|reader operator|. name|getLocationByRecordNum argument_list|( name|x argument_list|) argument_list|) argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test DECL|method|testSplit () specifier|public name|void name|testSplit parameter_list|() throws|throws name|IOException block|{ name|System operator|. name|out operator|. name|println argument_list|( literal|"testSplit" argument_list|) expr_stmt|; name|createFile argument_list|( literal|100000 argument_list|, name|Compression operator|. name|Algorithm operator|. name|NONE operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|checkRecNums argument_list|() expr_stmt|; name|readFile argument_list|() expr_stmt|; name|readRowSplits argument_list|( literal|10 argument_list|) expr_stmt|; name|fs operator|. name|delete argument_list|( name|path argument_list|, literal|true argument_list|) expr_stmt|; name|createFile argument_list|( literal|500000 argument_list|, name|Compression operator|. name|Algorithm operator|. name|GZ operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|checkRecNums argument_list|() expr_stmt|; name|readFile argument_list|() expr_stmt|; name|readRowSplits argument_list|( literal|83 argument_list|) expr_stmt|; name|fs operator|. name|delete argument_list|( name|path argument_list|, literal|true argument_list|) expr_stmt|; block|} block|} end_class end_unit
13.384146
806
0.792312
6aa11f814f411de180ef50d449753ea7cfdf3457
1,247
package com.techreturners.exercise003; import java.util.*; public class Exercise003 { int getIceCreamCode(String iceCreamFlavour) { int key = 0; HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap map.put(1,"Raspberry Ripple"); //Put elements in Map map.put(2,"Pistachio"); map.put(4,"Vanilla"); map.put(3,"Mint Chocolate Chip"); map.put(5,"Mango Sorbet"); map.put(6,"Chocolate"); for(Map.Entry m : map.entrySet()) { if(m.getValue().equals(iceCreamFlavour)) { key = (int) m.getKey(); } } return key; } String[] iceCreamFlavours() { String[] Flavours = new String[6]; int i=0; HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap //Put elements in Map map.put(1,"Pistachio"); map.put(2,"Raspberry Ripple"); map.put(3,"Vanilla"); map.put(4,"Mint Chocolate Chip"); map.put(5,"Chocolate"); map.put(6,"Mango Sorbet"); for(Map.Entry m : map.entrySet()) { Flavours[i] = (String) m.getValue(); i++; } return Flavours; } }
26.531915
84
0.545309
c1cd259b4199f384843f65445f2a38787a5b101a
841
package main.server.view; import javax.swing.*; import java.awt.*; /** * ServerWindowrepresent the server JFrame. * Consists of 3 panels Interactive, Detection and Console Panel. * * @author Ejaz * @version 1.0 */ public class ServerWindow extends JFrame { public ServerWindow(InteractivePanel interactivePanel, DetectionPanel detectionPanel, ConsolePanel consolePanel) { this.setTitle("GroupX Server"); this.getContentPane().setBackground(Color.LIGHT_GRAY); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); this.getContentPane().add(interactivePanel); this.getContentPane().add(detectionPanel); this.getContentPane().add(consolePanel); } }
31.148148
118
0.724138
ac251ed32c1d66cecf2a2abf6239635f3e5ff493
19,785
/* * Copyright 2015 Synced Synapse. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xbmc.kore.ui; import android.annotation.TargetApi; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.SharedElementCallback; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.transition.Transition; import android.transition.TransitionInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import org.xbmc.kore.R; import org.xbmc.kore.utils.LogUtils; import org.xbmc.kore.utils.Utils; import java.util.List; import java.util.Map; /** * Controls the presentation of Music information (list, details) * All the information is presented by specific fragments */ public class MusicActivity extends BaseActivity implements ArtistListFragment.OnArtistSelectedListener, AlbumListFragment.OnAlbumSelectedListener, AudioGenresListFragment.OnAudioGenreSelectedListener, MusicVideoListFragment.OnMusicVideoSelectedListener { private static final String TAG = LogUtils.makeLogTag(MusicActivity.class); public static final String ALBUMID = "album_id"; public static final String ALBUMTITLE = "album_title"; public static final String ARTISTID = "artist_id"; public static final String ARTISTNAME = "artist_name"; public static final String GENREID = "genre_id"; public static final String GENRETITLE = "genre_title"; public static final String MUSICVIDEOID = "music_video_id"; public static final String MUSICVIDEOTITLE = "music_video_title"; private int selectedAlbumId = -1; private int selectedArtistId = -1; private int selectedGenreId = -1; private int selectedMusicVideoId = -1; private String selectedAlbumTitle = null; private String selectedArtistName = null; private String selectedGenreTitle = null; private String selectedMusicVideoTitle = null; private NavigationDrawerFragment navigationDrawerFragment; private MusicListFragment musicListFragment; private boolean clearSharedElements; @TargetApi(21) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_generic_media); // Set up the drawer. navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager() .findFragmentById(R.id.navigation_drawer); navigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); if (savedInstanceState == null) { musicListFragment = new MusicListFragment(); // Setup animations if (Utils.isLollipopOrLater()) { musicListFragment.setExitTransition(null); musicListFragment.setReenterTransition(TransitionInflater .from(this) .inflateTransition(android.R.transition.fade)); musicListFragment.setExitSharedElementCallback(new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { // Clearing must be done in the reentering fragment // as this is called last. Otherwise, the app will crash during transition setup. Not sure, but might // be a v4 support package bug. if (clearSharedElements) { names.clear(); sharedElements.clear(); clearSharedElements = false; } } }); } getSupportFragmentManager() .beginTransaction() .add(R.id.fragment_container, musicListFragment) .commit(); } else { selectedAlbumId = savedInstanceState.getInt(ALBUMID, -1); selectedArtistId = savedInstanceState.getInt(ARTISTID, -1); selectedGenreId = savedInstanceState.getInt(GENREID, -1); selectedMusicVideoId = savedInstanceState.getInt(MUSICVIDEOID, -1); selectedAlbumTitle = savedInstanceState.getString(ALBUMTITLE, null); selectedArtistName = savedInstanceState.getString(ARTISTNAME, null); selectedGenreTitle = savedInstanceState.getString(GENRETITLE, null); selectedMusicVideoTitle = savedInstanceState.getString(MUSICVIDEOTITLE, null); } setupActionBar(selectedAlbumTitle, selectedArtistName, selectedGenreTitle, selectedMusicVideoTitle); // // Setup system bars and content padding, allowing averlap with the bottom bar // setupSystemBarsColors(); // UIUtils.setPaddingForSystemBars(this, findViewById(R.id.fragment_container), true, true, true); // UIUtils.setPaddingForSystemBars(this, findViewById(R.id.drawer_layout), true, true, true); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override protected void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(ALBUMID, selectedAlbumId); outState.putInt(ARTISTID, selectedArtistId); outState.putInt(GENREID, selectedGenreId); outState.putInt(MUSICVIDEOID, selectedMusicVideoId); outState.putString(ALBUMTITLE, selectedAlbumTitle); outState.putString(ARTISTNAME, selectedArtistName); outState.putString(GENRETITLE, selectedGenreTitle); outState.putString(MUSICVIDEOTITLE, selectedMusicVideoTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { // if (!navigationDrawerFragment.isDrawerOpen()) { // getMenuInflater().inflate(R.menu.media_info, menu); // } getMenuInflater().inflate(R.menu.media_info, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_show_remote: // Starts remote Intent launchIntent = new Intent(this, RemoteActivity.class) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(launchIntent); return true; case android.R.id.home: // Only respond to this if we are showing some details, which can be checked by // checking if some id != -1, in which case we should go back to the previous // fragment, which is the list. // The default behaviour is handled by the nav drawer (open/close) if (selectedAlbumId != -1) { selectedAlbumId = -1; selectedAlbumTitle = null; setupActionBar(null, selectedArtistName, selectedGenreTitle, selectedMusicVideoTitle); getSupportFragmentManager().popBackStack(); return true; } else if (selectedArtistId != -1) { selectedArtistId = -1; selectedArtistName = null; setupActionBar(selectedAlbumTitle, null, selectedGenreTitle, selectedMusicVideoTitle); getSupportFragmentManager().popBackStack(); return true; } else if (selectedGenreId != -1) { selectedGenreId = -1; selectedGenreTitle = null; setupActionBar(selectedAlbumTitle, selectedArtistName, null, selectedMusicVideoTitle); getSupportFragmentManager().popBackStack(); return true; } else if (selectedMusicVideoId != -1) { selectedMusicVideoId = -1; selectedMusicVideoTitle = null; setupActionBar(selectedAlbumTitle, selectedArtistName, selectedGenreTitle, null); getSupportFragmentManager().popBackStack(); return true; } break; default: break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { // If we are showing episode or show details in portrait, clear selected and show action bar if (selectedAlbumId != -1) { selectedAlbumId = -1; selectedAlbumTitle = null; setupActionBar(null, selectedArtistName, selectedGenreTitle, selectedMusicVideoTitle); } else if (selectedArtistId != -1) { selectedArtistId = -1; selectedArtistName = null; setupActionBar(selectedAlbumTitle, null, selectedGenreTitle, selectedMusicVideoTitle); } else if (selectedGenreId != -1) { selectedGenreId = -1; selectedGenreTitle = null; setupActionBar(selectedAlbumTitle, selectedArtistName, null, selectedMusicVideoTitle); } else if (selectedMusicVideoId != -1) { selectedMusicVideoId = -1; selectedMusicVideoTitle = null; setupActionBar(selectedAlbumTitle, selectedArtistName, selectedGenreTitle, null); } super.onBackPressed(); } private boolean drawerIndicatorIsArrow = false; private void setupActionBar(String albumTitle, String artistName, String genreTitle, String musicVideoTitle) { Toolbar toolbar = (Toolbar)findViewById(R.id.default_toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar == null) return; actionBar.setDisplayHomeAsUpEnabled(true); if (albumTitle != null) { actionBar.setTitle(albumTitle); } else if (artistName != null) { actionBar.setTitle(artistName); } else if (genreTitle != null) { actionBar.setTitle(genreTitle); } else if (musicVideoTitle != null) { actionBar.setTitle(musicVideoTitle); } else { actionBar.setTitle(R.string.music); } if ((albumTitle != null) || (artistName != null) || (genreTitle != null) || (musicVideoTitle != null)) { if (!drawerIndicatorIsArrow) { navigationDrawerFragment.animateDrawerToggle(true); drawerIndicatorIsArrow = true; } } else { if (drawerIndicatorIsArrow) { navigationDrawerFragment.animateDrawerToggle(false); drawerIndicatorIsArrow = false; } } } @TargetApi(21) public void onArtistSelected(ArtistListFragment.ViewHolder viewHolder) { selectedArtistId = viewHolder.artistId; selectedArtistName = viewHolder.artistName; // Replace list fragment final ArtistDetailsFragment artistDetailsFragment = ArtistDetailsFragment.newInstance(viewHolder); FragmentTransaction fragTrans = getSupportFragmentManager().beginTransaction(); // Setup animations if (Utils.isLollipopOrLater()) { android.support.v4.app.SharedElementCallback seCallback = new android.support.v4.app.SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { View sharedView = artistDetailsFragment.getSharedElement(); if (sharedView == null) { // shared element not visible clearSharedElements = true; } } }; artistDetailsFragment.setEnterSharedElementCallback(seCallback); artistDetailsFragment.setEnterTransition(TransitionInflater .from(this) .inflateTransition(R.transition.media_details)); artistDetailsFragment.setReturnTransition(null); Transition changeImageTransition = TransitionInflater.from( this).inflateTransition(R.transition.change_image); artistDetailsFragment.setSharedElementReturnTransition(changeImageTransition); artistDetailsFragment.setSharedElementEnterTransition(changeImageTransition); fragTrans.addSharedElement(viewHolder.artView, viewHolder.artView.getTransitionName()); } else { fragTrans.setCustomAnimations(R.anim.fragment_details_enter, 0, R.anim.fragment_list_popenter, 0); } fragTrans.replace(R.id.fragment_container, artistDetailsFragment) .addToBackStack(null) .commit(); navigationDrawerFragment.animateDrawerToggle(true); setupActionBar(null, selectedArtistName, null, null); } @TargetApi(21) public void onAlbumSelected(AlbumListFragment.ViewHolder vh) { selectedAlbumId = vh.albumId; selectedAlbumTitle = vh.albumTitle; // Replace list fragment final AlbumDetailsFragment albumDetailsFragment = AlbumDetailsFragment.newInstance(vh); FragmentTransaction fragTrans = getSupportFragmentManager().beginTransaction(); // Set up transitions if (Utils.isLollipopOrLater()) { android.support.v4.app.SharedElementCallback seCallback = new android.support.v4.app.SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { //On returning onMapSharedElements for the exiting fragment is called before the onMapSharedElements // for the reentering fragment. We use this to determine if we are returning and if // we should clear the shared element lists. Note that, clearing must be done in the reentering fragment // as this is called last. Otherwise it the app will crash during transition setup. Not sure, but might // be a v4 support package bug. if (albumDetailsFragment.isVisible()) { View sharedView = albumDetailsFragment.getSharedElement(); if (sharedView == null) { // shared element not visible clearSharedElements = true; } } } }; albumDetailsFragment.setEnterSharedElementCallback(seCallback); albumDetailsFragment.setEnterTransition(TransitionInflater .from(this) .inflateTransition(R.transition.media_details)); albumDetailsFragment.setReturnTransition(null); Transition changeImageTransition = TransitionInflater.from( this).inflateTransition(R.transition.change_image); albumDetailsFragment.setSharedElementReturnTransition(changeImageTransition); albumDetailsFragment.setSharedElementEnterTransition(changeImageTransition); fragTrans.addSharedElement(vh.artView, vh.artView.getTransitionName()); } else { fragTrans.setCustomAnimations(R.anim.fragment_details_enter, 0, R.anim.fragment_list_popenter, 0); } fragTrans.replace(R.id.fragment_container, albumDetailsFragment) .addToBackStack(null) .commit(); setupActionBar(selectedAlbumTitle, null, null, null); } public void onAudioGenreSelected(int genreId, String genreTitle) { selectedGenreId = genreId; selectedGenreTitle = genreTitle; // Replace list fragment AlbumListFragment albumListFragment = AlbumListFragment.newInstanceForGenre(genreId); getSupportFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.fragment_details_enter, 0, R.anim.fragment_list_popenter, 0) .replace(R.id.fragment_container, albumListFragment) .addToBackStack(null) .commit(); setupActionBar(null, null, genreTitle, null); } @TargetApi(21) public void onMusicVideoSelected(MusicVideoListFragment.ViewHolder vh) { selectedMusicVideoId = vh.musicVideoId; selectedMusicVideoTitle = vh.musicVideoTitle; // Replace list fragment final MusicVideoDetailsFragment detailsFragment = MusicVideoDetailsFragment.newInstance(vh); FragmentTransaction fragTrans = getSupportFragmentManager().beginTransaction(); // Set up transitions if (Utils.isLollipopOrLater()) { android.support.v4.app.SharedElementCallback seCallback = new android.support.v4.app.SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { //On returning onMapSharedElements for the exiting fragment is called before the onMapSharedElements // for the reentering fragment. We use this to determine if we are returning and if // we should clear the shared element lists. Note that, clearing must be done in the reentering fragment // as this is called last. Otherwise it the app will crash during transition setup. Not sure, but might // be a v4 support package bug. if (detailsFragment.isVisible()) { View sharedView = detailsFragment.getSharedElement(); if (sharedView == null) { // shared element not visible LogUtils.LOGD(TAG, "onMusicVideoSelected: setting clearedSharedElements to true"); clearSharedElements = true; } } } }; detailsFragment.setEnterSharedElementCallback(seCallback); detailsFragment.setEnterTransition(TransitionInflater .from(this) .inflateTransition(R.transition.media_details)); detailsFragment.setReturnTransition(null); Transition changeImageTransition = TransitionInflater.from( this).inflateTransition(R.transition.change_image); detailsFragment.setSharedElementReturnTransition(changeImageTransition); detailsFragment.setSharedElementEnterTransition(changeImageTransition); fragTrans.addSharedElement(vh.artView, vh.artView.getTransitionName()); } else { fragTrans.setCustomAnimations(R.anim.fragment_details_enter, 0, R.anim.fragment_list_popenter, 0); } fragTrans.replace(R.id.fragment_container, detailsFragment) .addToBackStack(null) .commit(); setupActionBar(null, null, null, selectedMusicVideoTitle); } }
45.904872
125
0.642557
a98054e6f7a8ba0fa3776aa23252ad7cc268a566
1,516
package myTest; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author Stephen Cai * @date 2018-06-24 17:01 */ public class BatchQueue { public static void blockQueue() throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(2); final int[] i = {1}; BlockingQueue<String> queue = new ArrayBlockingQueue(10); //for (int i = 0; i < 1000; i++) { // queue.put("" + i) ; //} Thread t1 = new Thread(() -> { try { queue.put("" + i[0]) ; System.out.println("queue put:"+i[0]); i[0]++; } catch (InterruptedException e) { e.printStackTrace(); } }); Thread t2 = new Thread(() -> { try { System.out.println("queue take:"+queue.take()); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } }); while (true) { service.submit(t1); //service.submit(t2); } //Thread.sleep(100000000); //System.out.println(queue.poll()); //List<String> temp = Lists.newArrayList(); //queue.drainTo(temp); } public static void main(String[] args) throws InterruptedException { blockQueue(); } }
29.153846
72
0.532322
3930e73ca4768ea1e699326d2ea7d48317303c04
1,733
/* * Copyright 2020 IEXEC BLOCKCHAIN TECH * * 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.iexec.common.result.eip712; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.iexec.common.chain.eip712.TypeParam; import lombok.*; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class Types { @JsonProperty("EIP712Domain") private List<TypeParam> domainTypeParams = null; @JsonProperty("Challenge") private List<TypeParam> challengeTypeParams = null; public static String typeParamsToString(List<TypeParam> typeParams) { StringBuilder s = new StringBuilder(); for (int i = 0; i < typeParams.size(); i++) { s.append(typeParams.get(i).getType()).append(" ").append(typeParams.get(i).getName()); if (i <= typeParams.size() - 2) { s.append(","); } } return s.toString(); } @JsonIgnore public List<TypeParam> getDomainTypeParams() { return domainTypeParams; } @JsonIgnore public List<TypeParam> getChallengeTypeParams() { return challengeTypeParams; } }
29.372881
98
0.691287
2aa508584fdf21d9dd29ca39b208a5cfc2a85451
4,591
/* * Copyright 2014 Guidewire Software, Inc. */ package gw.plugin.ij.lang.psi.impl.expressions; import com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.JavaElementVisitor; import com.intellij.psi.JavaResolveResult; import com.intellij.psi.PsiCallExpression; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiExpressionList; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiReferenceParameterList; import com.intellij.psi.PsiType; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.util.PsiMatcherImpl; import com.intellij.psi.util.PsiMatchers; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import gw.lang.parser.expressions.IBeanMethodCallExpression; import gw.lang.reflect.IMethodInfo; import gw.plugin.ij.lang.GosuTokenTypes; import gw.plugin.ij.lang.parser.GosuCompositeElement; import gw.plugin.ij.lang.parser.GosuElementTypes; import gw.plugin.ij.lang.psi.api.types.IGosuCodeReferenceElement; import gw.plugin.ij.lang.psi.api.types.IGosuTypeElement; import gw.plugin.ij.lang.psi.api.types.IGosuTypeParameterList; import gw.plugin.ij.lang.psi.impl.GosuElementVisitor; import gw.plugin.ij.lang.psi.impl.resolvers.PsiFeatureResolver; import gw.plugin.ij.lang.psi.impl.statements.typedef.GosuSyntheticClassDefinitionImpl; import gw.plugin.ij.lang.psi.util.ElementTypeMatcher; import gw.plugin.ij.lang.psi.util.GosuPsiParseUtil; import gw.plugin.ij.util.ExecutionUtil; import gw.plugin.ij.util.SafeCallable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class GosuBeanMethodCallExpressionImpl extends GosuReferenceExpressionImpl<IBeanMethodCallExpression> implements IGosuCodeReferenceElement, IGosuTypeElement, PsiCallExpression { public GosuBeanMethodCallExpressionImpl(GosuCompositeElement node) { super(node); } @Nullable public PsiElement getReferenceNameElement() { PsiElement child = getLastChild(); while (child != null) { final ASTNode node = child.getNode(); if (node != null && (node.getElementType() == GosuTokenTypes.TT_IDENTIFIER || GosuTokenTypes.isKeyword(node.getElementType()))) return child; child = child.getPrevSibling(); } return null; } @Override public IGosuCodeReferenceElement getQualifier() { final PsiElement firstChild = getFirstChild(); return firstChild instanceof IGosuCodeReferenceElement ? (IGosuCodeReferenceElement) firstChild : null; } @Override public void setQualifier(IGosuCodeReferenceElement newQualifier) { throw new UnsupportedOperationException("Men at work"); } @Nullable public IGosuTypeParameterList getTypeParameterList() { return null; } @Override public PsiType[] getTypeArguments() { return PsiType.EMPTY_ARRAY; } @Override public PsiElement resolve() { return ExecutionUtil.execute(new SafeCallable<PsiElement>(this) { @Nullable public PsiElement execute() throws Exception { final IBeanMethodCallExpression pe = getParsedElement(); if (pe != null) { final IMethodInfo mi = pe.getGenericMethodDescriptor(); if (mi != null) { return PsiFeatureResolver.resolveMethodOrConstructor(mi, GosuBeanMethodCallExpressionImpl.this); } } return null; } }); } @Override public void accept( @NotNull PsiElementVisitor visitor ) { if( visitor instanceof JavaElementVisitor && !(visitor instanceof HighlightVisitorImpl) ) { ((JavaElementVisitor)visitor).visitCallExpression( this ); } else if( visitor instanceof GosuElementVisitor) { ((GosuElementVisitor)visitor).visitBeanMethodCallExpression(this); } else { visitor.visitElement( this ); } } @NotNull @Override public PsiExpressionList getArgumentList() { return (GosuExpressionListImpl)findChildByType( GosuElementTypes.ELEM_TYPE_ArgumentListClause ); } @Override public PsiMethod resolveMethod() { PsiElement ref = resolve(); return ref instanceof PsiMethod ? (PsiMethod)ref : null; } @NotNull @Override public JavaResolveResult resolveMethodGenerics() { throw new UnsupportedOperationException( "Not implemented yet" ); } @NotNull @Override public PsiReferenceParameterList getTypeArgumentList() { return null; } }
34.007407
184
0.767371
688304f8fab8f592deefc1869e9921f4e69f79d1
4,616
import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("dk") public class class104 extends class103 { @ObfuscatedName("s") @ObfuscatedGetter( intValue = 580988101 ) int field1297; @ObfuscatedName("t") boolean field1298; // $FF: synthetic field @ObfuscatedSignature( descriptor = "Ldn;" ) final class106 this$0; @ObfuscatedSignature( descriptor = "(Ldn;)V" ) class104(class106 var1) { this.this$0 = var1; this.field1297 = -1; } @ObfuscatedName("s") @ObfuscatedSignature( descriptor = "(Lnv;B)V", garbageValue = "0" ) void vmethod2562(Buffer var1) { this.field1297 = var1.readUnsignedShort(); this.field1298 = var1.readUnsignedByte() == 1; } @ObfuscatedName("t") @ObfuscatedSignature( descriptor = "(Ldj;I)V", garbageValue = "1598392944" ) void vmethod2567(ClanSettings var1) { var1.method2369(this.field1297, this.field1298); } @ObfuscatedName("s") @ObfuscatedSignature( descriptor = "(III)I", garbageValue = "1066744869" ) static int method2272(int var0, int var1) { FloorOverlayDefinition var3 = (FloorOverlayDefinition)FloorOverlayDefinition.FloorOverlayDefinition_cached.get((long)var0); FloorOverlayDefinition var2; if (var3 != null) { var2 = var3; } else { byte[] var4 = FloorOverlayDefinition.FloorOverlayDefinition_archive.takeFile(4, var0); var3 = new FloorOverlayDefinition(); if (var4 != null) { var3.decode(new Buffer(var4), var0); } var3.postDecode(); FloorOverlayDefinition.FloorOverlayDefinition_cached.put(var3, (long)var0); var2 = var3; } if (var2 == null) { return var1; } else if (var2.secondaryRgb >= 0) { return var2.secondaryRgb | -16777216; } else { int var6; if (var2.texture >= 0) { var6 = Messages.method2072(Rasterizer3D.Rasterizer3D_textureLoader.getAverageTextureRGB(var2.texture), 96); return Rasterizer3D.Rasterizer3D_colorPalette[var6] | -16777216; } else if (var2.primaryRgb == 16711935) { return var1; } else { var6 = TileItem.method2007(var2.hue, var2.saturation, var2.lightness); int var5 = Messages.method2072(var6, 96); return Rasterizer3D.Rasterizer3D_colorPalette[var5] | -16777216; } } } @ObfuscatedName("j") @ObfuscatedSignature( descriptor = "(Ljava/lang/CharSequence;I)[B", garbageValue = "-789847888" ) public static byte[] method2265(CharSequence var0) { int var1 = var0.length(); byte[] var2 = new byte[var1]; for (int var3 = 0; var3 < var1; ++var3) { char var4 = var0.charAt(var3); if (var4 > 0 && var4 < 128 || var4 >= 160 && var4 <= 255) { var2[var3] = (byte)var4; } else if (var4 == 8364) { var2[var3] = -128; } else if (var4 == 8218) { var2[var3] = -126; } else if (var4 == 402) { var2[var3] = -125; } else if (var4 == 8222) { var2[var3] = -124; } else if (var4 == 8230) { var2[var3] = -123; } else if (var4 == 8224) { var2[var3] = -122; } else if (var4 == 8225) { var2[var3] = -121; } else if (var4 == 710) { var2[var3] = -120; } else if (var4 == 8240) { var2[var3] = -119; } else if (var4 == 352) { var2[var3] = -118; } else if (var4 == 8249) { var2[var3] = -117; } else if (var4 == 338) { var2[var3] = -116; } else if (var4 == 381) { var2[var3] = -114; } else if (var4 == 8216) { var2[var3] = -111; } else if (var4 == 8217) { var2[var3] = -110; } else if (var4 == 8220) { var2[var3] = -109; } else if (var4 == 8221) { var2[var3] = -108; } else if (var4 == 8226) { var2[var3] = -107; } else if (var4 == 8211) { var2[var3] = -106; } else if (var4 == 8212) { var2[var3] = -105; } else if (var4 == 732) { var2[var3] = -104; } else if (var4 == 8482) { var2[var3] = -103; } else if (var4 == 353) { var2[var3] = -102; } else if (var4 == 8250) { var2[var3] = -101; } else if (var4 == 339) { var2[var3] = -100; } else if (var4 == 382) { var2[var3] = -98; } else if (var4 == 376) { var2[var3] = -97; } else { var2[var3] = 63; } } return var2; } @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "(IB)V", garbageValue = "-121" ) @Export("clearItemContainer") static void clearItemContainer(int var0) { ItemContainer var1 = (ItemContainer)ItemContainer.itemContainers.get((long)var0); if (var1 != null) { for (int var2 = 0; var2 < var1.ids.length; ++var2) { var1.ids[var2] = -1; var1.quantities[var2] = 0; } } } }
25.502762
125
0.618934
e9c5bf6e590bccab1eede7ed33c3cc8306aa4fe0
372
package cn.jsprun.dao; import java.util.List; import cn.jsprun.domain.Statvars; import cn.jsprun.domain.StatvarsId; public interface StatvarsDao { public List<Statvars> getStatvarsByType(String type); public void updateStatvarsForMain(List<Statvars> statvarsList); public Statvars getStatvarsById(StatvarsId statvarsId); public void saveStatvars(Statvars statvars); }
33.818182
64
0.825269
4bd1f5a6b44222f74bcccdb25b654d039acc8b48
21,411
package com.oncecloud.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Component; import com.oncecloud.vsphere.VMWareUtil; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.oncecloud.constants.PowerConstant; import com.oncecloud.dao.HostDAO; import com.oncecloud.dao.HostSRDAO; import com.oncecloud.dao.PoolDAO; import com.oncecloud.dao.PowerDAO; import com.oncecloud.dao.StorageDAO; import com.oncecloud.dao.UserDAO; import com.oncecloud.dao.VMDAO; import com.oncecloud.entity.OCHost; import com.oncecloud.entity.OCLog; import com.oncecloud.entity.OCPool; import com.oncecloud.entity.OCVM; import com.oncecloud.entity.Power; import com.oncecloud.entity.Storage; import com.oncecloud.log.LogAction; import com.oncecloud.log.LogObject; import com.oncecloud.log.LogRecord; import com.oncecloud.log.LogRole; import com.oncecloud.message.MessageUtil; import com.oncecloud.model.VMPlatform; import com.oncecloud.model.VMPower; import com.oncecloud.model.VMStatus; import com.oncecloud.service.HostService; import com.oncecloud.util.TimeUtils; @Component("HostService") public class HostServiceImpl implements HostService { @Resource private HostDAO hostDAO; @Resource private PoolDAO poolDAO; @Resource private PowerDAO powerDAO; @Resource private StorageDAO storageDAO; @Resource private HostSRDAO hostSRDAO; @Resource private VMDAO vmDAO; @Resource private UserDAO userDAO; @Resource private LogRecord logRecord; @Resource private MessageUtil message; public JSONArray createHost(String hostUuid, String hostName, String hostPwd, String hostDesc, String hostIp, String hostType, int userid) { Date startTime = new Date(); JSONArray qaArray = new JSONArray(); //添加主机类型的检验(待添加的功能) OCHost host = new OCHost(hostUuid, hostPwd, hostName, hostType, hostDesc, hostIp, 0, 0, null, null, 1, new Date()); //注册物理机 boolean result = hostDAO.saveHost(host); if (result) { JSONObject tObj = new JSONObject(); tObj.put("hostname", TimeUtils.encodeText(hostName)); tObj.put("hostdesc", TimeUtils.encodeText(hostDesc)); tObj.put("hostid", hostUuid); tObj.put("hostip", hostIp); tObj.put("hostcpu", host.getHostCpu()); tObj.put("hostmem", host.getHostMem()); tObj.put("createdate", TimeUtils.formatTime(host.getCreateDate())); tObj.put("poolid", ""); tObj.put("poolname", ""); tObj.put("srsize", 0); qaArray.put(tObj); } Date endTime = new Date(); JSONArray infoArray = logRecord.createLoginfos(LogRole.HOST, hostIp); if (result) { OCLog log = logRecord.addSuccessLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushSuccess(userid, log.toString()); } else { OCLog log = logRecord.addFailedLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushError(userid, log.toString()); } return qaArray; } @Override public JSONArray createDockerHost(String hostUuid, String hostName, String hostPwd, String hostDesc, String hostIp, String hostType, int hostCpu, int hostMem, int userid) { Date startTime = new Date(); JSONArray qaArray = new JSONArray(); //添加主机类型的检验(待添加的功能) OCHost host = new OCHost(hostUuid, hostPwd, hostName, hostType, hostDesc, hostIp, hostMem, hostCpu, null, null, 1, new Date()); //注册物理机 boolean result = hostDAO.saveHost(host); if (result) { JSONObject tObj = new JSONObject(); tObj.put("hostname", TimeUtils.encodeText(hostName)); tObj.put("hostdesc", TimeUtils.encodeText(hostDesc)); tObj.put("hostid", hostUuid); tObj.put("hostip", hostIp); tObj.put("hostcpu", host.getHostCpu()); tObj.put("hostmem", host.getHostMem()); tObj.put("hosttype", host.getHostType()); tObj.put("createdate", TimeUtils.formatTime(host.getCreateDate())); tObj.put("poolid", ""); tObj.put("poolname", ""); tObj.put("srsize", 0); qaArray.put(tObj); } Date endTime = new Date(); JSONArray infoArray = logRecord.createLoginfos(LogRole.HOST, hostIp); if (result) { OCLog log = logRecord.addSuccessLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushSuccess(userid, log.toString()); } else { OCLog log = logRecord.addFailedLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushError(userid, log.toString()); } return qaArray; } public JSONArray getHostList(int page, int limit, String search) { JSONArray qaArray = new JSONArray(); int totalNum = hostDAO.countAllHostList(search); List<OCHost> hostList = hostDAO.getOnePageHostList(page, limit, search); qaArray.put(totalNum); for (OCHost result : hostList) { JSONObject tObj = new JSONObject(); tObj.put("hostname", TimeUtils.encodeText(result.getHostName())); tObj.put("hostdesc", TimeUtils.encodeText(result.getHostDesc())); String hostUuid = result.getHostUuid(); Power power = powerDAO.getPowerByHostID(hostUuid); if (power == null) { tObj.put("powerstatus", -1); }else { tObj.put("powerstatus", power.getPowerValid()); } tObj.put("hostid", hostUuid); tObj.put("hostip", result.getHostIP()); tObj.put("hostcpu", result.getHostCpu()); tObj.put("hostmem", result.getHostMem()); tObj.put("hosttype", result.getHostType()); tObj.put("createdate", TimeUtils.formatTime(result.getCreateDate())); String poolId = result.getPoolUuid(); if (poolId == null) { tObj.put("poolid", ""); tObj.put("poolname", ""); } else { tObj.put("poolid", poolId); tObj.put("poolname", TimeUtils.encodeText(poolDAO.getPool( poolId).getPoolName())); } tObj.put("srsize", storageDAO.getStorageSize(hostUuid)); qaArray.put(tObj); } return qaArray; } public JSONArray getHostLoadList(int page, int limit, String searchStr, String srUuid) { int totalNum = hostDAO.countAllHostList(searchStr); JSONArray qaArray = new JSONArray(); List<OCHost> hostList = hostDAO.getOnePageLoadHostList(page, limit, searchStr, srUuid); qaArray.put(totalNum); for (OCHost result : hostList) { JSONObject tObj = new JSONObject(); tObj.put("hostname", TimeUtils.encodeText(result.getHostName())); tObj.put("hostdesc", TimeUtils.encodeText(result.getHostDesc())); tObj.put("hostid", result.getHostUuid()); String poolId = result.getPoolUuid(); if (poolId == null) { poolId = ""; } tObj.put("poolid", poolId); qaArray.put(tObj); } return qaArray; } public JSONArray getSrOfHost(String hostUuid) { List<Storage> srOfHost = hostDAO.getSROfHost(hostUuid); JSONArray qaArray = new JSONArray(); for (int i = 0; i < srOfHost.size(); i++) { Storage sr = srOfHost.get(i); JSONObject obj = new JSONObject(); obj.put("sruuid", sr.getSrUuid()); obj.put("srname", TimeUtils.encodeText(sr.getSrName())); obj.put("srip", sr.getSrAddress()); obj.put("srdir", sr.getSrdir()); obj.put("srtype", sr.getSrtype()); qaArray.put(obj); } return qaArray; } public void unbindSr(String hostUuid, String srUuid, int userid) { if (hostDAO.unbindSr(hostUuid, srUuid)) { message.pushSuccess(userid, "解绑成功"); } else { message.pushError(userid, "解绑失败"); } } public JSONArray isSameSr(String uuidJsonStr) { JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uuidJsonStr); JsonArray ja = je.getAsJsonArray(); JSONArray qaArray = new JSONArray(); boolean isSame = false; if (ja.size() > 0) { if (ja.size() > 1) { String firstUuid = ja.get(0).getAsString(); List<Storage> _srlist1 = hostDAO.getSROfHost(firstUuid); List<String> srlist1 = new ArrayList<String>(); for (Storage storage : _srlist1) { srlist1.add(storage.getSrUuid()); } for (int i = 1; i < ja.size(); i++) { String uuid = ja.get(i).getAsString(); List<Storage> srlist2 = hostDAO.getSROfHost(uuid); for (Storage storage : srlist2) { if (srlist1.contains(storage.getSrUuid())) { srlist1.remove(storage.getSrUuid()); } } if (srlist1.size() == 0) { isSame = true; } else { isSame = false; } } if (isSame) { JSONObject tObj1 = new JSONObject(); tObj1.put("isSuccess", true); qaArray.put(tObj1); } else { JSONObject tObj = new JSONObject(); tObj.put("isSuccess", false); qaArray.put(tObj); } } else { JSONObject tObj = new JSONObject(); tObj.put("isSuccess", true); qaArray.put(tObj); } } else { JSONObject tObj = new JSONObject(); tObj.put("isSuccess", false); qaArray.put(tObj); } return qaArray; } public JSONArray getTablePool(String uuidJsonStr) { JsonParser jp = new JsonParser(); JSONArray qaArray = new JSONArray(); JsonElement je = jp.parse(uuidJsonStr); JsonArray ja = je.getAsJsonArray(); String hostUuid = ja.get(0).getAsString(); List<Storage> _targetList = hostDAO.getSROfHost(hostUuid); List<String> targetList = new ArrayList<String>(); for (Storage storage : _targetList) { targetList.add(storage.getSrUuid()); } List<OCPool> poolList = poolDAO.getPoolList(); for (OCPool pool : poolList) { String poolUuid = pool.getPoolUuid(); String poolName = pool.getPoolName(); String poolMaster = pool.getPoolMaster(); String poolType = pool.getPoolType(); if (poolMaster != null) { List<Storage> compareList = hostDAO.getSROfHost(poolMaster); for (Storage storage : compareList) { if (targetList.contains(storage.getSrUuid())) { targetList.remove(storage.getSrUuid()); } } if (targetList.size() == 0) { JSONObject tObj = new JSONObject(); tObj.put("pooluuid", poolUuid); tObj.put("poolname", TimeUtils.encodeText(poolName)); tObj.put("hasmaster", 1); tObj.put("pooltype", poolType); qaArray.put(tObj); } } else { JSONObject tObj = new JSONObject(); tObj.put("pooluuid", poolUuid); tObj.put("poolname", TimeUtils.encodeText(poolName)); tObj.put("hasmaster", 0); tObj.put("pooltype", poolType); qaArray.put(tObj); } } return qaArray; } private boolean isStandaloneHost(String hostUuid){ OCHost host = hostDAO.getHost(hostUuid); if(host != null){ return host.getPoolUuid() == null || host.getPoolUuid().isEmpty(); }else{ throw new IllegalStateException("Host数据库中没有 uuid为[" + hostUuid +"]的记录"); } } // support standalone host deletion public JSONArray deleteHost(String hostId, String hostName, int userid) { Date startTime = new Date(); JSONArray qaArray = new JSONArray(); boolean result = false; if(isStandaloneHost(hostId)){ // delete directly result = deleteHostDb(hostId, hostName, userid, startTime); }else{ // host in a pool String poolUuid = userDAO.getUser(userid).getUserAllocate(); OCPool pool = poolDAO.getPool(poolUuid); if (hostId.equals(pool.getPoolMaster())) { int hostNumOfPool = hostDAO.getHostListOfPool(poolUuid).size(); if (hostNumOfPool > 1) { message.pushWarning(userid, "资源池内存在从节点,请清空后再删除主节点!"); }else { result = deleteHostDb(hostId, hostName, userid, startTime); } }else { int vmofHost = vmDAO.getVmListByhostUuid(hostId).size(); if (vmofHost != 0) { message.pushWarning(userid, "服务器中内包含正在使用的资源,请清空资源再删除!"); }else { result = deleteHostDb(hostId, hostName, userid, startTime); } } } JSONObject tObj = new JSONObject(); tObj.put("result", result); qaArray.put(tObj); return qaArray; } private boolean deleteHostDb(String hostId, String hostName, int userid, Date startTime) { boolean result; result = hostDAO.deleteHost(hostId); Date endTime = new Date(); JSONArray infoArray = logRecord.createLoginfos(LogRole.HOST, hostName); if (result) { OCLog log = logRecord.addSuccessLog(userid, LogObject.HOST, LogAction.DELETE, infoArray.toString(), startTime, endTime); message.pushSuccess(userid, log.toString()); } else { OCLog log = logRecord.addFailedLog(userid, LogObject.HOST, LogAction.DELETE, infoArray.toString(), startTime, endTime); message.pushError(userid, log.toString()); } return result; } public JSONArray queryAddress(String address) { OCHost query = hostDAO.getHostFromIp(address); JSONObject tObj = new JSONObject(); JSONArray qaArray = new JSONArray(); if (query != null) { tObj.put("exist", true); } else { tObj.put("exist", false); } qaArray.put(tObj); return qaArray; } public OCHost getHostFromIp(String address){ return hostDAO.getHostFromIp(address); } public boolean setPool(String hostUuid, String poolUuid){ return hostDAO.setPool(hostUuid, poolUuid); } public JSONArray add2Pool(String uuidJsonStr, String hasMaster, String poolUuid, int userid) { // TODO Auto-generated method stub return null; } public JSONArray r4Pool(String hostUuid, int userid) { // TODO Auto-generated method stub return null; } public JSONArray getOneHost(String hostid) { OCHost ochost = this.getHostById(hostid); JSONArray qaArray = new JSONArray(); JSONObject jo = new JSONObject(); jo.put("hostName", TimeUtils.encodeText(ochost.getHostName())); jo.put("createDate", TimeUtils.formatTime(ochost.getCreateDate())); String timeUsed = TimeUtils.encodeText(TimeUtils.dateToUsed(ochost .getCreateDate())); jo.put("useDate", timeUsed); jo.put("hostCPU", ochost.getHostCpu()); jo.put("hostMemory", ochost.getHostMem()); jo.put("hostIP", ochost.getHostIP()); jo.put("hostUuid", hostid); jo.put("hostPwd", ochost.getHostPwd()); jo.put("hostDesc", TimeUtils.encodeText(ochost.getHostDesc())); jo.put("hostkernel", ochost.getKernelVersion()); jo.put("hostXen", ochost.getXenVersion()); String poolid = ochost.getPoolUuid(); if (poolid == null || poolid == "") { jo.put("poolId", ""); jo.put("poolName", ""); } else { OCPool ocpool = poolDAO.getPool(poolid); jo.put("poolId", ocpool.getPoolUuid()); jo.put("poolName", TimeUtils.encodeText(ocpool.getPoolName())); } qaArray.put(jo); Set<String> srlist = hostSRDAO.getSRList(hostid); for (String sr : srlist) { JSONObject josr = new JSONObject(); Storage srdao = storageDAO.getStorage(sr); josr.put("srId", srdao.getSrUuid()); josr.put("srName", TimeUtils.encodeText(srdao.getSrName())); qaArray.put(josr); } return qaArray; } public OCHost getMasterOfPool(String poolUuid) { OCHost master = null; if (poolUuid != null) { OCPool pool = poolDAO.getPool(poolUuid); if (pool != null) { String masterUuid = pool.getPoolMaster(); if (masterUuid != null) { master = getHostById(masterUuid); } } } return master; } public boolean updateHost(String hostId, String hostName, String hostDesc, String hostType) { return hostDAO.updateHost(hostId, hostName, hostDesc, hostType); } public boolean updateHost(OCHost host) { return hostDAO.update(host); } public JSONArray getAllList() { JSONArray ja = new JSONArray(); List<OCHost> list = hostDAO.getAllHost(); if (list != null) { for (OCHost oh : list) { JSONObject jo = new JSONObject(); jo.put("hostName", oh.getHostName()); jo.put("hostUuid", oh.getHostUuid()); jo.put("ip", oh.getHostIP()); ja.put(jo); } } return ja; } public boolean recover(int userId, String ip, String username, String password, String content, String conid, String hostUuid) { // TODO Auto-generated method stub return false; } public JSONArray getHostListForMigration(String vmuuid) { String hostuuid = vmDAO.getVM(vmuuid).getVmHostUuid(); OCHost ochost = this.getHostById(hostuuid); String pooluuid = ochost.getPoolUuid(); List<OCHost> list = hostDAO.getHostListOfPool(pooluuid); JSONArray ja = new JSONArray(); if (list.size() > 0) { for (OCHost oh : list) { if (oh.getHostUuid().equals(hostuuid)) continue; JSONObject jo = new JSONObject(); jo.put("ip", oh.getHostIP()); jo.put("hostUuid", oh.getHostUuid()); ja.put(jo); } } return ja; } public List<OCHost> getAllHostNotInPool() { return hostDAO.getAllHost(); } public List<OCHost> getAllHostInPool(String poolUuid) { return hostDAO.getHostListOfPool(poolUuid); } public JSONArray getAllHostOfPool(String poolUuid) { List<OCHost> list = hostDAO.getHostListOfPool(poolUuid); JSONArray ja = new JSONArray(); if (list.size() > 0) { for (OCHost oh : list) { JSONObject jo = new JSONObject(); jo.put("ip", oh.getHostIP()); jo.put("hostuuid", oh.getHostUuid()); jo.put("hostname", oh.getHostName()); ja.put(jo); } } return ja; } public OCHost getHostById(String hostid) { return hostDAO.getHost(hostid); } public boolean activeHost(String key, String ip, String hostid, int userId) { // TODO Auto-generated method stub return false; } public boolean isSameType(String hostUuid, String poolUuid) { boolean result = false; OCHost host = hostDAO.getHost(hostUuid); OCPool pool = poolDAO.getPool(poolUuid); if (host.getHostType().equals(pool.getPoolType())) { result = true; } return result; } @Override public List<OCHost> getAllHost() { return hostDAO.getAllHost(); } @SuppressWarnings("unused") @Override public JSONArray createVSphereHost(String hostUuid, String hostName, String hostPwd, String hostDesc, String hostIp, String hostType, int userid) { try { //创建连接 VMWareUtil.connect("https://"+hostIp+"/sdk","root",hostPwd); } catch (Exception e) { e.printStackTrace(); } //主机属性 List<Map<String, Object>> str = VMWareUtil.printHostProductDetails(); Integer hostMem = 0; Integer hostCpu = 0; String kernelVersion=""; for(Map<String, Object> map:str){ hostUuid = (String) map.get("summary.hardware.uuid"); hostMem = (int)(Double.parseDouble(String.valueOf( map.get("summary.hardware.memorySize")==null?0:map.get("summary.hardware.memorySize")))/1024/1024); hostCpu = (int)Double.parseDouble(String.valueOf( map.get("summary.hardware.numCpuCores")==null?0:map.get("summary.hardware.numCpuCores"))); kernelVersion=(String) map.get("summary.config.product.osType"); } // if(str.length()>0) // { // String[] hostKey2Value = str.split(","); // // hostUuid = hostKey2Value[11]; // hostMem = (int)(Long.parseLong(hostKey2Value[7])/1024/1024); // hostCpu = (int)Long.parseLong(hostKey2Value[9]); // kernelVersion=hostKey2Value[3]; // } Date startTime = new Date(); JSONArray qaArray = new JSONArray(); //添加主机类型的检验(待添加的功能) OCHost host = new OCHost(hostUuid, hostPwd, hostName, hostType, hostDesc, hostIp, hostMem, hostCpu, kernelVersion, null, 1, new Date()); //注入虚拟机 boolean result = hostDAO.saveHost(host); if (result) { JSONObject tObj = new JSONObject(); tObj.put("hostname", TimeUtils.encodeText(hostName)); tObj.put("hostdesc", TimeUtils.encodeText(hostDesc)); tObj.put("hostid", hostUuid); tObj.put("hostip", hostIp); tObj.put("hostcpu", host.getHostCpu()); tObj.put("hostmem", host.getHostMem()); tObj.put("createdate", TimeUtils.formatTime(host.getCreateDate())); tObj.put("poolid", ""); tObj.put("poolname", ""); tObj.put("srsize", 0); qaArray.put(tObj); } //所有虚拟机 List<Map<String,Object>> data0 = new ArrayList<Map<String,Object>>(); data0 = VMWareUtil.vmHardwareinfo(); for(Map<String,Object> map:data0){ String vmUuid=(String) map.get("vmuuids"); String vmPWD="onceas";//onceas String vmName=(String) map.get("vmname"); String vmMac=(String) map.get("mac"); int vmMem = (int) map.get("vmmemry"); int vmCpu = (int) map.get("vmcpu"); int vmPower=PowerConstant.POWER_CREATE;//PowerConstant.POWER_RUNNING int disk = (int) map.get("vmdisck"); if(map.containsKey("")){ } OCVM vm = new OCVM(); vm.setVmUuid(vmUuid); vm.setVmPwd(vmPWD); vm.setVmName(vmName); vm.setVmMac(vmMac); vm.setVmMem(vmMem); vm.setVmDisk(disk); vm.setVmCpu(vmCpu); vm.setVmVlan("-1");// try { String propertyStr = VMWareUtil.callWaitForUpdatesEx("60", "1",vmName) ; String[] pros = propertyStr.split(":"); if("POWERED_ON".equals(pros[1])){ vmPower = PowerConstant.POWER_RUNNING; } if("POWERED_OFF".equals(pros[1])){ vmPower = PowerConstant.POWER_HALTED; } } catch (Exception e) { e.printStackTrace(); } vm.setVmPower(VMPower.values()[vmPower]); vm.setVmHostUuid(hostUuid); vm.setVmCreateDate(new Date()); vm.setVmPlatform(VMPlatform.LINUX); vm.setVmStatus(VMStatus.EXIST); vm.setVmUid(userid); boolean b = vmDAO.saveVmFromVSphere(vm); } Date endTime = new Date(); JSONArray infoArray = logRecord.createLoginfos(LogRole.HOST, hostIp); if (result) { OCLog log = logRecord.addSuccessLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushSuccess(userid, log.toString()); } else { OCLog log = logRecord.addFailedLog(userid, LogObject.HOST, LogAction.ADD, infoArray.toString(), startTime, endTime); message.pushError(userid, log.toString()); } return qaArray; } }
31.440529
153
0.688338
a77f3dfcf05a640f725a8221908e60cfd1bcc6e5
1,503
/* * Copyright (C) J.P. Morrison, Enterprises, Ltd. 2009, 2012 All Rights Reserved. */ package com.jpmorrsn.fbp.examples.networks; import com.jpmorrsn.fbp.components.Discard; import com.jpmorrsn.fbp.engine.Network; import com.jpmorrsn.fbp.examples.components.GenerateTestData; /** This network is intended for timing runs */ public class VolumeTest2 extends Network { static final String copyright = "Copyright 2007, 2008, 2012, J. Paul Morrison. At your option, you may copy, " + "distribute, or make derivative works under the terms of the Clarified Artistic License, " + "based on the Everything Development Company's Artistic License. A document describing " + "this License may be found at http://www.jpaulmorrison.com/fbp/artistic2.htm. " + "THERE IS NO WARRANTY; USE THIS PRODUCT AT YOUR OWN RISK."; @Override protected void define() { component("Generate", GenerateTestData.class); component("Discard", Discard.class); connect(component("Generate"), port("OUT"), component("Discard"), port("IN")); initialize("100000000", component("Generate"), port("COUNT")); /*** on my (AMD 925) machine (4 processors) - JavaFBP 2.6.5 - approx. 1200 secs * approx. 100,000,000 sends, receives each, and 100,000,000 creates and drops each -> * only uses 2 processors, so elapsed time unrealistic * Aug. 11, 2012 * */ } public static void main(final String[] argv) throws Exception { new VolumeTest2().go(); } }
33.4
113
0.696607
88d2f2055ef70598faf0c288258d33d188f24149
13,448
/** * Copyright (c) 2015 LingoChamp Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.liulishuo.qiniuimageloader; import android.content.Context; import android.text.TextUtils; import android.util.Log; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; import javax.microedition.khronos.opengles.GL10; /** * Created by Jacksgong on 15/8/3. * * @Api: http://developer.qiniu.com/docs/v6/api/reference/fop/image/imagemogr2.html */ public class QiniuImageLoader<T extends QiniuImageLoader> { private final static String TAG = "QiniuImageLoader"; private int mode = MODE_FIT_XY; private int w = 0; private int h = 0; private String oriUrl; private ImageView imageView; /** * 限定缩略图的宽最少为<Width>,高最少为<Height>,进行等比缩放,居中裁剪。 * <p/> * 转后的缩略图通常恰好是 <Width>x<Height> 的大小(有一个边缩放的时候会因为超出矩形框而被裁剪掉多余部分)。 * <p/> * 如果只指定 w 参数或只指定 h 参数,代表限定为长宽相等的正方图。 * <p/> * 强制使用给定w与h */ private final static int MODE_CENTER_CROP = 1; /** * 限定缩略图的宽最多为<Width>,高最多为<Height>,进行等比缩放,不裁剪。 * <p/> * 如果只指定 w 参数则表示限定宽(长自适应),只指定 h 参数则表示限定长(宽自适应)。 * <p/> * 如果给定的w或h大于原图,则采用原图 */ private final static int MODE_FIT_XY = 2; /** * 强制需要原图,通常是图片需要动态缩放才需要 */ private final static int MODE_FORCE_ORIGIN = -1; public QiniuImageLoader(final Context context, final String oriUrl) { this.context = context; this.oriUrl = oriUrl; } public QiniuImageLoader(final ImageView imageView, final String oriUrl) { this.imageView = imageView; this.oriUrl = oriUrl; } /** * 指定最大宽度 为w * * @param w * @return */ public T w(final int w) { this.w = w; return (T) this; } /** * 指定最大宽度 * * @param wResource DimenRes * @return */ public T wR(final int wResource) { if (getContext() == null) { return (T) this; } this.w = getContext().getResources().getDimensionPixelSize(wResource); return (T) this; } /** * 指定最大宽高 * * @param size * @return */ public T size(final int size) { w(size); h(size); return (T) this; } /** * 指定最大宽高 * * @param sizeResource DimenRes * @return */ public T sizeR(final int sizeResource) { if (getContext() == null) { return (T) this; } final int size = getContext().getResources().getDimensionPixelSize(sizeResource); size(size); return (T) this; } /** * 指定最大高度 * * @param h * @return */ public T h(final int h) { this.h = h; return (T) this; } /** * 指定最大高度 * * @param hResource DimenRes * @return */ public T hR(final int hResource) { if (getContext() == null) { return (T) this; } this.h = getContext().getResources().getDimensionPixelSize(hResource); return (T) this; } /** * 指定模式为mode * * @param mode * @return */ public T mode(final int mode) { this.mode = mode; return (T) this; } /** * {@link #mode} to {@link #MODE_FIT_XY} * <p/> * 指定模式为FitXY * * @return * @see <url></url>https://github.com/lingochamp/QiniuImageLoader</url> */ public T fitXY() { return mode(MODE_FIT_XY); } /** * 指定模式为CenterCrop * * @return * @see <url>https://github.com/lingochamp/QiniuImageLoader</url> */ public T centerCrop() { return mode(MODE_CENTER_CROP); } /** * 请求图片最大宽高为GL10.GL_MAX_TEXTURE_SIZE * * @return * @see #MODE_FORCE_ORIGIN */ public T forceOrigin() { return mode(MODE_FORCE_ORIGIN); } /** * 根据七牛提供的API生成目标URL * * @return 目标URL * @see <url>http://developer.qiniu.com/docs/v6/api/reference/fop/image/imageview2.html</url> */ public String createQiniuUrl() { String u = this.oriUrl; if (!isUrl(u)) { return u; } int width = this.w; int height = this.h; final int maxWidth = getScreenWith(); final int maxHeight = getMaxHeight(); if (this.mode == MODE_FORCE_ORIGIN) { width = GL10.GL_MAX_TEXTURE_SIZE; height = GL10.GL_MAX_TEXTURE_SIZE; } else { // 其中一个有效 width = (height <= 0 && width > 0 && width > maxWidth) ? maxWidth : width; height = (width <= 0 && height > 0 && height > maxHeight) ? maxHeight : height; // 两个都无效 width = (width <= 0 && height <= 0) ? maxWidth : width; //两个都有效 if (width > 0 && height > 0) { if (width > maxWidth) { height = (int) (height * ((float) maxWidth / width)); width = maxWidth; } if (height > maxHeight) { width = (int) (width * ((float) maxHeight / height)); height = maxHeight; } } } // size /thumbnail/<width>x<height>[>最大宽高/<最小宽高] // /thumbnail/[!]<width>x<height>[r] 限定短边,生成不小于<width>x<height>的 默认不指定!与r,为限定长边 // %3E = URLEncoder.encoder(">", "utf-8") final String maxHeightUtf8 = "%3E"; String resizeParams = ""; if (width > 0 || height > 0) { if (width <= 0) { // h > 0 resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ? // fit xy String.format("/thumbnail/x%d%s", height, maxHeightUtf8) : // center crop String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", height, height, height, height); } else if (height <= 0) { // w > 0 resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ? // fit xy String.format("/thumbnail/%dx%s", width, maxHeightUtf8) : // center crop String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, width, width, width); } else { // h > 0 && w > 0 resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ? // fit xy String.format("/thumbnail/%dx%d%s", width, height, maxHeightUtf8) : // center crop String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, height, width, height); } } //op String opParams = ""; for (Op op : opList) { opParams += op.getOpUrlParam(); } // format String formatParams = ""; switch (this.format) { case webp: case jpg: case gif: case png: formatParams = String.format("/format/%s", this.format.toString()); break; case origin: break; } if (!TextUtils.isEmpty(resizeParams) || !TextUtils.isEmpty(formatParams)) { if (oriUrl.contains("?ImageView") || oriUrl.contains("?imageMogr2") || oriUrl.contains("?imageView2")) { Log.e(TAG, String.format("oriUrl should create 7Niu url by self, %s", oriUrl)); if (!oriUrl.contains("/format")) { u = String.format("%s%s", oriUrl, formatParams); } } else { u = String.format("%s?imageMogr2/auto-orient%s%s%s", oriUrl, resizeParams, opParams, formatParams); } } Log.d(TAG, String.format("【oriUrl】: %s 【url】: %s , (w: %d, h: %d)", oriUrl, u, w, h)); return u; } public void clear() { this.context = null; this.imageView = null; this.mode = MODE_FIT_XY; this.w = 0; this.h = 0; this.opList.clear(); } /** * 宽度等于屏幕的宽度 * * @return */ public T screenW() { if (getContext() == null) { return (T) this; } this.w = getScreenWith(); return (T) this; } /** * 宽度为屏幕的宽度的一半 * * @return */ public T halfScreenW() { if (getContext() == null) { return (T) this; } this.w = getScreenWith() / 2; return (T) this; } /** * @param n n倍 * @return 高度会等于 宽度的n倍 */ public T wTimesN2H(final float n) { this.h = (int) (this.w * n); return (T) this; } private static boolean isUrl(final String url) { return !TextUtils.isEmpty(url) && url.startsWith("http"); } protected Context getContext() { Context context = this.context; if (context == null) { context = this.imageView == null ? null : this.imageView.getContext(); } return context; } // for format private enum Format { origin, jpg, gif, png, webp } private enum OpName { none, blur, rotate } private static class Op { OpName name = OpName.none; int val1; int val2; /** * @param radius [1, 50] * @param sigma [0, -] * @return */ public Op blur(final int radius, final int sigma) { this.name = OpName.blur; this.val1 = radius; this.val2 = sigma; return this; } /** * @param rotateDegree [1, 360] * @return */ public Op rotate(final int rotateDegree) { this.name = OpName.rotate; this.val1 = rotateDegree; return this; } public String getOpUrlParam() { switch (name) { case none: return ""; case blur: return String.format("/blur/%dx%d", this.val1, this.val2); case rotate: return String.format("/rotate/%d", this.val1); } return ""; } } private final static Format COMMEND_FORMAT = Format.webp; private Format format = COMMEND_FORMAT; private List<Op> opList = new ArrayList<>(); /** * 请求图片进行高斯模糊处理 * * @param radius [1, 50] * @param sigma [0, -] * @return */ public T addOpBlur(final int radius, final int sigma) { opList.add(new Op().blur(radius, sigma)); return (T) this; } /** * 请求图片进行旋转处理 * * @param rotateDegree [1, 360] * @return */ public T addOpRotate(final int rotateDegree) { opList.add(new Op().rotate(rotateDegree)); return (T) this; } /** * 请求图片jpg格式 * * @return */ public T formatJpg() { this.format = Format.jpg; return (T) this; } /** * 请求图片原格式 * * @return */ public T formatOrigin() { this.format = Format.origin; return (T) this; } /** * 请求图片png格式 * * @return */ public T formatPng() { this.format = Format.png; return (T) this; } /** * 请求图片webp格式(默认格式) * * @return */ public T formatWebp() { this.format = Format.webp; return (T) this; } private Context context; private int getScreenWith() { return getContext().getResources().getDisplayMetrics().widthPixels; } private int getMaxHeight() { return getContext().getResources().getDisplayMetrics().heightPixels; } /** * 加载图片到目标ImageView上并清理所有变量 * * @see #attachWithNoClear() */ public void attach() { attachWithNoClear(); clear(); } /** * for download & attach image 2 imageView */ public void attachWithNoClear() { throw new UnsupportedOperationException( "Required method instantiateItem was not overridden"); } /** * for just download image */ public void fetch() { throw new UnsupportedOperationException( "Required method instantiateItem was not overridden"); } protected ImageView getImageView() { return imageView; } protected String getOriUrl() { return oriUrl; } protected int getW() { return w; } protected int getH() { return h; } protected int getMode() { return mode; } protected Format getFormat() { return format; } protected List<Op> getOpList() { return opList; } }
23.886323
118
0.513013
da2d3e6733d2d3a82fbc8916e279d582231cf555
8,110
package edu.umass.cs.gigapaxos.paxospackets; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import edu.umass.cs.gigapaxos.paxosutil.Ballot; import edu.umass.cs.utils.Util; /** * @author arun * */ public class BatchedAccept extends PaxosPacket { /** * */ public final Ballot ballot; private int medianCheckpointedSlot; private final TreeMap<Integer, byte[]> slotDigests = new TreeMap<Integer, byte[]>(); private final TreeMap<Integer, Long> slotRequestIDs = new TreeMap<Integer, Long>(); // private final TreeMap<Integer, Integer> slotBatchSizes = new TreeMap<Integer, Integer>(); private final Set<Integer> group; private static final String CHARSET = "ISO-8859-1"; /** * @param accept * @param group */ public BatchedAccept(AcceptPacket accept, Set<Integer> group) { super(accept); this.packetType = PaxosPacketType.BATCHED_ACCEPT; this.ballot = accept.ballot; this.slotDigests.put(accept.slot, (accept.getDigest(null))); this.slotRequestIDs.put(accept.slot, accept.requestID); // this.slotBatchSizes.put(accept.slot, accept.batchSize()); this.group = group; this.medianCheckpointedSlot = accept.getMedianCheckpointedSlot(); } /** * @param json * @throws JSONException */ public BatchedAccept(JSONObject json) throws JSONException { super(json); this.ballot = new Ballot(json.getString(PaxosPacket.NodeIDKeys.B .toString())); this.medianCheckpointedSlot = json.getInt(PaxosPacket.Keys.GC_S .toString()); this.packetType = PaxosPacket.getPaxosPacketType(json); this.group = new HashSet<Integer>(); JSONArray jsonArray = json.getJSONArray(PaxosPacket.NodeIDKeys.GROUP .toString()); for (int i = 0; i < jsonArray.length(); i++) this.group.add(jsonArray.getInt(i)); // slotDigests jsonArray = json.getJSONArray(PaxosPacket.Keys.S_DIGS.toString()); for (int i = 0; i < jsonArray.length(); i++) try { assert(jsonArray.get(0) instanceof JSONArray) : jsonArray.get(0); this.slotDigests.put(jsonArray.getJSONArray(i).getInt(0), jsonArray.getJSONArray(i).getString(1) .getBytes(CHARSET)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // slotRequestIDs jsonArray = json.getJSONArray(PaxosPacket.Keys.S_QIDS.toString()); for (int i = 0; i < jsonArray.length(); i++) this.slotRequestIDs.put(jsonArray.getJSONArray(i).getInt(0), jsonArray .getJSONArray(i).getLong(1)); // slotBatchSizes // jsonArray = json.getJSONArray(PaxosPacket.Keys.S_BS.toString()); // for (int i = 0; i < jsonArray.length(); i++) // this.slotBatchSizes.put(jsonArray.getJSONArray(i).getInt(0), jsonArray // .getJSONArray(i).getInt(1)); } @Override protected JSONObject toJSONObjectImpl() throws JSONException { JSONObject json = new JSONObject(); json.put(PaxosPacket.NodeIDKeys.B.toString(), ballot.toString()); json.put(PaxosPacket.Keys.GC_S.toString(), this.medianCheckpointedSlot); json.put(PaxosPacket.NodeIDKeys.GROUP.toString(), this.group); // slotDigests JSONArray jsonArray = new JSONArray(); for (Integer s : this.slotDigests.keySet()) { JSONArray jarray = new JSONArray(); jarray.put(s); try { jarray.put(new String(this.slotDigests.get(s), CHARSET)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } jsonArray.put(jarray); } json.put(PaxosPacket.Keys.S_DIGS.toString(), jsonArray); // slotRequestIDs jsonArray = new JSONArray(); for (Integer s : this.slotRequestIDs.keySet()) { JSONArray jarray = new JSONArray(); jarray.put(s); jarray.put(this.slotRequestIDs.get(s)); jsonArray.put(jarray); } json.put(PaxosPacket.Keys.S_QIDS.toString(), jsonArray); // // slotBatchSizes // jsonArray = new JSONArray(); // for (Integer s : this.slotBatchSizes.keySet()) { // JSONArray jarray = new JSONArray(); // jarray.put(s); // jarray.put(this.slotBatchSizes.get(s)); // jsonArray.put(jarray); // } // json.put(PaxosPacket.Keys.S_BS.toString(), jsonArray); return json; } @Override protected net.minidev.json.JSONObject toJSONSmartImpl() throws JSONException { net.minidev.json.JSONObject json = new net.minidev.json.JSONObject(); json.put(PaxosPacket.NodeIDKeys.B.toString(), ballot.toString()); json.put(PaxosPacket.Keys.GC_S.toString(), this.medianCheckpointedSlot); json.put(PaxosPacket.NodeIDKeys.GROUP.toString(), this.group); // slotDigests net.minidev.json.JSONArray jsonArray = new net.minidev.json.JSONArray(); for (Integer s : this.slotDigests.keySet()) { net.minidev.json.JSONArray jarray = new net.minidev.json.JSONArray(); jarray.add(s); try { jarray.add(new String(this.slotDigests.get(s), CHARSET)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } jsonArray.add(jarray); } json.put(PaxosPacket.Keys.S_DIGS.toString(), jsonArray); // slotRequestIDs jsonArray = new net.minidev.json.JSONArray(); for (Integer s : this.slotRequestIDs.keySet()) { net.minidev.json.JSONArray jarray = new net.minidev.json.JSONArray(); jarray.add(s); jarray.add(this.slotRequestIDs.get(s)); jsonArray.add(jarray); } json.put(PaxosPacket.Keys.S_QIDS.toString(), jsonArray); // // slotBatchSizes // jsonArray = new net.minidev.json.JSONArray(); // for (Integer s : this.slotBatchSizes.keySet()) { // net.minidev.json.JSONArray jarray = new net.minidev.json.JSONArray(); // jarray.add(s); // jarray.add(this.slotBatchSizes.get(s)); // jsonArray.add(jarray); // } // json.put(PaxosPacket.Keys.S_BS.toString(), jsonArray); return json; } /** * @return Median checkpointed slot. */ public int getMedianCheckpointedSlot() { return this.medianCheckpointedSlot; } /** * @param bAccept * @return True */ public boolean addBatchedAccept(BatchedAccept bAccept) { if (!bAccept.ballot.equals(this.ballot) || !bAccept.paxosID.equals(this.paxosID)) throw new RuntimeException("Unable to combine " + bAccept.getSummary() + " with " + this.getSummary()); if (bAccept.getMedianCheckpointedSlot() - this.medianCheckpointedSlot > 0) this.medianCheckpointedSlot = bAccept.getMedianCheckpointedSlot(); this.slotDigests.putAll(bAccept.slotDigests); this.slotRequestIDs.putAll(bAccept.slotRequestIDs); // this.slotBatchSizes.putAll(bAccept.slotBatchSizes); return true; } /** * @return Group as int[]. */ public int[] getGroup() { return Util.setToIntArray(this.group); } /** * @return Group as set. */ public Set<Integer> getGroupSet() { return this.group; } /** * @param accept */ public void addAccept(AcceptPacket accept) { if (!accept.ballot.equals(this.ballot) || !accept.paxosID.equals(this.paxosID)) throw new RuntimeException("Unable to combine " + accept.getSummary() + " with " + this.getSummary()); if (accept.getMedianCheckpointedSlot() - this.medianCheckpointedSlot > 0) this.medianCheckpointedSlot = accept.getMedianCheckpointedSlot(); this.slotDigests.put(accept.slot, accept.getDigest(null)); this.slotRequestIDs.put(accept.slot, accept.requestID); // this.slotBatchSizes.put(accept.slot, accept.batchSize()); } protected String getSummaryString() { return this.ballot + ":" + this.slotDigests.keySet(); } /** * @return Accept slots. */ public Integer[] getAcceptSlots() { return this.slotDigests.keySet().toArray(new Integer[0]); } /** * @param slot * @return Request ID. */ public Long getRequestID(Integer slot) { return this.slotRequestIDs.get(slot); } /** * @param slot * @return Digest. */ public byte[] getDigest(Integer slot) { return this.slotDigests.get(slot); } /** * @return Size. */ public int size() { return this.slotDigests.size(); } // /** // * @param slot // * @return Batch size for slot // */ // public int batchSize(int slot) { // return this.slotBatchSizes.containsKey(slot) ? this.slotBatchSizes // .get(slot) : 0; // } }
28.86121
92
0.702219
8627cf1686efc76d89ffaa7dcefb3515fa8d38e5
3,796
/* * Copyright (c) 2020 Thomas Neidhart. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.netomi.bat.dexfile; import com.github.netomi.bat.dexfile.io.DexDataInput; import com.github.netomi.bat.dexfile.io.DexDataOutput; import java.util.*; /** * A class representing an encoded catch handler inside a dex file. * * @see <a href="https://source.android.com/devices/tech/dalvik/dex-format#encoded-catch-handler">encoded catch handler @ dex format</a> * * @author Thomas Neidhart */ public class EncodedCatchHandler extends DexContent { //public int size; // sleb128, use handlers.size() private ArrayList<TypeAddrPair> handlers; private int catchAllAddr; // uleb128 public static EncodedCatchHandler of(int catchAllAddr, TypeAddrPair... handlers) { return new EncodedCatchHandler(catchAllAddr, handlers); } public static EncodedCatchHandler readContent(DexDataInput input) { EncodedCatchHandler encodedCatchHandler = new EncodedCatchHandler(); encodedCatchHandler.read(input); return encodedCatchHandler; } private EncodedCatchHandler() { this(-1); } private EncodedCatchHandler(int catchAllAddr, TypeAddrPair... handlers) { this.catchAllAddr = catchAllAddr; this.handlers = new ArrayList<>(handlers.length); this.handlers.addAll(Arrays.asList(handlers)); } public int getCatchAllAddr() { return catchAllAddr; } public int getHandlerCount() { return handlers.size(); } public TypeAddrPair getHandler(int index) { return handlers.get(index); } public Iterable<TypeAddrPair> getHandlers() { return handlers; } @Override protected void read(DexDataInput input) { int readSize = input.readSleb128(); int size = Math.abs(readSize); handlers.clear(); handlers.ensureCapacity(size); for (int i = 0; i < size; i++) { TypeAddrPair typeAddrPair = TypeAddrPair.readContent(input); handlers.add(typeAddrPair); } if (readSize <= 0) { catchAllAddr = input.readUleb128(); } } @Override protected void write(DexDataOutput output) { int writtenSize = handlers.size(); if (catchAllAddr != -1) { writtenSize = -writtenSize; } output.writeSleb128(writtenSize); for (TypeAddrPair typeAddrPair : handlers) { typeAddrPair.write(output); } if (writtenSize <= 0) { output.writeUleb128(catchAllAddr); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EncodedCatchHandler other = (EncodedCatchHandler) o; return catchAllAddr == other.catchAllAddr && Objects.equals(handlers, other.handlers); } @Override public int hashCode() { return Objects.hash(catchAllAddr, handlers); } @Override public String toString() { return String.format("EncodedCatchHandler[handlers=%d,catchAllAddr=%04x]", handlers.size(), catchAllAddr); } }
30.126984
136
0.645943
9b413756bcf583529b3849edb6fcb0853120f52a
3,124
/** * Copyright Plugtree LLC * * 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.idealista.solrmeter.view; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.apache.log4j.Logger; import com.idealista.solrmeter.model.SolrMeterConfiguration; public class I18n { private List<ResourceBundle> resources; private Locale locale; private static I18n instance = new I18n(); private I18n() { Locale locale; if(SolrMeterConfiguration.getProperty("view.locale.country") != null && SolrMeterConfiguration.getProperty("view.locale.language") != null) { locale = new Locale(SolrMeterConfiguration.getProperty("view.locale.language"), SolrMeterConfiguration.getProperty("view.locale.country")); } else if(SolrMeterConfiguration.getProperty("view.locale.language") != null) { locale = new Locale(SolrMeterConfiguration.getProperty("view.locale.language")); } else { locale = Locale.getDefault(); } Logger.getLogger(this.getClass()).info("Using Locale " + locale); this.locale = locale; // http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=d7adaa31e312a97d6d0854a3fc241?bug_id=4303146 this.resources = this.getResources(locale); } private List<ResourceBundle> getResources(Locale locale) { List<ResourceBundle> list = new LinkedList<>(); if(this.getClass().getClassLoader().getResource(("messages_" + locale.getLanguage() + "_" + locale.getCountry() + ".properties")) != null) { list.add(ResourceBundle.getBundle("messages_" + locale.getLanguage() + "_" + locale.getCountry())); } if(this.getClass().getClassLoader().getResource(("messages_" + locale.getLanguage() + ".properties")) != null) { list.add(ResourceBundle.getBundle("messages_" + locale.getLanguage())); } list.add(ResourceBundle.getBundle("messages", new Locale("", ""))); return list; } public static void onConfigurationChange() { instance = new I18n(); } public static String get(String key) { for(ResourceBundle resourceBundle:instance.resources) { if(resourceBundle.containsKey(key)) { try { return new String(resourceBundle.getString(key).getBytes(Charset.forName("ISO-8859-1")), "UTF-8"); } catch (UnsupportedEncodingException e) { return ""; } } } throw new RuntimeException("No resource value for key " + key); } public static Locale getLocale() { return instance.locale; } }
35.101124
143
0.708067
3d5c5cc9471aa0ae6737d96836bd6c77bc187732
477
package br.com.zupacademy.apass.mercadolivre.util; import java.text.Normalizer; import java.util.regex.Pattern; public class DiacriticoUtil { public static String removeDiacriticos(String stringComDiacriticos) { String nfdNormalizedString = Normalizer.normalize(stringComDiacriticos, Normalizer.Form.NFD); Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); return pattern.matcher(nfdNormalizedString).replaceAll(""); } }
34.071429
101
0.765199
9099a0008c6276fffaaea659777e5465dbc38f92
3,913
package com.centurylink.mdw.model.workflow; import java.text.ParseException; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.centurylink.mdw.model.InstanceList; import com.centurylink.mdw.model.JsonObject; import com.centurylink.mdw.model.Jsonable; /** * A collection of workflow process instances. */ public class ProcessList implements Jsonable, InstanceList<ProcessInstance> { public static final String PROCESS_INSTANCES = "processInstances"; public ProcessList(String name, String json) throws JSONException, ParseException { this(name, new JsonObject(json)); } public ProcessList(String name, JSONObject jsonObj) throws JSONException, ParseException { this.name = name; if (jsonObj.has("retrieveDate")) retrieveDate = (java.time.Instant)jsonObj.get("retrieveDate"); if (jsonObj.has("count")) count = jsonObj.getInt("count"); if (jsonObj.has("total")) total = jsonObj.getLong("total"); else if (jsonObj.has("totalCount")) total = jsonObj.getLong("totalCount"); // compatibility JSONArray processList = jsonObj.getJSONArray(name); for (int i = 0; i < processList.length(); i++) processes.add(new ProcessInstance((JSONObject)processList.get(i))); } public ProcessList(String name, List<ProcessInstance> processes) { this.name = name; this.processes = processes; if (processes != null) this.count = processes.size(); } public String getJsonName() { return name; } public JSONObject getJson() throws JSONException { JSONObject json = create(); if (retrieveDate != null) json.put("retrieveDate", (getRetrieveDate())); if (count != -1) json.put("count", count); if (total != -1) { json.put("total", total); json.put("totalCount", total); // compatibility } JSONArray array = new JSONArray(); if (processes != null) { for (ProcessInstance process : processes) array.put(process.getJson()); } json.put(name, array); return json; } private String name; public String getName() { return name;} public void setName(String name) { this.name = name; } private Instant retrieveDate; public Instant getRetrieveDate() { return retrieveDate; } public void setRetrieveDate(Date d) { this.retrieveDate = d.toInstant(); } private int count = -1; public int getCount() { return count; } public void setCount(int ct) { this.count = ct; } private long total = -1; public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } private List<ProcessInstance> processes = new ArrayList<ProcessInstance>(); public List<ProcessInstance> getProcesses() { return processes; } public void setProcesses(List<ProcessInstance> processes) { this.processes = processes; } public List<ProcessInstance> getItems() { return processes; } public void addProcess(ProcessInstance process) { processes.add(process); } public ProcessInstance getProcess(Long processInstanceId) { for (ProcessInstance process : processes) { if (process.getId().equals(processInstanceId)) return process; } return null; } public int getIndex(Long processInstanceId) { for (int i = 0; i < processes.size(); i++) { if (processes.get(i).getId().equals(processInstanceId)) return i; } return -1; } public int getIndex(String id) { return (getIndex(Long.parseLong(id))); } }
32.338843
94
0.637107