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
f408bfb239e7c88310581b7249c0667d9ed6b52f
6,787
package com.cloudplugs.util; /*<license> Copyright 2014 CloudPlugs Inc. 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. </license>*/ import com.cloudplugs.rest.RestManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @brief Tool class for validating parameters for making remote requests. * Every method throws an IllegalArgumentException if the given argument is not valid. * This class is for internal usage. */ public final class Validate { public static final int MIN_PASS_LENGTH = 4; public static final int MIN_HWID_LENGTH = 1; public static void oid(String id) { if(!PlugId.isOid(id)) throw new IllegalArgumentException("null id"); } public static void oids(String[] ids) { if(ids == null) throw new IllegalArgumentException("null id array"); int n = ids.length; if(n == 0) throw new IllegalArgumentException("empty id array"); while(--n >= 0) if(!PlugId.isOid(ids[n])) throw new IllegalArgumentException("invalid id at array index "+n); } public static void plugIds(String[] idPlugs) { if(idPlugs == null) throw new IllegalArgumentException("null device plug id array"); int n = idPlugs.length; if(n == 0) throw new IllegalArgumentException("empty plug id array"); while(--n >= 0) if(!PlugId.is(idPlugs[n])) throw new IllegalArgumentException("invalid plug id at array index "+n); } public static void devIds(String[] idPlugs) { if(idPlugs == null) throw new IllegalArgumentException("null device plug id array"); int n = idPlugs.length; if(n == 0) throw new IllegalArgumentException("empty device plug id array"); while(--n >= 0) if(!PlugId.isDev(idPlugs[n])) throw new IllegalArgumentException("invalid device plug id at array index "+n); } public static void devId(String idPlug) { if(!PlugId.isDev(idPlug)) throw new IllegalArgumentException("invalid device plug id"); } public static void devIdCsv(String idPlugCsv) { if(!PlugId.isDevCsv(idPlugCsv)) throw new IllegalArgumentException("invalid device plug id"); } public static void modelId(String idPlug) { if(!PlugId.isModel(idPlug)) throw new IllegalArgumentException("invalid model plug id"); } public static void plugId(String idPlug) { if(!PlugId.is(idPlug)) throw new IllegalArgumentException("invalid plug id"); } public static void plugIdCsv(String idPlugCsv) { if(!PlugId.isCsv(idPlugCsv)) throw new IllegalArgumentException("invalid plug id"); } public static void channelMask(String channel) { if(!Channel.isMask(channel)) throw new IllegalArgumentException("invalid channel mask"); } public static void channelName(String channel) { if(!Channel.isName(channel)) throw new IllegalArgumentException("invalid channel name"); } public static void hwid(String hwid, String name) { str(hwid, MIN_HWID_LENGTH, name); } public static void hwid(String hwid) { hwid(hwid, "hwid"); } public static void pass(String pass) { str(pass, MIN_PASS_LENGTH, "pass"); } public static void body(String body) { json(body, "invalid body", false); } public static void json(String json, String msg, boolean allowNull) { if(json == null) { if(allowNull) return; } else if(Json.is(json)) { return; } throw new IllegalArgumentException(msg==null ? "invalid json" : msg); } public static void prop(String prop) { str(prop, 1, "prop"); } public static void name(String name) { str(name, 1, "name"); } public static void status(String status) { if(RestManager.STATUS_OK.equals(status) || RestManager.STATUS_DISABLED.equals(status) || RestManager.STATUS_REACTIVATE.equals(status)) return; throw new IllegalArgumentException("invalid status"); } public static void perm(JSONObject perm) { if(perm != null) { int e = 0; int n = perm.length(); if(perm.has("of")) { try { subperm("of", perm.get("of")); e++; } catch(JSONException ex) {} } if(perm.has("ch")) { try { subperm("ch", perm.get("ch")); e++; } catch(JSONException ex) {} } if(perm.has("ctrl")) { try { Object ctrl = perm.get("ctrl"); if(ctrl == null || "rw".equals(ctrl) || "r".equals(ctrl) || "".equals(ctrl)) e++; else throw new IllegalArgumentException("invalid perm.ctrl: it must be null, an empty string, \"rw\" or \"r\""); } catch(JSONException ex) { throw new IllegalArgumentException("invalid json: unable to read perm.ctrl"); } } if(n == e) return; } throw new IllegalArgumentException("invalid perm: it must be null or a JSONObject containing only \"of\", \"ch\" and/or \"ctrl\" fields"); } private static void subperm(String name, Object o) { if(o == null) return; if(o instanceof JSONObject) { JSONObject perm = (JSONObject)o; int e = 0; int n = perm.length(); if(perm.has("r")) { try { Object r = perm.get("r"); if(r == null || r instanceof JSONArray) e++; else throw new IllegalArgumentException("invalid perm." + name + "." + ".r: it must be null or JSONArray"); } catch(JSONException ex) { throw new IllegalArgumentException("invalid json: unable to read perm." + name + 'r'); } } if(perm.has("w")) { try { Object w = perm.get("w"); if(w == null || w instanceof JSONArray) e++; else throw new IllegalArgumentException("invalid perm." + name + "." + ".w: it must be null or JSONArray"); } catch(JSONException ex) { throw new IllegalArgumentException("invalid json: unable to read perm." + name + 'w'); } } if(n == e) return; } throw new IllegalArgumentException("invalid perm field \""+name+"\": it must be null or a JSONObject containing only \"r\" and/or \"w\" fields (each one can be null or JSONArray)"); } public static void str(String str, int minLength, String name) { if(str == null) throw new IllegalArgumentException("null "+name); if(str.length() < minLength) throw new IllegalArgumentException("empty "+name); } public static void pos(int num, String name) { if(num < 0) throw new IllegalArgumentException("negative "+name); } }
33.269608
183
0.695447
9dd8d1437e556b8e49f7227cb57123f6796c0695
6,207
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.restconf.utils; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.commons.io.IOUtils; import org.onlab.osgi.DefaultServiceDirectory; import org.onosproject.restconf.api.RestconfException; import org.onosproject.restconf.utils.exceptions.RestconfUtilsException; import org.onosproject.yang.model.DataNode; import org.onosproject.yang.model.ResourceData; import org.onosproject.yang.model.ResourceId; import org.onosproject.yang.runtime.CompositeData; import org.onosproject.yang.runtime.CompositeStream; import org.onosproject.yang.runtime.DefaultCompositeData; import org.onosproject.yang.runtime.DefaultCompositeStream; import org.onosproject.yang.model.DefaultResourceData; import org.onosproject.yang.runtime.DefaultRuntimeContext; import org.onosproject.yang.runtime.RuntimeContext; import org.onosproject.yang.runtime.YangRuntimeService; import java.io.IOException; import java.io.InputStream; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; /** * Utilities used by the RESTCONF app. */ public final class RestconfUtils { /** * No instantiation. */ private RestconfUtils() { } /** * Data format required by YangRuntime Service. */ private static final String JSON_FORMAT = "JSON"; private static final YangRuntimeService YANG_RUNTIME = DefaultServiceDirectory.getService(YangRuntimeService.class); /** * Converts an input stream to JSON objectNode. * * @param inputStream the InputStream from Resource Data * @return JSON representation of the data resource */ public static ObjectNode convertInputStreamToObjectNode(InputStream inputStream) { ObjectNode rootNode; ObjectMapper mapper = new ObjectMapper(); try { rootNode = (ObjectNode) mapper.readTree(inputStream); } catch (IOException e) { throw new RestconfUtilsException("ERROR: InputStream failed to parse"); } return rootNode; } /** * Convert ObjectNode to InputStream. * * @param rootNode JSON representation of the data resource * @return the InputStream from Resource Data */ public static InputStream convertObjectNodeToInputStream(ObjectNode rootNode) { String json = rootNode.toString(); InputStream inputStream; try { inputStream = IOUtils.toInputStream(json); } catch (Exception e) { throw new RestconfUtilsException("ERROR: Json Node failed to parse"); } return inputStream; } /** * Convert URI to ResourceId. * * @param uri URI of the data resource * @return resource identifier */ public static ResourceId convertUriToRid(String uri) { ResourceData resourceData = convertJsonToDataNode(uri, null); return resourceData.resourceId(); } /** * Convert URI and ObjectNode to ResourceData. * * @param uri URI of the data resource * @param rootNode JSON representation of the data resource * @return represents type of node in data store */ public static ResourceData convertJsonToDataNode(String uri, ObjectNode rootNode) { RuntimeContext.Builder runtimeContextBuilder = new DefaultRuntimeContext.Builder(); runtimeContextBuilder.setDataFormat(JSON_FORMAT); RuntimeContext context = runtimeContextBuilder.build(); InputStream jsonData = null; if (rootNode != null) { jsonData = convertObjectNodeToInputStream(rootNode); } CompositeStream compositeStream = new DefaultCompositeStream(uri, jsonData); // CompositeStream --- YangRuntimeService ---> CompositeData. CompositeData compositeData = YANG_RUNTIME.decode(compositeStream, context); ResourceData resourceData = compositeData.resourceData(); return resourceData; } /** * Convert Resource Id and Data Node to Json ObjectNode. * * @param rid resource identifier * @param dataNode represents type of node in data store * @return JSON representation of the data resource */ public static ObjectNode convertDataNodeToJson(ResourceId rid, DataNode dataNode) { RuntimeContext.Builder runtimeContextBuilder = DefaultRuntimeContext.builder(); runtimeContextBuilder.setDataFormat(JSON_FORMAT); RuntimeContext context = runtimeContextBuilder.build(); DefaultResourceData.Builder resourceDataBuilder = DefaultResourceData.builder(); resourceDataBuilder.addDataNode(dataNode); resourceDataBuilder.resourceId(rid); ResourceData resourceData = resourceDataBuilder.build(); DefaultCompositeData.Builder compositeDataBuilder = DefaultCompositeData.builder(); compositeDataBuilder.resourceData(resourceData); CompositeData compositeData = compositeDataBuilder.build(); // CompositeData --- YangRuntimeService ---> CompositeStream. CompositeStream compositeStream = YANG_RUNTIME.encode(compositeData, context); InputStream inputStream = compositeStream.resourceData(); ObjectNode rootNode = convertInputStreamToObjectNode(inputStream); if (rootNode == null) { throw new RestconfException("ERROR: InputStream can not be convert to ObjectNode", INTERNAL_SERVER_ERROR); } return rootNode; } }
39.535032
94
0.709038
8fd138fd0914aff685319117a25e1c7232db6919
2,676
/* * Copyright 2000-2008 JetBrains s.r.o. * * 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.jetbrains.plugins.ruby.settings; import static org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorOptions.Option; import javax.annotation.Nonnull; import org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorOptions; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vcs.VcsShowConfirmationOption; import com.intellij.openapi.vcs.VcsShowConfirmationOptionImpl; import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx; /** * Created by IntelliJ IDEA. * * @author: Roman Chernyatchik * @date: 25.05.2007 */ public class RProjectUtil { public static boolean isVcsAddSilently(@Nonnull final Project project) { final VcsShowConfirmationOptionImpl opt = ProjectLevelVcsManagerEx.getInstanceEx(project).getConfirmation(VcsConfiguration.StandardConfirmation.ADD); return opt.getValue() == VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY; } public static boolean isVcsAddNothingSilently(@Nonnull final Project project) { final VcsShowConfirmationOptionImpl opt = ProjectLevelVcsManagerEx.getInstanceEx(project).getConfirmation(VcsConfiguration.StandardConfirmation.ADD); return opt.getValue() == VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY; } public static boolean isVcsAddShowConfirmation(@Nonnull final Project project) { final VcsShowConfirmationOptionImpl opt = ProjectLevelVcsManagerEx.getInstanceEx(project).getConfirmation(VcsConfiguration.StandardConfirmation.ADD); return opt.getValue() == VcsShowConfirmationOption.Value.SHOW_CONFIRMATION; } public static GeneratorOptions getGeneratorsOptions(@Nonnull final Project project) { final GeneratorOptions options = RProjectSettings.getInstance(project).getGeneratorsOptions(); final boolean showConfirmation = isVcsAddShowConfirmation(project); options.setOption(Option.SVN_SHOW_CONFIRMATION, showConfirmation); if(!showConfirmation) { // set SVN option from Vcs settings options.setOption(Option.SVN, isVcsAddSilently(project)); } return options; } }
37.690141
151
0.80568
a7c1ba32b24cd640aaa52c20b6fa6c8ce8335af9
1,006
package zone.cogni.asquare.security.saml.extension.entity; import org.opensaml.saml2.metadata.LocalizedString; /** * SAML Organisation Entity * * @author Patrick Lezy * @see org.opensaml.saml2.metadata.Organization */ public class CHOrganization { private LocalizedString name; private LocalizedString displayName; private LocalizedString url; public CHOrganization(LocalizedString name, LocalizedString displayName, LocalizedString url) { this.name = name; this.displayName = displayName; this.url = url; } public CHOrganization() { } public LocalizedString getName() { return name; } public void setName(LocalizedString name) { this.name = name; } public LocalizedString getDisplayName() { return displayName; } public void setDisplayName(LocalizedString displayName) { this.displayName = displayName; } public LocalizedString getUrl() { return url; } public void setUrl(LocalizedString url) { this.url = url; } }
20.12
97
0.722664
0824bb0a97f41717b3113b185c99d76fc87388db
1,594
package org.atalk.android.util.javax.sound.sampled; import java.io.IOException; import java.net.URL; public class AudioSystem { /** * An integer that stands for an unknown numeric value. * This value is appropriate only for signed quantities that do not * normally take negative values. Examples include file sizes, frame * sizes, buffer sizes, and sample rates. * A number of Java Sound constructors accept * a value of <code>NOT_SPECIFIED</code> for such parameters. Other * methods may also accept or return this value, as documented. */ public static final int NOT_SPECIFIED = -1; /** * Obtains an audio input stream from the URL provided. The URL must * point to valid audio file data. * * @param url * the URL for which the <code>AudioInputStream</code> should be * constructed * @return an <code>AudioInputStream</code> object based on the audio file data pointed * to by the URL * @throws UnsupportedAudioFileException * if the URL does not point to valid audio * file data recognized by the system * @throws IOException * if an I/O exception occurs */ public static AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { return null; } public static AudioFormat[] getTargetFormats(AudioFormat.Encoding targetEncoding, AudioFormat sourceFormat) { return new AudioFormat[0]; } }
35.422222
112
0.651819
ea8aff13316881546d77b43cc5dab9a47b845550
338
package com.thread.volatil; /** * Created by wangyong on 2016/8/18. */ public class Runner { public static void main(String[] args) { Service service = new Service(); new Thread(new ThreadA(service)).start(); new Thread(new ThreadB(service)).start(); System.out.println("已经发起了停止指令... "); } }
19.882353
49
0.612426
65ccd236c4eae8e2c092c213fc14ec449e7c9fef
6,180
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|table operator|. name|misc operator|. name|properties package|; end_package begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|StatsSetupConst import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|TableType import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|DDLOperationContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|table operator|. name|AbstractAlterTableOperation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|io operator|. name|AcidUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|HiveException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|Partition import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|metadata operator|. name|Table import|; end_import begin_comment comment|/** * Operation process of unsetting properties of a table. */ end_comment begin_class specifier|public class|class name|AlterTableUnsetPropertiesOperation extends|extends name|AbstractAlterTableOperation argument_list|< name|AlterTableUnsetPropertiesDesc argument_list|> block|{ specifier|public name|AlterTableUnsetPropertiesOperation parameter_list|( name|DDLOperationContext name|context parameter_list|, name|AlterTableUnsetPropertiesDesc name|desc parameter_list|) block|{ name|super argument_list|( name|context argument_list|, name|desc argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|protected name|void name|doAlteration parameter_list|( name|Table name|table parameter_list|, name|Partition name|partition parameter_list|) throws|throws name|HiveException block|{ if|if condition|( name|StatsSetupConst operator|. name|USER operator|. name|equals argument_list|( name|environmentContext operator|. name|getProperties argument_list|() operator|. name|get argument_list|( name|StatsSetupConst operator|. name|STATS_GENERATED argument_list|) argument_list|) condition|) block|{ comment|// drop a stats parameter, which triggers recompute stats update automatically name|environmentContext operator|. name|getProperties argument_list|() operator|. name|remove argument_list|( name|StatsSetupConst operator|. name|DO_NOT_UPDATE_STATS argument_list|) expr_stmt|; block|} if|if condition|( name|partition operator|== literal|null condition|) block|{ name|Set argument_list|< name|String argument_list|> name|removedSet init|= name|desc operator|. name|getProps argument_list|() operator|. name|keySet argument_list|() decl_stmt|; name|boolean name|isFromMmTable init|= name|AcidUtils operator|. name|isInsertOnlyTable argument_list|( name|table operator|. name|getParameters argument_list|() argument_list|) decl_stmt|; name|boolean name|isRemoved init|= name|AcidUtils operator|. name|isRemovedInsertOnlyTable argument_list|( name|removedSet argument_list|) decl_stmt|; if|if condition|( name|isFromMmTable operator|&& name|isRemoved condition|) block|{ throw|throw operator|new name|HiveException argument_list|( literal|"Cannot convert an ACID table to non-ACID" argument_list|) throw|; block|} comment|// Check if external table property being removed if|if condition|( name|removedSet operator|. name|contains argument_list|( literal|"EXTERNAL" argument_list|) operator|&& name|table operator|. name|getTableType argument_list|() operator|== name|TableType operator|. name|EXTERNAL_TABLE condition|) block|{ name|table operator|. name|setTableType argument_list|( name|TableType operator|. name|MANAGED_TABLE argument_list|) expr_stmt|; block|} block|} for|for control|( name|String name|key range|: name|desc operator|. name|getProps argument_list|() operator|. name|keySet argument_list|() control|) block|{ if|if condition|( name|partition operator|!= literal|null condition|) block|{ name|partition operator|. name|getTPartition argument_list|() operator|. name|getParameters argument_list|() operator|. name|remove argument_list|( name|key argument_list|) expr_stmt|; block|} else|else block|{ name|table operator|. name|getTTable argument_list|() operator|. name|getParameters argument_list|() operator|. name|remove argument_list|( name|key argument_list|) expr_stmt|; block|} block|} block|} block|} end_class end_unit
15.036496
813
0.798544
05255b942ae8f6928d5caa4be8939c9d8fd6fcdb
355
package com.shanjingtech.secumchat.db; import androidx.room.ColumnInfo; /** * Created by flamearrow on 4/1/18. */ public class GroupId { @ColumnInfo(name = "group_id") private String groupId; public void setGroupId(String groupId) { this.groupId = groupId; } public String getGroupId() { return groupId; } }
16.904762
44
0.653521
87b29422babe9c528560ee343186a772c4c7bfd4
63
package coordinates; public interface CoordinateTransform { }
12.6
38
0.825397
96b77247fe68169f22256f2da3e0c6a89f45509c
1,748
package logbook.api; import java.util.LinkedHashSet; import java.util.Map; import java.util.stream.Collectors; import javax.json.JsonObject; import logbook.bean.Ndock; import logbook.bean.NdockCollection; import logbook.bean.Ship; import logbook.bean.ShipCollection; import logbook.proxy.RequestMetaData; import logbook.proxy.ResponseMetaData; /** * /kcsapi/api_req_nyukyo/speedchange * */ @API("/kcsapi/api_req_nyukyo/speedchange") public class ApiReqNyukyoSpeedchange implements APIListenerSpi { @Override public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) { Map<Integer, Ndock> ndockMap = NdockCollection.get() .getNdockMap(); Integer ndockId = Integer.valueOf(req.getParameter("api_ndock_id")); Ndock ndock = ndockMap.get(ndockId); Map<Integer, Ship> shipMap = ShipCollection.get() .getShipMap(); Integer shipId = ndock.getShipId(); Ship ship = shipMap.get(shipId).clone(); // 艦娘を修理完了状態にする ship.setNowhp(ship.getMaxhp()); ship.setNdockTime(0); if (ship.getCond() < 40) { ship.setCond(40); } shipMap.put(shipId, ship); // 高速修復材を使った入渠ドックを初期化 ndock.setCompleteTime(0L); ndock.setShipId(-1); ndock.setState(0); ndockMap.put(ndockId, ndock); // 入渠中の艦娘 NdockCollection.get() .setNdockSet(ndockMap.entrySet() .stream() .map(Map.Entry::getValue) .map(Ndock::getShipId) .collect(Collectors.toCollection(LinkedHashSet::new))); } }
28.655738
85
0.604691
bc86d73f7794ef7d95ffa4e6bea6d7c98febb59a
3,638
package wzp.com.texturemusic.util; import android.content.Context; import android.content.SharedPreferences; import com.alibaba.fastjson.JSONObject; import wzp.com.texturemusic.MyApplication; import wzp.com.texturemusic.bean.MusicBean; import wzp.com.texturemusic.core.config.AppConstant; /** * Created by Go_oG * Description:应用设置工具类 * on 2017/9/24. * xml文件名字为 AppConstant.SP_NAME_APP_SET常量对应的string */ public class SPSetingUtil { public static void setBooleanValue(String keyName, boolean value) { SharedPreferences sharedPreferences = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(keyName, value); editor.apply(); } public static boolean getBooleanValue(String keyName, boolean defValue) { SharedPreferences sp = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); return sp.getBoolean(keyName, defValue); } public static void setStringValue(String keyName, String value) { SharedPreferences sharedPreferences = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(keyName, value); editor.apply(); } public static String getStringValue(String keyName, String defValue) { SharedPreferences sp = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); return sp.getString(keyName, defValue); } public static void setIntValue(String keyName, int value) { SharedPreferences sharedPreferences = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(keyName, value); editor.apply(); } public static int getIntValue(String keyName, int defValue) { SharedPreferences sp = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); return sp.getInt(keyName, defValue); } public static SharedPreferences getSettingSP() { return MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_APP_SET, Context.MODE_PRIVATE); } /** * 保存播放的音乐数据 * * @param musicBean */ public static void saveMusicData(MusicBean musicBean) { if (musicBean != null) { SharedPreferences sharedPreferences = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_SAVE_MUSIC, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); String json = JSONObject.toJSONString(musicBean); editor.putString(AppConstant.SP_KEY_MUSIC_INFO, json); editor.apply(); } } public static MusicBean getSaveMusicData() { MusicBean bean; SharedPreferences sp = MyApplication.getInstace() .getSharedPreferences(AppConstant.SP_NAME_SAVE_MUSIC, Context.MODE_PRIVATE); String json = sp.getString(AppConstant.SP_KEY_MUSIC_INFO, ""); if (!StringUtil.isEmpty(json)) { bean = JSONObject.parseObject(json, MusicBean.class); } else { bean = null; } return bean; } }
36.747475
96
0.692139
a7b04a6debacdd69ec910de25fcf74c112dd5410
18,511
/** * The MIT License (MIT) * * MSUSEL Quamoco Implementation * Copyright (c) 2015-2017 Montana State University, Gianforte School of Computing, * Software Engineering Laboratory * * 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 edu.montana.gsoc.msusel.quamoco.model.qmr; import java.util.List; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import edu.montana.gsoc.msusel.quamoco.model.AbstractEntity; import edu.montana.gsoc.msusel.quamoco.model.qmr.AbstractResult; import edu.montana.gsoc.msusel.quamoco.model.qmr.EvaluationResult; import edu.montana.gsoc.msusel.quamoco.model.qmr.MeasurementResult; import edu.montana.gsoc.msusel.quamoco.model.qmr.QualityModelResult; /** * The class <code>QualityModelResultTest</code> contains tests for the class * <code>{@link QualityModelResult}</code>. * * @generatedBy CodePro at 5/30/15 3:49 PM * @author isaac * @version $Revision: 1.0 $ */ public class QualityModelResultTest { /** * Run the QualityModelResult(String,String) constructor test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testQualityModelResult_1() throws Exception { final String date = ""; final String system = ""; final QualityModelResult result = new QualityModelResult(date, system); // TODO: add additional test code here Assert.assertNotNull(result); Assert.assertEquals("", result.getSystem()); Assert.assertEquals("", result.getDate()); } /** * Run the void addEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddEvalResult_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = null; fixture.addEvalResult(result); // TODO: add additional test code here Assert.assertEquals(1, fixture.getEvaluationResults().size()); } /** * Run the void addEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddEvalResult_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = new EvaluationResult(); result.setId("new"); fixture.addEvalResult(result); // TODO: add additional test code here Assert.assertEquals(2, fixture.getEvaluationResults().size()); } /** * Run the void addEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddEvalResult_3() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = new EvaluationResult(); fixture.addEvalResult(result); Assert.assertEquals(1, fixture.getEvaluationResults().size()); } /** * Run the void addMeasureResult(MeasurementResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddMeasureResult_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final MeasurementResult result = null; fixture.addMeasureResult(result); // TODO: add additional test code here Assert.assertEquals(1, fixture.getMeasurementResults().size()); } /** * Run the void addMeasureResult(MeasurementResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddMeasureResult_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final MeasurementResult result = new MeasurementResult(); result.setId("new"); fixture.addMeasureResult(result); // TODO: add additional test code here Assert.assertEquals(2, fixture.getMeasurementResults().size()); } /** * Run the void addMeasureResult(MeasurementResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testAddMeasureResult_3() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final MeasurementResult result = new MeasurementResult(); fixture.addMeasureResult(result); // TODO: add additional test code here Assert.assertEquals(1, fixture.getMeasurementResults().size()); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final QualityModelResult obj = new QualityModelResult("", ""); obj.addMeasureResult(new MeasurementResult()); obj.addEvalResult(new EvaluationResult()); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(true, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = null; final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(false, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_3() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = new Object(); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(false, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_4() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = new QualityModelResult("", ""); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(true, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_5() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = new QualityModelResult("", ""); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(true, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_6() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = new QualityModelResult("", ""); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(true, result); } /** * Run the boolean equals(Object) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testEquals_7() throws Exception { final QualityModelResult fixture = new QualityModelResult("", (String) null); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final Object obj = new QualityModelResult("", (String) null); final boolean result = fixture.equals(obj); // TODO: add additional test code here Assert.assertEquals(true, result); } /** * Run the List<AbstractResult> getContained() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testGetContained_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final List<AbstractResult> result = fixture.getContained(); // TODO: add additional test code here Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); } /** * Run the String getDate() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testGetDate_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final String result = fixture.getDate(); // TODO: add additional test code here Assert.assertEquals("", result); } /** * Run the List<EvaluationResult> getEvaluationResults() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testGetEvaluationResults_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final List<EvaluationResult> result = fixture.getEvaluationResults(); // TODO: add additional test code here Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); } /** * Run the List<MeasurementResult> getMeasurementResults() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testGetMeasurementResults_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final List<MeasurementResult> result = fixture.getMeasurementResults(); // TODO: add additional test code here Assert.assertNotNull(result); Assert.assertEquals(1, result.size()); } /** * Run the String getSystem() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testGetSystem_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final String result = fixture.getSystem(); // TODO: add additional test code here Assert.assertEquals("", result); } /** * Run the int hashCode() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testHashCode_1() throws Exception { final QualityModelResult fixture = new QualityModelResult((String) null, ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final int result = fixture.hashCode(); // TODO: add additional test code here Assert.assertEquals(961, result); } /** * Run the int hashCode() method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testHashCode_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", (String) null); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final int result = fixture.hashCode(); // TODO: add additional test code here Assert.assertEquals(961, result); } /** * Run the void removeEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveEvalResult_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = null; fixture.removeEvalResult(result); Assert.assertEquals(1, fixture.getEvaluationResults().size()); } /** * Run the void removeEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveEvalResult_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = new EvaluationResult(); fixture.removeEvalResult(result); Assert.assertEquals(0, fixture.getEvaluationResults().size()); } /** * Run the void removeEvalResult(EvaluationResult) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveEvalResult_3() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final EvaluationResult result = new EvaluationResult(); result.setId("other"); fixture.removeEvalResult(result); Assert.assertEquals(1, fixture.getEvaluationResults().size()); } /** * Run the void removeMeasureResult(AbstractEntity) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveMeasureResult_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final AbstractEntity result = null; fixture.removeMeasureResult(result); Assert.assertEquals(1, fixture.getMeasurementResults().size()); } /** * Run the void removeMeasureResult(AbstractEntity) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveMeasureResult_2() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final AbstractEntity result = new MeasurementResult(); fixture.removeMeasureResult(result); Assert.assertEquals(0, fixture.getMeasurementResults().size()); } /** * Run the void removeMeasureResult(AbstractEntity) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testRemoveMeasureResult_3() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final AbstractEntity result = new AbstractResult(); result.setId("other"); fixture.removeMeasureResult(result); Assert.assertEquals(1, fixture.getMeasurementResults().size()); } /** * Run the void setDate(String) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testSetDate_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final String date = ""; fixture.setDate(date); Assert.assertEquals(date, fixture.getDate()); } /** * Run the void setSystem(String) method test. * * @throws Exception * @generatedBy CodePro at 5/30/15 3:49 PM */ @Test public void testSetSystem_1() throws Exception { final QualityModelResult fixture = new QualityModelResult("", ""); fixture.addMeasureResult(new MeasurementResult()); fixture.addEvalResult(new EvaluationResult()); final String system = ""; fixture.setSystem(system); Assert.assertEquals(system, fixture.getSystem()); } /** * Perform pre-test initialization. * * @throws Exception * if the initialization fails for some reason * @generatedBy CodePro at 5/30/15 3:49 PM */ @Before public void setUp() throws Exception { // TODO: add additional set up code here } /** * Perform post-test clean-up. * * @throws Exception * if the clean-up fails for some reason * @generatedBy CodePro at 5/30/15 3:49 PM */ @After public void tearDown() throws Exception { // TODO: add additional tear down code here } /** * Launch the test. * * @param args * the command line arguments * @generatedBy CodePro at 5/30/15 3:49 PM */ public static void main(final String[] args) { new org.junit.runner.JUnitCore().run(QualityModelResultTest.class); } }
29.476115
83
0.727892
92974147a9672861160b2c4d039799daa97c56f1
3,456
/* * Copyright 2020 StreamSets 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.streamsets.lib.security.http.aster; import com.google.common.base.Preconditions; import com.streamsets.datacollector.http.AsterConfig; import com.streamsets.datacollector.http.AsterContext; import org.eclipse.jetty.security.Authenticator; import org.eclipse.jetty.security.ServerAuthException; import org.eclipse.jetty.server.Authentication; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.util.function.Function; /** * {@link Function} that creates an Aster {@link Authenticator} using the given configuration. * <p/> * The authenticator is created with the function class' classloader in context. The returned authenticator * is wrapped with {@link ClassLoaderInContextAuthenticator} to ensure all invocations use the {@link ClassLoader} of * the Aster authenticator. * <p/> * The Aster authenticator stores the token credentials in a {@code aster-token.json} file within the specified * data directory. */ public class AsterContextCreator implements Function<AsterConfig, AsterContext> { /** * Creates an Aster {@link Authenticator} wrapped with a {@link ClassLoaderInContextAuthenticator}. */ @Override public AsterContext apply(AsterConfig asterConfig) { AsterService service; String asterUrl = asterConfig.getEngineConf().get(AsterServiceProvider.ASTER_URL, AsterServiceProvider.ASTER_URL_DEFAULT); if (!asterUrl.isEmpty()) { AsterServiceConfig serviceConfig = new AsterServiceConfig( AsterRestConfig.SubjectType.valueOf(asterConfig.getEngineType()), asterConfig.getEngineVersion(), asterConfig.getEngineId(), asterConfig.getEngineConf() ); File tokensFile = new File(asterConfig.getDataDir(), "aster-token.json"); service = new AsterServiceImpl(serviceConfig, tokensFile); } else { service = null; } ClassLoaderInContextAuthenticator authenticator = new ClassLoaderInContextAuthenticator(new AsterAuthenticator(service)); return new AsterContext() { @Override public boolean isEnabled() { return service != null; } @Override public AsterService getService() { Preconditions.checkState(service != null, "Aster service not available"); return service; } @Override public void handleRegistration(ServletRequest req, ServletResponse res) { Preconditions.checkState(service != null, "Aster service not available"); authenticator.handleRegistration(req, res); } @Override public Authenticator getAuthenticator() { Preconditions.checkState(service != null, "Aster service not available"); return authenticator; } }; } }
36.765957
126
0.734954
1fb1dee54d488fb890230131569e526bb6a9f393
1,451
package org.resec.algorithms; import edu.princeton.cs.algs4.In; public class Outcast { private final WordNet wordNet; // constructor takes a WordNet object public Outcast(WordNet wordnet) { if (wordnet == null) { throw new NullPointerException("Input wordnet is null"); } this.wordNet = wordnet; } public static void main(String[] args) { WordNet wordnet = new WordNet(args[0], args[1]); Outcast outcast = new Outcast(wordnet); for (int t = 2; t < args.length; t++) { In in = new In(args[t]); String[] nouns = in.readAllStrings(); System.out.println(args[t] + ": " + outcast.outcast(nouns)); } } // given an array of WordNet nouns, return an outcast public String outcast(String[] nouns) { if (nouns == null) { throw new NullPointerException("Input nouns is null"); } if (nouns.length == 0) { throw new IllegalArgumentException("Input nouns is empty"); } int maxD = Integer.MIN_VALUE; String outcast = null; for (String nounA : nouns) { int d = Integer.MIN_VALUE; for (String nounB : nouns) { d += wordNet.distance(nounA, nounB); } if (maxD < d) { maxD = d; outcast = nounA; } } return outcast; } }
27.903846
72
0.534804
b0f7f91afb0b8b0f9d8b0e4fbbf82f627b2c2e46
13,114
package org.recap.camel.submitcollection; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.*; import com.amazonaws.util.IOUtils; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Predicate; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.recap.PropertyKeyConstants; import org.recap.ScsbCommonConstants; import org.recap.ScsbConstants; import org.recap.camel.submitcollection.processor.SubmitCollectionProcessor; import org.recap.repository.jpa.InstitutionDetailsRepository; import org.recap.util.CommonUtil; import org.recap.util.PropertyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * Created by premkb on 19/3/17. */ @Component public class SubmitCollectionPollingS3RouteBuilder { private static final Logger logger = LoggerFactory.getLogger(SubmitCollectionPollingS3RouteBuilder.class); @Autowired ProducerTemplate producer; @Autowired CamelContext camelContext; @Autowired ApplicationContext applicationContext; @Autowired PropertyUtil propertyUtil; @Autowired InstitutionDetailsRepository institutionDetailsRepository; @Autowired CommonUtil commonUtil; @Value("${" + PropertyKeyConstants.S3_SUBMIT_COLLECTION_DIR + "}") private String submitCollectionS3BasePath; @Autowired AmazonS3 awsS3Client; @Value("${" + PropertyKeyConstants.SCSB_BUCKET_NAME + "}") private String scsbBucketName; @Value("${" + PropertyKeyConstants.SUBMIT_COLLECTION_LOCAL_DIR + "}") private String submitCollectionLocalWorkingDir; /** * Predicate to identify is the input file is gz */ Predicate gzipFile = exchange -> { if (exchange.getIn().getHeader(ScsbConstants.CAMEL_FILE_NAME_ONLY) != null) { String fileName = exchange.getIn().getHeader(ScsbConstants.CAMEL_FILE_NAME_ONLY).toString(); return StringUtils.equalsIgnoreCase("gz", FilenameUtils.getExtension(fileName)); } else { return false; } }; public SubmitCollectionPollingS3RouteBuilder(CamelContext camelContext, ApplicationContext applicationContext) { try { //This route is used to send message to queue which is used in controller to identify the completion of submit collection process camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(ScsbConstants.SUBMIT_COLLECTION_COMPLETION_QUEUE_FROM) .routeId(ScsbConstants.SUBMIT_COLLECTION_COMPLETED_ROUTE) .log("Completed Submit Collection Process") .process(exchange -> exchange.getIn().setBody("Submit collection process completed sucessfully in sequential order")) .to(ScsbConstants.SUBMIT_COLLECTION_COMPLETION_QUEUE_TO) .end(); } }); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(ScsbCommonConstants.DIRECT_ROUTE_FOR_EXCEPTION) .log("Calling direct route for exception") .bean(applicationContext.getBean(SubmitCollectionProcessor.class), ScsbConstants.SUBMIT_COLLECTION_CAUGHT_EXCEPTION_METHOD); } }); } catch (Exception e) { logger.info("Exception occurred while instantiating submit collection route definitions : {}", e.getMessage()); } } public void createRoutesForSubmitCollection() { List<String> protectedAndNotProtected = Arrays.asList(ScsbConstants.PROTECTED, ScsbConstants.NOT_PROTECTED); String nextInstitution = null; List<String> allInstitutionCodesExceptSupportInstitution = commonUtil.findAllInstitutionCodesExceptSupportInstitution(); for (int i = 0; i < allInstitutionCodesExceptSupportInstitution.size(); i++) { String currentInstitution = allInstitutionCodesExceptSupportInstitution.get(i); nextInstitution = (i < allInstitutionCodesExceptSupportInstitution.size() - 1) ? allInstitutionCodesExceptSupportInstitution.get(i + 1) : null; for (String cdgType : protectedAndNotProtected) { String nextRouteId = getNextRouteId(currentInstitution, nextInstitution, cdgType); if (ScsbConstants.PROTECTED.equalsIgnoreCase(cdgType)) addRoutesToCamelContext(currentInstitution, cdgType, currentInstitution + ScsbConstants.CGD_PROTECTED_ROUTE_ID, nextRouteId, true); else { addRoutesToCamelContext(currentInstitution, cdgType, currentInstitution + ScsbConstants.CGD_NOT_PROTECTED_ROUTE_ID, nextRouteId, false); } } } } private String getNextRouteId(String currentInstitution, String nextInstitution, String cdgType) { if (ScsbConstants.PROTECTED.equalsIgnoreCase(cdgType)) { return currentInstitution + ScsbConstants.CGD_NOT_PROTECTED_ROUTE_ID; } else if (StringUtils.isNotBlank(nextInstitution)) { return nextInstitution + ScsbConstants.CGD_PROTECTED_ROUTE_ID; } else { return ScsbConstants.SUBMIT_COLLECTION_COMPLETED_ROUTE; } } public void addRoutesToCamelContext(String currentInstitution, String cgdType, String currentInstitutionRouteId, String nextInstitutionRouteId, Boolean isCGDProtected) { try { ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); listObjectsRequest.setBucketName(scsbBucketName); listObjectsRequest.setPrefix(submitCollectionS3BasePath + currentInstitution + "/cgd_" + cgdType + "/" + "scsb"); ObjectListing objectListing = awsS3Client.listObjects(listObjectsRequest); for (S3ObjectSummary os : objectListing.getObjectSummaries()) { getObjectContentToDrive(os.getKey(), currentInstitution, cgdType); logger.info("File with the key --> {} Size --> {} Last Modified -->{} " , os.getKey() , os.getSize() , os.getLastModified()); } camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { onCompletion() .choice() .when(exchangeProperty(ScsbCommonConstants.CAMEL_BATCH_COMPLETE)) .process(exchange -> clearDirectory(currentInstitution, cgdType)) .log("OnCompletion executing for :" + currentInstitution + cgdType) .to("controlbus:route?routeId=" + currentInstitutionRouteId + "&action=stop&async=true") .delay(10) .process(exchange -> startNextRouteInNewThread(exchange, nextInstitutionRouteId)); onException(Exception.class) .log("Exception caught during submit collection process - " + currentInstitution + cgdType) .handled(true) .setHeader(ScsbCommonConstants.INSTITUTION, constant(currentInstitution)) .setHeader(ScsbCommonConstants.IS_CGD_PROTECTED, constant(isCGDProtected)) .setHeader(ScsbConstants.CGG_TYPE, constant(cgdType)) .to(ScsbCommonConstants.DIRECT_ROUTE_FOR_EXCEPTION); from("file://"+ submitCollectionLocalWorkingDir + currentInstitution + ScsbCommonConstants.PATH_SEPARATOR + "cgd_" + cgdType + "?sendEmptyMessageWhenIdle=true&delete=true") .routeId(currentInstitutionRouteId) .noAutoStartup() .choice() .when(gzipFile) .unmarshal() .gzipDeflater() .log(currentInstitution + "Submit Collection S3 Route Unzip Complete") .bean(applicationContext.getBean(SubmitCollectionProcessor.class, currentInstitution, isCGDProtected, cgdType), ScsbConstants.PROCESS_INPUT) .when(body().isNull())//This condition is satisfied when there are no files in the S3 directory(parameter-sendEmptyMessageWhenIdle=true) .bean(applicationContext.getBean(SubmitCollectionProcessor.class, currentInstitution, isCGDProtected, cgdType), ScsbConstants.SEND_EMAIL_FOR_EMPTY_DIRECTORY) .log(currentInstitution + "-" + cgdType + " Directory is empty") .otherwise() .log("submit collection for " + currentInstitution + "-" + cgdType + " started") .bean(applicationContext.getBean(SubmitCollectionProcessor.class, currentInstitution, isCGDProtected, cgdType), ScsbConstants.PROCESS_INPUT) .log(currentInstitution + " Submit Collection " + cgdType + " S3 Route Record Processing completed") .end(); } }); } catch (Exception e) { logger.error(ScsbCommonConstants.LOG_ERROR, e.getMessage()); } } private void getObjectContentToDrive(String fileName, String currentInstitution, String cgdType) { String finalFileName = null; try { S3Object s3Object = awsS3Client.getObject(scsbBucketName, fileName); S3ObjectInputStream inputStream = s3Object.getObjectContent(); finalFileName = fileName.substring(fileName.lastIndexOf('/') + 1); if (inputStream != null) { IOUtils.copy(inputStream, new FileOutputStream(new File(submitCollectionLocalWorkingDir + currentInstitution + ScsbCommonConstants.PATH_SEPARATOR + "cgd_" + cgdType + ScsbCommonConstants.PATH_SEPARATOR + finalFileName))); } } catch (Exception e) { logger.error(ScsbCommonConstants.LOG_ERROR, e.getMessage()); } } public void startNextRouteInNewThread(Exchange exchange, String nextInstitutionRouteId) { Thread startThread; startThread = new Thread(() -> { try { if (nextInstitutionRouteId.contains("Complete")) { producer.sendBody(ScsbConstants.SUBMIT_COLLECTION_COMPLETION_QUEUE_FROM, exchange); } else { camelContext.getRouteController().startRoute(nextInstitutionRouteId); } } catch (Exception e) { logger.info("Exception occured while starting next route : {}", e.getMessage()); exchange.setException(e); } }); startThread.start(); } public void removeRoutesForSubmitCollection() throws Exception { logger.info(" Total routes before removing : {}", camelContext.getRoutesSize()); List<String> protectedAndNotProtected = Arrays.asList(ScsbConstants.PROTECTED, ScsbConstants.NOT_PROTECTED); List<String> allInstitutionCodesExceptSupportInstitution = commonUtil.findAllInstitutionCodesExceptSupportInstitution(); for (String institution : allInstitutionCodesExceptSupportInstitution) { for (String cdgType : protectedAndNotProtected) { if (ScsbConstants.PROTECTED.equalsIgnoreCase(cdgType)) { camelContext.getRouteController().stopRoute(institution + ScsbConstants.CGD_PROTECTED_ROUTE_ID); camelContext.removeRoute(institution + ScsbConstants.CGD_PROTECTED_ROUTE_ID); } else { camelContext.getRouteController().stopRoute(institution + ScsbConstants.CGD_NOT_PROTECTED_ROUTE_ID); camelContext.removeRoute(institution + ScsbConstants.CGD_NOT_PROTECTED_ROUTE_ID); } } } logger.info(" Total routes after removing : {}", camelContext.getRoutesSize()); } public void clearDirectory(String institutionCode, String cgdType) { File destDirFile = new File(submitCollectionLocalWorkingDir + institutionCode + "/cgd_"+ cgdType); try { FileUtils.cleanDirectory(destDirFile); } catch (IOException e) { logger.error(ScsbCommonConstants.LOG_ERROR, e.getMessage()); } } }
51.427451
237
0.657847
5521fcf4984eede70621287fc9119845246df9c6
353
package br.com.carlosFreitas.recursividade035; public class TesteCalculadora { public static void main(String[] args) { // TODO Auto-generated method stub int calcNaoRecursivo = Calculadora.fatorialNaoRecursivo(5); int calc = Calculadora.fatorial(5); System.out.println(calcNaoRecursivo); System.out.println(calc); } }
23.533333
61
0.72238
f130175dc5d0504d26cb67074a14c8b566c84c3a
31,177
package edu.ucla.cs.jshrinklib; import edu.ucla.cs.jshrinklib.classcollapser.ClassCollapser; import edu.ucla.cs.jshrinklib.classcollapser.ClassCollapserAnalysis; import edu.ucla.cs.jshrinklib.classcollapser.ClassCollapserData; import edu.ucla.cs.jshrinklib.fieldwiper.FieldWiper; import edu.ucla.cs.jshrinklib.methodinliner.InlineData; import edu.ucla.cs.jshrinklib.methodinliner.MethodInliner; import edu.ucla.cs.jshrinklib.methodwiper.MethodWiper; import edu.ucla.cs.jshrinklib.reachability.*; import edu.ucla.cs.jshrinklib.util.ClassFileUtils; import edu.ucla.cs.jshrinklib.util.PathResolutionUtil; import edu.ucla.cs.jshrinklib.util.SootUtils; import org.apache.commons.io.FileUtils; import soot.*; import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class JShrink { private File projectDir; private EntryPointProcessor entryPointProcessor; private Optional<File> tamiflex; private Optional<File> jmtrace; private boolean useSpark; private boolean verbose; private boolean useCache; private boolean ignoreLibs; private Optional<IProjectAnalyser> projectAnalyser = Optional.empty(); private boolean projectAnalyserRun = false; private Set<SootClass> classesToModify = new HashSet<SootClass>(); private Set<SootClass> classesToRemove = new HashSet<SootClass>(); private ClassReferenceGraph classDependencyGraph = null; private long libSizeCompressed = -1; private long libSizeDecompressed = -1; private long appSizeCompressed = -1; private long appSizeDecompressed = -1; // a global boolean variable indicating whether we should allow public static boolean enable_type_dependency = false; public static boolean enable_member_visibility = false; public static boolean enable_super_class_recursion_check = false; public static boolean enable_annotation_updates = false; //Map<Class,Exception thrown by Soot> private Map<String,String> unmodifiableClasses = new HashMap<String, String>(); private boolean runTests; private Optional<Map<MethodData, Set<MethodData>>> callGraphs = Optional.empty(); /* Regardless of whether "reset()" is run, the project, if compiled, remains so. We do not want to recompile, thus we keep note of the compilation status of the project. */ private boolean alreadyCompiled = false; private static Optional<JShrink> instance = Optional.empty(); /* At present this only work on Maven Directories. I should expand this to be more general (some code exists to support this but TamiFlex is a big hurdle for now --- we need to run test cases). */ //TODO: Expand for projects that are not just Maven (see above). //TODO: Yet to implement the functionality to ignore certain classes for modification. /* TODO: We do not assume interaction between remove methods/method inlining/call-graph collapsing. E.g., it could be the case that a method is inlined, and we can therefore remove that method to save space. I would assume we need to rebuild the callgraph to do so. Perhaps we need to implement an "updateCallGraph" feature. At present we need to simply run "updateClassFiles()" after inlining/call-graph collapsing to observe these affects. Is there a way to update the call graph in a more efficient way? We don't need to reload the classes to SootClasses, for example. */ public static JShrink createInstance(File projectDir, EntryPointProcessor entryPointProcessor, Optional<File> tamiflex, Optional<File> jmtrace, boolean useSpark, boolean verbose, boolean executeTests, boolean useCache, boolean ignoreLibs) throws IOException{ /* Due to Soot using a singleton pattern, I use a singleton pattern here to ensure safety. E.g., only one project can be worked on at once. */ if(instance.isPresent()){ throw new IOException("Instance of JShrink already exists. Please use \"getInstance\"."); } instance = Optional.of(new JShrink(projectDir, entryPointProcessor, tamiflex, jmtrace, useSpark, verbose, executeTests, useCache, ignoreLibs)); return instance.get(); } public static boolean instanceExists(){ return instance.isPresent(); } public static JShrink getInstance() throws IOException{ if(instance.isPresent()){ return instance.get(); } throw new IOException("Instance of JShrink does not exist. Please used \"createInstance\"."); } public static JShrink resetInstance(File projectDir, EntryPointProcessor entryPointProcessor, Optional<File> tamiflex, Optional<File> jmtrace, boolean useSpark, boolean verbose, boolean executeTests, boolean useCache, boolean ignoreLibs) throws IOException{ if(instance.isPresent()){ instance.get().reset(); instance.get().projectDir = projectDir; instance.get().entryPointProcessor = entryPointProcessor; instance.get().tamiflex = tamiflex; instance.get().jmtrace = jmtrace; instance.get().useSpark = useSpark; instance.get().verbose = verbose; instance.get().useCache = useCache; instance.get().runTests = executeTests; instance.get().ignoreLibs = ignoreLibs; instance.get().alreadyCompiled = false; instance.get().libSizeCompressed = -1; instance.get().libSizeDecompressed = -1; instance.get().appSizeCompressed = -1; instance.get().appSizeDecompressed = -1; return instance.get(); } throw new IOException("Instance of JShrink does not exist. Please use \"createInstance\"."); } private JShrink(File projectDir, EntryPointProcessor entryPointProcessor, Optional<File> tamiflex, Optional<File> jmtrace, boolean useSpark, boolean verbose, boolean executeTests, boolean useCache, boolean ignoreLibs){ this.projectDir = projectDir; this.entryPointProcessor = entryPointProcessor; this.tamiflex = tamiflex; this.jmtrace = jmtrace; this.useSpark = useSpark; this.verbose = verbose; this.runTests = executeTests; this.useCache = useCache; this.ignoreLibs = ignoreLibs; classDependencyGraph = new ClassReferenceGraph(); } public Set<MethodData> getAllEntryPoints() { return this.getProjectAnalyserRun().getEntryPoints(); } private IProjectAnalyser getProjectAnalyser(){ //Will return setup, not guaranteed to have been run. Use "getProjectAnalyserRun" for this. if(this.projectAnalyser.isPresent()){ return this.projectAnalyser.get(); } //Just supporting MavenSingleProjectAnalysis for now this.projectAnalyser = Optional.of( new MavenSingleProjectAnalyzer(this.projectDir.getAbsolutePath(), this.entryPointProcessor, this.tamiflex, this.jmtrace, this.useSpark, this.verbose, this.runTests, this.useCache, this.ignoreLibs)); ((MavenSingleProjectAnalyzer) this.projectAnalyser.get()).setCompileProject(!alreadyCompiled); this.projectAnalyser.get().setup(); this.alreadyCompiled = true; ((MavenSingleProjectAnalyzer) this.projectAnalyser.get()).setCompileProject(!alreadyCompiled); updateSizes(); return this.projectAnalyser.get(); } private void loadClasses(){ G.reset(); SootUtils.setup_trimming(this.getProjectAnalyser().getLibClasspaths(), this.getProjectAnalyser().getAppClasspaths(), this.getProjectAnalyser().getTestClasspaths()); Scene.v().loadNecessaryClasses(); } private IProjectAnalyser getProjectAnalyserRun(){ if(!this.projectAnalyserRun){ this.getProjectAnalyser().run(); loadClasses(); this.projectAnalyserRun = true; } return this.getProjectAnalyser(); } public Set<MethodData> getAllAppMethods(){ return this.getProjectAnalyserRun().getAppMethods(); } public Set<MethodData> getAllLibMethods(){ return this.getProjectAnalyserRun().getLibMethodsCompileOnly(); } public Set<FieldData> getAllAppFields() { return this.getProjectAnalyserRun().getAppFields(); } public Set<FieldData> getAllLibFields() { return this.getProjectAnalyserRun().getLibFieldsCompileOnly(); } public Set<MethodData> getUsedAppMethods(){ return this.getProjectAnalyserRun().getUsedAppMethods().keySet(); } public Set<MethodData> getUsedLibMethods(){ return this.getProjectAnalyserRun().getUsedLibMethodsCompileOnly().keySet(); } public Set<FieldData> getUsedAppFields() { return this.getProjectAnalyserRun().getUsedAppFields(); } public Set<FieldData> getUsedLibFields() { return this.getProjectAnalyserRun().getUsedLibFieldsCompileOnly(); } public Set<MethodData> getAllTestMethods(){ return this.getProjectAnalyserRun().getTestMethods(); } public Set<MethodData> getUsedTestMethods(){ return this.getProjectAnalyserRun().getUsedTestMethods().keySet(); } public Set<String> getAllAppClasses(){ return this.getProjectAnalyserRun().getAppClasses(); } public Set<String> getAllLibClasses(){ return this.getProjectAnalyserRun().getLibClassesCompileOnly(); } public Set<String> getUsedAppClasses(){ return this.getProjectAnalyserRun().getUsedAppClasses(); } public Set<String> getUsedLibClasses(){ return this.getProjectAnalyserRun().getUsedLibClassesCompileOnly(); } public Set<String> getTestClasses(){ return this.getProjectAnalyserRun().getTestClasses(); } public Set<String> getUsedTestClasses(){ return this.getProjectAnalyserRun().getUsedTestClasses(); } public Map<String, String> getUnmodifiableClasses() { return this.unmodifiableClasses; } public ClassCollapserData collapseClasses(boolean collapseAppClasses, boolean collapseLibClasses, boolean removeClasses){ Set<String> allClasses = new HashSet<String>(); Set<String> usedClasses = new HashSet<String>(); Set<MethodData> usedMethods = new HashSet<MethodData>(); if(collapseAppClasses) { allClasses.addAll(this.getAllAppClasses()); usedClasses.addAll(this.getUsedAppClasses()); usedMethods.addAll(this.getUsedAppMethods()); } if(collapseLibClasses) { allClasses.addAll(this.getAllLibClasses()); usedClasses.addAll(this.getUsedLibClasses()); usedMethods.addAll(this.getUsedLibMethods()); } ClassCollapserAnalysis classCollapserAnalysis = new ClassCollapserAnalysis(allClasses, usedClasses, usedMethods, this.getSimplifiedCallGraph(), this.getAllEntryPoints(), unmodifiableClasses.keySet()); classCollapserAnalysis.run(); ClassCollapser classCollapser = new ClassCollapser(); classCollapser.run(classCollapserAnalysis, this.getTestClasses()); ClassCollapserData classCollapserData = classCollapser.getClassCollapserData(); for(String classToRewrite : classCollapserData.getClassesToRewrite()){ SootClass sootClass = Scene.v().loadClassAndSupport(classToRewrite); this.classesToModify.add(sootClass); } for(String classToRemove : classCollapserData.getClassesToRemove()){ SootClass sootClass = Scene.v().loadClassAndSupport(classToRemove); this.classesToModify.remove(sootClass); this.classesToRemove.add(sootClass); } if(removeClasses) { // The class collapsing procedure only removed unused subclasses // we can further remove all unused classes Set<String> unusedClasses = new HashSet<String>(allClasses); unusedClasses.removeAll(usedClasses); for(String classToRemove : unusedClasses) { // as mentioned in the Jax paper, Jax removes a class if it is unused and if it does not have a derived class if(!classCollapserAnalysis.childrenMap.containsKey(classToRemove) || (classCollapserAnalysis.childrenMap.get(classToRemove).isEmpty())) { SootClass sootClass = Scene.v().loadClassAndSupport(classToRemove); this.classesToModify.remove(sootClass); this.classesToRemove.add(sootClass); } } } return classCollapserData; } public Map<MethodData, Set<MethodData>> getSimplifiedCallGraph(){ if(callGraphs.isPresent()) { return callGraphs.get(); } callGraphs = Optional.of(new HashMap<MethodData, Set<MethodData>>()); callGraphs.get().putAll(this.getProjectAnalyserRun().getUsedAppMethods()); callGraphs.get().putAll(this.getProjectAnalyserRun().getUsedLibMethodsCompileOnly()); callGraphs.get().putAll(this.getProjectAnalyserRun().getUsedTestMethods()); return callGraphs.get(); } public InlineData inlineMethods(boolean inlineAppClassMethods, boolean inlineLibClassMethods){ Set<String> classesInScope = new HashSet<String>(); if(inlineAppClassMethods) { classesInScope.addAll(this.getAllAppClasses()); } if(inlineLibClassMethods) { classesInScope.addAll(this.getAllLibClasses()); } classesInScope.addAll(this.getUsedTestClasses()); Map<MethodData, Set<MethodData>> simplifiedCallGraph = new HashMap<MethodData, Set<MethodData>>(); Map<MethodData, Set<MethodData>> originalCallGraph = this.getSimplifiedCallGraph(); for(MethodData md : originalCallGraph.keySet()) { if(classesInScope.contains(md.getClassName())) { simplifiedCallGraph.put(md, originalCallGraph.get(md)); } } Map<SootMethod, Set<SootMethod>> callgraph = new HashMap<SootMethod, Set<SootMethod>>(); for(Map.Entry<SootMethod, Set<SootMethod>> entry : SootUtils.convertMethodDataCallGraphToSootMethodCallGraph(simplifiedCallGraph).entrySet()){ callgraph.put(entry.getKey(), entry.getValue()); } Set<File> classPaths = new HashSet<File>(); classPaths.addAll(this.getProjectAnalyser().getAppClasspaths()); classPaths.addAll(this.getProjectAnalyser().getLibClasspaths()); InlineData output = MethodInliner.inlineMethods(callgraph, classPaths, unmodifiableClasses.keySet()); this.classesToModify.addAll(output.getClassesModified()); return output; } public Set<MethodData> removeMethods(Set<MethodData> toRemove, boolean removeUnusedClasses){ Set<MethodData> removedMethods = new HashSet<MethodData>(); if(removeUnusedClasses) { Set<SootClass> sootClassesAffected = new HashSet<SootClass>(); for (MethodData methodData : toRemove) { sootClassesAffected.add(Scene.v().loadClassAndSupport(methodData.getClassName())); } for (SootClass sootClass : sootClassesAffected) { boolean removeClass = true; for (SootField sootField : sootClass.getFields()) { if (sootField.isStatic() && !sootField.isPrivate()) { removeClass = false; break; } } if (!removeClass) { continue; } for (SootMethod sootMethod : sootClass.getMethods()) { MethodData methodData = SootUtils.sootMethodToMethodData(sootMethod); if (!toRemove.contains(methodData)) { removeClass = false; break; } } if (removeClass) { this.classesToRemove.add(sootClass); for (SootMethod sootMethod : sootClass.getMethods()) { MethodData methodData = SootUtils.sootMethodToMethodData(sootMethod); removedMethods.add(methodData); } } } } //Remove the classes and not the classes affected. for(MethodData methodData : toRemove){ if(!removedMethods.contains(methodData)) { if(unmodifiableClasses.containsKey(methodData.getClassName())) { // this class cannot be modified by Soot continue; } SootClass sootClass = Scene.v().loadClassAndSupport(methodData.getClassName()); if (!sootClass.isEnum() && sootClass.declaresMethod(methodData.getSubSignature())) { SootMethod sootMethod = sootClass.getMethod(methodData.getSubSignature()); if (MethodWiper.removeMethod(sootMethod)) { removedMethods.add(methodData); this.classesToModify.add(sootClass); } } } } return removedMethods; } public Set<MethodData> wipeMethods(Set<MethodData> toRemove){ Set<MethodData> removedMethods = new HashSet<MethodData>(); for(MethodData methodData : toRemove){ SootClass sootClass = Scene.v().loadClassAndSupport(methodData.getClassName()); if(!sootClass.isEnum() && sootClass.declaresMethod(methodData.getSubSignature())) { SootMethod sootMethod = sootClass.getMethod(methodData.getSubSignature()); if(MethodWiper.wipeMethodBody(sootMethod)) { removedMethods.add(methodData); this.classesToModify.add(sootClass); } } } return removedMethods; } public Set<MethodData> wipeMethodAndAddException(Set<MethodData> toRemove, Optional<String> exceptionMethod){ Set<MethodData> removedMethods = new HashSet<MethodData>(); for(MethodData methodData : toRemove){ SootClass sootClass = Scene.v().loadClassAndSupport(methodData.getClassName()); if(!sootClass.isEnum() && sootClass.declaresMethod(methodData.getSubSignature())) { SootMethod sootMethod = sootClass.getMethod(methodData.getSubSignature()); boolean success = false; if (exceptionMethod.isPresent()) { success = MethodWiper.wipeMethodBodyAndInsertRuntimeException(sootMethod, exceptionMethod.get()); } else { success = MethodWiper.wipeMethodBodyAndInsertRuntimeException(sootMethod); } if (success) { removedMethods.add(methodData); this.classesToModify.add(sootClass); } } } return removedMethods; } public void removeClasses(Set<String> classes){ loadClasses(); for(String className : classes){ SootClass sootClass = Scene.v().loadClassAndSupport(className); this.classesToRemove.add(sootClass); this.classesToModify.remove(sootClass); } } public Set<File> getClassPaths(){ Set<File> classPaths = new HashSet<File>(); classPaths.addAll(this.getProjectAnalyser().getAppClasspaths()); classPaths.addAll(this.getProjectAnalyser().getLibClasspaths()); classPaths.addAll(this.getProjectAnalyser().getTestClasspaths()); return classPaths; } public void updateClassFilesAtPath(Set<File> classPaths){ try { Set<File> decompressedJars = new HashSet<File>(ClassFileUtils.extractJars(new ArrayList<File>(classPaths))); modifyClasses(this.classesToModify, classPaths); this.removeClasses(this.classesToRemove, classPaths); /* File.delete() does not delete a file immediately. I was therefore running into a problem where the jars were being recompressed with the files that were supposed to be deleted. I found adding a small delay solved this problem. However, it would be good to find a better solution to this problem. TODO: Fix the above. */ TimeUnit.SECONDS.sleep(1); ClassFileUtils.compressJars(decompressedJars); }catch(IOException | InterruptedException e){ e.printStackTrace(); System.exit(1); } } public void updateClassFiles(){ try { Set<File> classPaths = this.getClassPaths(); Set<File> decompressedJars = new HashSet<File>(ClassFileUtils.extractJars(new ArrayList<File>(classPaths))); modifyClasses(this.classesToModify, classPaths); this.classesToModify.clear(); this.removeClasses(this.classesToRemove, classPaths); /* File.delete() does not delete a file immediately. I was therefore running into a problem where the jars were being recompressed with the files that were supposed to be deleted. I found adding a small delay solved this problem. However, it would be good to find a better solution to this problem. TODO: Fix the above. */ TimeUnit.SECONDS.sleep(1); this.classesToRemove.clear(); //modifyClasses(this.classesToModify, classPaths); ClassFileUtils.compressJars(decompressedJars); //this.classesToModify.clear(); updateSizes(); this.reset(); }catch(IOException | InterruptedException e){ e.printStackTrace(); System.exit(1); } } private void reset(){ this.projectAnalyser = Optional.empty(); this.projectAnalyserRun = false; this.classesToModify.clear(); this.classesToRemove.clear(); this.callGraphs = Optional.empty(); G.reset(); } private long getSize(boolean withJarsDecompressed, List<File> classPaths){ Set<File> decompressedJars = new HashSet<File>(); long toReturn = 0; try { if(withJarsDecompressed){ decompressedJars = new HashSet<File>(ClassFileUtils.extractJars(new ArrayList<File>(classPaths))); } for(File file : classPaths){ toReturn+=ClassFileUtils.getSize(file); } ClassFileUtils.compressJars(decompressedJars); }catch(IOException e){ e.printStackTrace(); System.exit(1); } return toReturn; } private void updateSizes(){ this.libSizeCompressed = getSize(false, this.getProjectAnalyser().getLibClasspaths()); this.libSizeDecompressed = getSize(true, this.getProjectAnalyser().getLibClasspaths()); this.appSizeCompressed = getSize(false, this.getProjectAnalyser().getAppClasspaths()); this.appSizeDecompressed = getSize(true, this.getProjectAnalyser().getAppClasspaths()); } private void checkSizes(){ // if(this.libSizeCompressed < 0 || this.libSizeDecompressed < 0 // || this.appSizeCompressed < 0 || this.appSizeDecompressed < 0){ // updateSizes(); // } updateSizes(); } public long getLibSize(boolean withJarsDecompressed){ checkSizes(); if(withJarsDecompressed){ return this.libSizeDecompressed; } else { return this.libSizeCompressed; } } public long getAppSize(boolean withJarsDecompressed){ checkSizes(); if(withJarsDecompressed){ return this.appSizeDecompressed; } else { return this.appSizeCompressed; } } public TestOutput getTestOutput(){ assert(this.runTests); return this.getProjectAnalyser().getTestOutput(); } /* This method does a Soot pass. Soot can make classes smaller even without any transformations. Thus, this allows us to do a pass at the beginning of the run to optimise all the code with soot before doing so with transformations (to obtain a good ground truth). This must be run before any transformations as it may cause problems later. */ public void makeSootPass(){ Set<File> classPaths = getClassPaths(); Set<SootClass> classesToRewrite = new HashSet<SootClass>(); for(String className : this.getProjectAnalyserRun().getAppClasses()){ SootClass sootClass = Scene.v().loadClassAndSupport(className); if(!SootUtils.modifiableSootClass(sootClass)){ Optional<String> exceptionMessage = SootUtils.getUnmodifiableClassException(sootClass); assert(exceptionMessage.isPresent()); unmodifiableClasses.put(className, exceptionMessage.get()); continue; } classesToRewrite.add(sootClass); } for(String className : this.getProjectAnalyserRun().getLibClassesCompileOnly()){ SootClass sootClass = Scene.v().loadClassAndSupport(className); if(!SootUtils.modifiableSootClass(sootClass)){ Optional<String> exceptionMessage = SootUtils.getUnmodifiableClassException(sootClass); assert(exceptionMessage.isPresent()); unmodifiableClasses.put(className, exceptionMessage.get()); continue; } classesToRewrite.add(sootClass); } /*for(String className: this.getProjectAnalyserRun().getLibClasses()){ SootClass sootClass = Scene.v().loadClassAndSupport(className); if(!SootUtils.modifiableSootClass(sootClass)){ Optional<String> exceptionMessage = SootUtils.getUnmodifiableClassException(sootClass); assert(exceptionMessage.isPresent()); unmodifiableClasses.put(className, exceptionMessage.get()); continue; } this.classDependencyGraph.addClass(sootClass); }*/ // We need to update class name references in test classes in class collapsing // So we need to make sure they are modifiable. // I saw a case in the disunity project where a test class has lambda expressions which // crashes the write-out process for(String className : this.getProjectAnalyserRun().getTestClasses()) { SootClass sootClass = Scene.v().loadClassAndSupport(className); if(!SootUtils.modifiableSootClass(sootClass)){ Optional<String> exceptionMessage = SootUtils.getUnmodifiableClassException(sootClass); assert(exceptionMessage.isPresent()); unmodifiableClasses.put(className, exceptionMessage.get()); } // no need to rewrite since we do not measure the size of test code // classesToRewrite.add(sootClass); } try { Set<File> decompressedJars = new HashSet<File>(ClassFileUtils.extractJars(new ArrayList<File>(classPaths))); modifyClasses(classesToRewrite, classPaths); ClassFileUtils.compressJars(decompressedJars); }catch(IOException e){ e.printStackTrace(); System.exit(1); } updateSizes(); long appSizeBefore = this.getAppSize(true); long libSizeBefore = this.getLibSize(true); //Run setup again to return the tests (They may have been corrupted by the Soot class). this.getProjectAnalyser().setup(); long appSizeAfter = this.getAppSize(true); long libSizeAfter = this.getLibSize(true); if(appSizeAfter != appSizeBefore){ System.out.println("WARNING: App Size Differs before and after running 'setup'"); } if(libSizeAfter != libSizeBefore){ System.out.println("WARNING: Lib Size Differs before and after running 'setup'"); } } /* I basically just use these (the following two methods) for debugging purposes. They keep track of classes that will be modified and deleted upon execution of "updateClassFiles()". */ public Set<String> classesToModified(){ Set<String> toReturn = new HashSet<String>(); for(SootClass sootClass : this.classesToModify){ toReturn.add(sootClass.getName()); } return Collections.unmodifiableSet(toReturn); } public Set<String> classesToRemove(){ Set<String> toReturn = new HashSet<String>(); for(SootClass sootClass : this.classesToRemove){ toReturn.add(sootClass.getName()); } return Collections.unmodifiableSet(toReturn); } private void modifyClasses(Set<SootClass> classesToRewrite, Set<File> classPaths){ for (SootClass sootClass : classesToRewrite) { try { if(unmodifiableClasses.containsKey(sootClass.getName())) { if(verbose) { // we will not update the class since it will cause exceptions when writing out to bytecode based on // the first soot pass. But this may cause a problem when loading or running the unmodified class. System.out.println("Attempting to update an unmodifiable class " + sootClass.getName()); } } else { ClassFileUtils.writeClass(sootClass, classPaths); } } catch (IOException e) { System.err.println("An exception was thrown when attempting to rewrite a class:"); e.printStackTrace(); System.exit(1); } } } public Set<String> filterUnmodifiableClass() { HashSet<SootClass> unmodifiableClasses = new HashSet<SootClass>(); HashSet<String> classNameOnly = new HashSet<String>(); for(SootClass sootClass : this.classesToModify) { if(!SootUtils.modifiableSootClass(sootClass)) { unmodifiableClasses.add(sootClass); classNameOnly.add(sootClass.getName()); } } this.classesToModify.removeAll(unmodifiableClasses); return classNameOnly; } private void removeClasses(Set<SootClass> classesToRemove, Set<File> classPaths){ if(classesToRemove.size() == 0) return; Set<String> classesToBeRemoved = new HashSet<String>(); if(JShrink.enable_type_dependency) { Instant start = Instant.now(); PathResolutionUtil.buildMap(classPaths); classesToBeRemoved = classesToRemove.stream().map(x->x.getName()).collect(Collectors.toSet()); for(String className : this.getProjectAnalyser().getAppClasses()){ SootClass sootClass = Scene.v().getSootClass(className); this.classDependencyGraph.addClass(sootClass.getName(), PathResolutionUtil.getClassPath(sootClass.getName())); } for(String className : this.getProjectAnalyser().getLibClassesCompileOnly()){ SootClass sootClass = Scene.v().getSootClass(className); this.classDependencyGraph.addClass(sootClass.getName(), PathResolutionUtil.getClassPath(sootClass.getName())); } for(String className : this.getProjectAnalyser().getTestClasses()){ SootClass sootClass = Scene.v().getSootClass(className); this.classDependencyGraph.addClass(sootClass.getName(), PathResolutionUtil.getClassPath(sootClass.getName())); } if(this.verbose) System.out.println("Resolved dependencies in "+Duration.between(Instant.now(),start).getSeconds()); } for(SootClass sootClass : classesToRemove){ Set<String> referencedBy = this.classDependencyGraph.getReferencedBy(sootClass.getName()); //not including classes marked for deletion referencedBy.removeAll(classesToBeRemoved); try{ if(referencedBy.size()>0) { if(unmodifiableClasses.containsKey(sootClass.getName()) || sootClass.isAbstract()) { // do not remove things in an unmodifiable class since the class cannot be updated anyway continue; } Set<SootField> fieldsToRemove = new HashSet<SootField>(sootClass.getFields()); for(SootField toRemove : fieldsToRemove){ toRemove.setDeclared(true); toRemove.setDeclaringClass(sootClass); sootClass.removeField(toRemove); } Set<SootMethod> methodsToRemove = new HashSet<SootMethod>(sootClass.getMethods()); for(SootMethod toRemove : methodsToRemove){ sootClass.removeMethod(toRemove); } methodsToRemove.clear(); fieldsToRemove.clear(); ClassFileUtils.writeClass(sootClass, classPaths); }else{ ClassFileUtils.removeClass(sootClass, classPaths); } } catch (IOException e){ System.err.println("An exception was thrown when attempting to delete a class:"); e.printStackTrace(); System.exit(1); } } } public Set<FieldData> removeFields(Set<FieldData> toRemove) { Set<FieldData> removedFields = new HashSet<FieldData>(); // cluster fields based on their owner classes, so we only need to load each class once in Soot Map<String, Set<FieldData>> toRemoveByClassName = new HashMap<String, Set<FieldData>>(); for(FieldData field : toRemove) { String className = field.getClassName(); Set<FieldData> set; if(toRemoveByClassName.containsKey(className)) { set = toRemoveByClassName.get(className); } else { set = new HashSet<FieldData>(); } set.add(field); toRemoveByClassName.put(className, set); } // modify each Soot class for(String className : toRemoveByClassName.keySet()) { if(unmodifiableClasses.containsKey(className)) { // do not remove a field in an unmodifiable class since the class cannot be updated anyway continue; } SootClass sootClass = Scene.v().getSootClass(className); Set<FieldData> unusedFields = toRemoveByClassName.get(className); for(FieldData unusedField : unusedFields) { SootField sootField = null; for(SootField field : sootClass.getFields()) { // comment out the check on serialVersionUID since Tamiflex can detect it // if(field.getName().equals("serialVersionUID")) { // // keep this field since JVM needs this field for serialization and validating serialized objects // continue; // } if(field.getName().equals(unusedField.getName()) && field.getType().toString() .equals(unusedField.getType())) { sootField = field; break; } } if(sootField != null && FieldWiper.removeField(sootField, verbose)) { removedFields.add(unusedField); this.classesToModify.add(sootClass); } } } return removedFields; } public String getLog(){ return ((MavenSingleProjectAnalyzer)getProjectAnalyser()).getLog(); } }
36.678824
123
0.741444
f7663a9b8e8e961562b33bf4f7190df536ce491d
654
package com.jaeger.statusbarutil; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.jaeger.library.StatusBarUtil; import com.jaeger.statusbardemo.R; /** * Created by Jaeger on 16/2/14. * * Email: chjie.jaeger@gmail.com * GitHub: https://github.com/laobie */ public class BaseActivity extends AppCompatActivity { @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); setStatusBar(); } protected void setStatusBar() { StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary)); } }
24.222222
84
0.729358
915bd4b8950bd485fb3f4c4aeee1f8cb65d0693f
311
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.neptuo.os.client.data.databus; import java.util.List; /** * * @author Mara */ public interface DataListener<T> { public void changed(DataEventType type, Object source, List<T> objects); }
17.277778
76
0.700965
40cb8481c9864ddb7ffeb58ecb9d0fbbc38ba5da
827
package com.ceiba.repartidor.adaptador.dao; import com.ceiba.infraestructura.jdbc.MapperResult; import com.ceiba.repartidor.modelo.dto.DtoRepartidor; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; public class MapeoRepartidor implements RowMapper<DtoRepartidor>, MapperResult { @Override public DtoRepartidor mapRow(ResultSet resultSet, int rowNum) throws SQLException { Long id = resultSet.getLong("id"); String identificacion = resultSet.getString("identificacion"); String nombres = resultSet.getString("nombres"); String apellidos = resultSet.getString("apellidos"); String telefono = resultSet.getString("telefono"); return new DtoRepartidor(id, identificacion, nombres, apellidos, telefono); } }
33.08
86
0.752116
73f773088a772736873eeaf85d016598ebae464d
3,674
package com.osiris.component.bootstrap.alert.render; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import org.primefaces.renderkit.CoreRenderer; import com.osiris.component.bootstrap.alert.UIAlert; import com.osiris.component.util.HTML; import com.osiris.component.util.HtmlConstants; /** * Classe responsavel por renderizar o alert do bootstrap. * * @author Cristian Urbainski<cristianurbainskips@gmail.com> * @since 23/07/2013 * @version 1.0 * */ @FacesRenderer(componentFamily = UIAlert.COMPONENT_FAMILY, rendererType = AlertRender.RENDERER_TYPE) public class AlertRender extends CoreRenderer { /** * Tipo do renderizador do componente. */ public static final String RENDERER_TYPE = "com.osiris.component.bootstrap.AlertRenderer"; @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { UIAlert alert = (UIAlert) component; encodeMarkup(context, alert); } /** * Método responsável por fazer a construção do html para o componente. * * @param context * do jsf * @param alert * componente a ser transcrito para html * @throws IOException * excecao que pode ocorrer */ protected void encodeMarkup(FacesContext context, UIAlert alert) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = alert.getClientId(context); writer.startElement(HTML.DIV_ELEM, null); writer.writeAttribute(HtmlConstants.ID_ATTRIBUTE, clientId, null); writer.writeAttribute(HtmlConstants.CLASS_ATTR, "alert alert-" + alert.getSeverity(), null); encodeCloseButton(context, alert, writer); encodeTitle(context, alert, writer); encodeMessage(context, alert, writer); writer.endElement(HTML.DIV_ELEM); } /** * Método responsável por escrever o botão de fechar da mensagem. * * @param context do jsf * @param alert componente a ser usado * @param writer de texto * @throws IOException */ protected void encodeCloseButton(FacesContext context, UIAlert alert, ResponseWriter writer) throws IOException { if (alert.isCloseable()) { writer.startElement(HTML.BUTTON_ELEM, null); writer.writeAttribute(HtmlConstants.TYPE_ATTR, "button", null); writer.writeAttribute(HtmlConstants.CLASS_ATTR, "close", null); writer.writeAttribute("data-dismiss", "alert", null); writer.writeText("\u00D7", null); writer.endElement(HTML.BUTTON_ELEM); } } /** * Método responsável por escrever o titulo da caixa de mensagem. * * @param context do jsf * @param alert componente a ser usado * @param writer de texto * @throws IOException */ protected void encodeTitle(FacesContext context, UIAlert alert, ResponseWriter writer) throws IOException { if (alert.getTitle() != null && !alert.getTitle().isEmpty()) { writer.startElement(HTML.H4_ELEM, null); writer.writeText(alert.getTitle(), null); writer.endElement(HTML.H4_ELEM); } } /** * Método responsável por escrever a mensagem na caixa da mensagem. * * @param context do jsf * @param alert componente a ser usado * @param writer de texto * @throws IOException */ protected void encodeMessage(FacesContext context, UIAlert alert, ResponseWriter writer) throws IOException { writer.writeText(alert.getMessage(), null); } }
33.099099
117
0.6957
312ae4700a7d61ee4953dc26c6f5e4b91616aa6a
592
package Game; import java.util.*; public class GameApp { public static void main(String[] args) { // TODO Auto-generated method stub Hand player1 = new Hand(3); Scanner s = new Scanner(System.in); while (!player1.gameOver()) { System.out.println("Here is your hand: " + player1.getCards()); System.out.println("Input a card index to replace: (0, 1, 2)"); int input = s.nextInt(); if (player1.replace(input)) { System.out.println("A random card has been replaced!"); } } System.out.println("All cards match, you win!"); } }
22.769231
67
0.619932
923b2a503293bd5ca58a3a3a13718f297934eed3
3,920
/* * Copyright (c) 2020 Dzikoysk * * 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.panda_lang.utilities.commons; import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.function.BiPredicate; import java.util.function.Function; public final class ObjectUtils { private ObjectUtils() { } /** * Try to cast or get null * * @param object the object to cast * @param clazz the type to cast * @param <T> the result type * @return casted object or null if object is not a clazz type */ public static @Nullable <T> T cast(Class<T> clazz, @Nullable Object object) { if (!clazz.isInstance(object)) { return null; } return clazz.cast(object); } @SuppressWarnings("unchecked") public static @Nullable <T> T cast(Object object) { return (T) object; } /** * Check if object is not null * * @param object object to check * @return true if object is not null */ public static boolean isNotNull(@Nullable Object object) { return object != null; } /** * Check if all values are null * * @param objects array to check * @return true if all values are null and false for non null element/empty array */ public static boolean areNull(Object... objects) { for (Object object : objects) { if (object != null) { return false; } } return objects.length > 0; } /** * Check if the value is one of the expected * * @param value value to check * @param expected expected values * @return true if expected values contains the specified value */ public static boolean equalsOneOf(Object value, Object... expected) { for (Object expectedValue : expected) { if (Objects.equals(value, expectedValue)) { return true; } } return false; } /** * Compare only one value that belongs to class and determines equality * * @param object the current object (~ this) * @param value the value of current object * @param to the object to compare with * @param getter the getter to obtain value from compared object * @param <T> type of current object * @param <C> type of compared values * @return true if compared objects are equal */ public static <T, C> boolean equals(T object, C value, Object to, Function<T, C> getter) { return equals(object, to, ((a, b) -> Objects.equals(value, getter.apply(b)))); } /** * Compare objects without boilerplate initial statements like (object == this) and (getClass() != to.getClass()) * * @param object the current object (this) * @param to the object to compare with * @param equals the predicate which determines equality * @param <T> type of objects to compare * @return true if objects are the same type and fulfils the predicate */ @SuppressWarnings("unchecked") public static <T> boolean equals(T object, Object to, BiPredicate<T, T> equals) { if (object == to) { return true; } if (to == null || object.getClass() != to.getClass()) { return false; } return equals.test(object, (T) to); } }
29.923664
117
0.620663
edbb22384658cf2da171a05977bb8be5719f86fb
462
package io.ebean.config; /** * Used to provide some automatic configuration early in the creation of a Database. */ public interface AutoConfigure { /** * Perform configuration for the DatabaseConfig prior to properties load. */ void preConfigure(DatabaseConfig config); /** * Provide some configuration the DatabaseConfig prior to server creation but after properties have been applied. */ void postConfigure(DatabaseConfig config); }
24.315789
115
0.746753
03ab29c2c544369e2045a01f026c6104c8d2b584
602
package com.google.kpierudzki.driverassistant.obd.service.commandmodels.pressure; import com.google.kpierudzki.driverassistant.obd.datamodel.ObdParamType; import com.google.kpierudzki.driverassistant.obd.service.commandmodels.ObdCommandModel; /** * Created by Kamil on 15.09.2017. */ public class BarometricPressureCommand extends ObdCommandModel { public BarometricPressureCommand() { super(new com.github.pires.obd.commands.pressure.BarometricPressureCommand(), true, ObdParamType.BAROMETRIC_PRESSURE); } @Override public int getPidNumber() { return 51; } }
30.1
126
0.772425
7c43a910b2f4f444413fd6d127658df8c55fd3db
361
package com.luo.leetcode.单调栈; /** * 拼接最大数 * https://leetcode-cn.com/problems/create-maximum-number/ * * @author luoxiangnan * @date 2020-11-15 */ public class MaxNumber { /** * TODO 待补充 */ public int[] maxNumber(int[] nums1, int[] nums2, int k) { int[] nums = new int[nums1.length + nums2.length]; return null; } }
18.05
61
0.590028
adf07b4fad7ca73e939d2951f0d52e0a3eb7eda0
452
package com.OE.Beans; public class Subject { Integer subject_id; String subject_name; public Subject() { // TODO Auto-generated constructor stub } public Integer getSubject_id() { return subject_id; } public void setSubject_id(Integer subject_id) { this.subject_id = subject_id; } public String getSubject_name() { return subject_name; } public void setSubject_name(String subject_name) { this.subject_name = subject_name; } }
19.652174
51
0.745575
6179caa98e300d414de60ae949a0acc1a206563b
158
/** * Created by Alex Backer on 12/2/2016. */ public class Starter { public static void main(String args[]) { Game g = new Game(); } }
14.363636
42
0.556962
eae52d61dfc120172ee820ea02cfff0eadd62b5d
2,504
/* * Copyright 2017 Abed Tony BenBrahim <tony.benrahim@10xdev.com> * and Gwt-JElement project contributors. * * 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.tenxdev.jsinterop.generator.parsing.visitors.secondpass; import com.tenxdev.jsinterop.generator.model.AbstractDefinition; import com.tenxdev.jsinterop.generator.model.Constructor; import com.tenxdev.jsinterop.generator.parsing.ParsingContext; import org.antlr4.webidl.WebIDLParser; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class DefinitionsVisitor extends ContextWebIDLBaseVisitor<List<AbstractDefinition>> { public DefinitionsVisitor(ParsingContext parsingContext) { super(parsingContext); } @Override public List<AbstractDefinition> visitDefinitions(WebIDLParser.DefinitionsContext ctx) { List<AbstractDefinition> definitionList = new ArrayList<>(); WebIDLParser.DefinitionsContext definitions = ctx; while (definitions != null && definitions.definition() != null) { List<Constructor> constructors = definitions.extendedAttributeList() != null ? definitions.extendedAttributeList().accept(new ExtendedAttributeListVisitor(parsingContext)) : Collections.emptyList(); List<String> extendedAttributes = definitions.extendedAttributeList() != null ? definitions.extendedAttributeList().accept(new GenericExtendedAttributeListVisitor()) : null; AbstractDefinition definition = definitions.definition().accept(new DefinitionVisitor(parsingContext, constructors, extendedAttributes)); if (definition != null) { definitionList.add(definition); } else { parsingContext.getLogger().reportError("Unexpected missed definition: " + ParsingContext.getText(ctx)); } definitions = definitions.definitions(); } return definitionList; } }
44.714286
149
0.722444
f725b7c0645e4dce7b090bf6b1252980dd682bf9
1,135
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.gruposet.ecommerce.models; /** * * @author thiago */ public class ItemPedido { private int id; private int produto_id; private int pedido_id; private float preco; private int quantidade; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getProduto_id() { return produto_id; } public void setProduto_id(int produto_id) { this.produto_id = produto_id; } public int getPedido_id() { return pedido_id; } public void setPedido_id(int pedido_id) { this.pedido_id = pedido_id; } public float getPreco() { return preco; } public void setPreco(float preco) { this.preco = preco; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } }
18.916667
79
0.617621
949212f4a124cfca1bb4a981e632527d3fe7cf50
1,565
package Characters; //Jplay imports import jplay.Animation; import jplay.Sprite; //Variables imports import static Main.Main.someMethods; import static Main.Main.window; /** * * @author Rodrigo Fernando da Silva */ public class Characters extends Thread { //Java variables public boolean itOver; public int spriteSheetEnable; //It for known which sprite sheet is going to be draw and update public int animationSpeed; public double[][] spriteAdjustX; public double[][] spriteAdjustY; public double x; public double y; //Jplay variables public Animation[] spriteSheet; public Sprite soul; /*---- Classe Methods ----*/ public void DrawSould() { if (someMethods.IsOnScene(soul, window)) { soul.draw(); } } public void DrawSpriteSheet() { if (someMethods.IsOnScene(spriteSheet[spriteSheetEnable], window)) { spriteSheet[spriteSheetEnable].draw(); } } public void UpdateSpriteSheet() { spriteSheet[spriteSheetEnable].update(); } public Sprite GetSoul() { return soul; } public Animation GetSpriteSheetEnable() { return spriteSheet[spriteSheetEnable]; } /** * Returns if the frame that was passed is higher than the correct frame that the sprite is * playing. * * @param frame * @return */ public boolean FrameHigherThan(int frame) { return (spriteSheet[spriteSheetEnable].getCurrFrame() > frame); } }
23.358209
98
0.632588
141a9dd1b2ed9459e2b0f498909f30040ddbcbb0
19,443
package com.bullhead.equalizer; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.media.audiofx.BassBoost; import android.media.audiofx.Equalizer; import android.media.audiofx.PresetReverb; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.SwitchCompat; import androidx.fragment.app.Fragment; import com.db.chart.model.LineSet; import com.db.chart.view.AxisController; import com.db.chart.view.ChartView; import com.db.chart.view.LineChartView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class EqualizerFragment extends Fragment { public static final String ARG_AUDIO_SESSIOIN_ID = "audio_session_id"; ImageView backBtn; TextView fragTitle; SwitchCompat equalizerSwitch; LineSet dataset; LineChartView chart; Paint paint; float[] points; int y = 0; ImageView spinnerDropDownIcon; short numberOfFrequencyBands; LinearLayout mLinearLayout; SeekBar[] seekBarFinal = new SeekBar[5]; AnalogController bassController, reverbController; Spinner presetSpinner; FrameLayout equalizerBlocker; Context ctx; public EqualizerFragment() { // Required empty public constructor } public Equalizer mEqualizer; public BassBoost bassBoost; public PresetReverb presetReverb; private int audioSesionId; static int themeColor = Color.parseColor("#B24242"); static boolean showBackButton = true; public static EqualizerFragment newInstance(int audioSessionId) { Bundle args = new Bundle(); args.putInt(ARG_AUDIO_SESSIOIN_ID, audioSessionId); EqualizerFragment fragment = new EqualizerFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Settings.isEditing = true; if (getArguments() != null && getArguments().containsKey(ARG_AUDIO_SESSIOIN_ID)){ audioSesionId = getArguments().getInt(ARG_AUDIO_SESSIOIN_ID); } if (Settings.equalizerModel == null){ Settings.equalizerModel = new EqualizerModel(); Settings.equalizerModel.setReverbPreset(PresetReverb.PRESET_NONE); Settings.equalizerModel.setBassStrength((short) (1000 / 19)); } mEqualizer = new Equalizer(0, audioSesionId); bassBoost = new BassBoost(0, audioSesionId); bassBoost.setEnabled(Settings.isEqualizerEnabled); BassBoost.Settings bassBoostSettingTemp = bassBoost.getProperties(); BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString()); bassBoostSetting.strength = Settings.equalizerModel.getBassStrength(); bassBoost.setProperties(bassBoostSetting); presetReverb = new PresetReverb(0, audioSesionId); presetReverb.setPreset(Settings.equalizerModel.getReverbPreset()); presetReverb.setEnabled(Settings.isEqualizerEnabled); mEqualizer.setEnabled(Settings.isEqualizerEnabled); if (Settings.presetPos == 0){ for (short bandIdx = 0; bandIdx < mEqualizer.getNumberOfBands(); bandIdx++) { mEqualizer.setBandLevel(bandIdx, (short) Settings.seekbarpos[bandIdx]); } } else { mEqualizer.usePreset((short) Settings.presetPos); } } @Override public void onAttach(Context context) { super.onAttach(context); ctx = context; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_equalizer, container, false); } @SuppressLint("SetTextI18n") @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); backBtn = view.findViewById(R.id.equalizer_back_btn); backBtn.setVisibility(showBackButton ? View.VISIBLE : View.GONE); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getActivity() != null) { getActivity().onBackPressed(); } } }); fragTitle = view.findViewById(R.id.equalizer_fragment_title); equalizerSwitch = view.findViewById(R.id.equalizer_switch); equalizerSwitch.setChecked(Settings.isEqualizerEnabled); equalizerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mEqualizer.setEnabled(isChecked); bassBoost.setEnabled(isChecked); presetReverb.setEnabled(isChecked); Settings.isEqualizerEnabled = isChecked; Settings.equalizerModel.setEqualizerEnabled(isChecked); } }); spinnerDropDownIcon = view.findViewById(R.id.spinner_dropdown_icon); spinnerDropDownIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { presetSpinner.performClick(); } }); presetSpinner = view.findViewById(R.id.equalizer_preset_spinner); equalizerBlocker = view.findViewById(R.id.equalizerBlocker); chart = view.findViewById(R.id.lineChart); paint = new Paint(); dataset = new LineSet(); bassController = view.findViewById(R.id.controllerBass); reverbController = view.findViewById(R.id.controller3D); bassController.setLabel("BASS"); reverbController.setLabel("3D"); bassController.circlePaint2.setColor(themeColor); bassController.linePaint.setColor(themeColor); bassController.invalidate(); reverbController.circlePaint2.setColor(themeColor); bassController.linePaint.setColor(themeColor); reverbController.invalidate(); if (!Settings.isEqualizerReloaded) { int x = 0; if (bassBoost != null) { try { x = ((bassBoost.getRoundedStrength() * 19) / 1000); } catch (Exception e) { e.printStackTrace(); } } if (presetReverb != null) { try { y = (presetReverb.getPreset() * 19) / 6; } catch (Exception e) { e.printStackTrace(); } } if (x == 0) { bassController.setProgress(1); } else { bassController.setProgress(x); } if (y == 0) { reverbController.setProgress(1); } else { reverbController.setProgress(y); } } else { int x = ((Settings.bassStrength * 19) / 1000); y = (Settings.reverbPreset * 19) / 6; if (x == 0) { bassController.setProgress(1); } else { bassController.setProgress(x); } if (y == 0) { reverbController.setProgress(1); } else { reverbController.setProgress(y); } } bassController.setOnProgressChangedListener(new AnalogController.onProgressChangedListener() { @Override public void onProgressChanged(int progress) { Settings.bassStrength = (short) (((float) 1000 / 19) * (progress)); try { bassBoost.setStrength(Settings.bassStrength); Settings.equalizerModel.setBassStrength(Settings.bassStrength); } catch (Exception e) { e.printStackTrace(); } } }); reverbController.setOnProgressChangedListener(new AnalogController.onProgressChangedListener() { @Override public void onProgressChanged(int progress) { Settings.reverbPreset = (short) ((progress * 6) / 19); Settings.equalizerModel.setReverbPreset(Settings.reverbPreset); try { presetReverb.setPreset(Settings.reverbPreset); } catch (Exception e) { e.printStackTrace(); } y = progress; } }); mLinearLayout = view.findViewById(R.id.equalizerContainer); TextView equalizerHeading = new TextView(getContext()); equalizerHeading.setText(R.string.eq); equalizerHeading.setTextSize(20); equalizerHeading.setGravity(Gravity.CENTER_HORIZONTAL); numberOfFrequencyBands = 5; points = new float[numberOfFrequencyBands]; final short lowerEqualizerBandLevel = mEqualizer.getBandLevelRange()[0]; final short upperEqualizerBandLevel = mEqualizer.getBandLevelRange()[1]; for (short i = 0; i < numberOfFrequencyBands; i++) { final short equalizerBandIndex = i; final TextView frequencyHeaderTextView = new TextView(getContext()); frequencyHeaderTextView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT )); frequencyHeaderTextView.setGravity(Gravity.CENTER_HORIZONTAL); frequencyHeaderTextView.setTextColor(Color.parseColor("#FFFFFF")); frequencyHeaderTextView.setText((mEqualizer.getCenterFreq(equalizerBandIndex) / 1000) + "Hz"); LinearLayout seekBarRowLayout = new LinearLayout(getContext()); seekBarRowLayout.setOrientation(LinearLayout.VERTICAL); TextView lowerEqualizerBandLevelTextView = new TextView(getContext()); lowerEqualizerBandLevelTextView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT )); lowerEqualizerBandLevelTextView.setTextColor(Color.parseColor("#FFFFFF")); lowerEqualizerBandLevelTextView.setText((lowerEqualizerBandLevel / 100) + "dB"); TextView upperEqualizerBandLevelTextView = new TextView(getContext()); lowerEqualizerBandLevelTextView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT )); upperEqualizerBandLevelTextView.setTextColor(Color.parseColor("#FFFFFF")); upperEqualizerBandLevelTextView.setText((upperEqualizerBandLevel / 100) + "dB"); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); layoutParams.weight = 1; SeekBar seekBar = new SeekBar(getContext()); TextView textView = new TextView(getContext()); switch (i) { case 0: seekBar = view.findViewById(R.id.seekBar1); textView = view.findViewById(R.id.textView1); break; case 1: seekBar = view.findViewById(R.id.seekBar2); textView = view.findViewById(R.id.textView2); break; case 2: seekBar = view.findViewById(R.id.seekBar3); textView = view.findViewById(R.id.textView3); break; case 3: seekBar = view.findViewById(R.id.seekBar4); textView = view.findViewById(R.id.textView4); break; case 4: seekBar = view.findViewById(R.id.seekBar5); textView = view.findViewById(R.id.textView5); break; } seekBarFinal[i] = seekBar; seekBar.getProgressDrawable().setColorFilter(new PorterDuffColorFilter(Color.DKGRAY, PorterDuff.Mode.SRC_IN)); seekBar.getThumb().setColorFilter(new PorterDuffColorFilter(themeColor, PorterDuff.Mode.SRC_IN)); seekBar.setId(i); // seekBar.setLayoutParams(layoutParams); seekBar.setMax(upperEqualizerBandLevel - lowerEqualizerBandLevel); textView.setText(frequencyHeaderTextView.getText()); textView.setTextColor(Color.WHITE); textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); if (Settings.isEqualizerReloaded) { points[i] = Settings.seekbarpos[i] - lowerEqualizerBandLevel; dataset.addPoint(frequencyHeaderTextView.getText().toString(), points[i]); seekBar.setProgress(Settings.seekbarpos[i] - lowerEqualizerBandLevel); } else { points[i] = mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel; dataset.addPoint(frequencyHeaderTextView.getText().toString(), points[i]); seekBar.setProgress(mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel); Settings.seekbarpos[i] = mEqualizer.getBandLevel(equalizerBandIndex); Settings.isEqualizerReloaded = true; } seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mEqualizer.setBandLevel(equalizerBandIndex, (short) (progress + lowerEqualizerBandLevel)); points[seekBar.getId()] = mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel; Settings.seekbarpos[seekBar.getId()] = (progress + lowerEqualizerBandLevel); Settings.equalizerModel.getSeekbarpos()[seekBar.getId()] = (progress + lowerEqualizerBandLevel); dataset.updateValues(points); chart.notifyDataUpdate(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { presetSpinner.setSelection(0); Settings.presetPos = 0; Settings.equalizerModel.setPresetPos(0); } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } equalizeSound(); paint.setColor(Color.parseColor("#555555")); paint.setStrokeWidth((float) (1.10 * Settings.ratio)); dataset.setColor(themeColor); dataset.setSmooth(true); dataset.setThickness(5); chart.setXAxis(false); chart.setYAxis(false); chart.setYLabels(AxisController.LabelPosition.NONE); chart.setXLabels(AxisController.LabelPosition.NONE); chart.setGrid(ChartView.GridType.NONE, 7, 10, paint); chart.setAxisBorderValues(-300, 3300); chart.addData(dataset); chart.show(); Button mEndButton = new Button(getContext()); mEndButton.setBackgroundColor(themeColor); mEndButton.setTextColor(Color.WHITE); } public void equalizeSound() { ArrayList<String> equalizerPresetNames = new ArrayList<>(); ArrayAdapter<String> equalizerPresetSpinnerAdapter = new ArrayAdapter<>(ctx, R.layout.spinner_item, equalizerPresetNames); equalizerPresetSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); equalizerPresetNames.add("Custom"); for (short i = 0; i < mEqualizer.getNumberOfPresets(); i++) { equalizerPresetNames.add(mEqualizer.getPresetName(i)); } presetSpinner.setAdapter(equalizerPresetSpinnerAdapter); //presetSpinner.setDropDownWidth((Settings.screen_width * 3) / 4); if (Settings.isEqualizerReloaded && Settings.presetPos != 0) { // correctPosition = false; presetSpinner.setSelection(Settings.presetPos); } presetSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { try { if (position != 0) { mEqualizer.usePreset((short) (position - 1)); Settings.presetPos = position; short numberOfFreqBands = 5; final short lowerEqualizerBandLevel = mEqualizer.getBandLevelRange()[0]; for (short i = 0; i < numberOfFreqBands; i++) { seekBarFinal[i].setProgress(mEqualizer.getBandLevel(i) - lowerEqualizerBandLevel); points[i] = mEqualizer.getBandLevel(i) - lowerEqualizerBandLevel; Settings.seekbarpos[i] = mEqualizer.getBandLevel(i); Settings.equalizerModel.getSeekbarpos()[i] = mEqualizer.getBandLevel(i); } dataset.updateValues(points); chart.notifyDataUpdate(); } } catch (Exception e) { Toast.makeText(ctx, "Error while updating Equalizer", Toast.LENGTH_SHORT).show(); } Settings.equalizerModel.setPresetPos(position); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); if (mEqualizer != null){ mEqualizer.release(); } if (bassBoost != null){ bassBoost.release(); } if (presetReverb != null){ presetReverb.release(); } Settings.isEditing = false; } public static Builder newBuilder() { return new Builder(); } public static class Builder { private int id = -1; public Builder setAudioSessionId(int id) { this.id = id; return this; } public Builder setAccentColor(int color) { themeColor = color; return this; } public Builder setShowBackButton(boolean show){ showBackButton = show; return this; } public EqualizerFragment build() { return EqualizerFragment.newInstance(id); } } }
36.754253
122
0.609577
8d48090acffc9111fc1ac1d6237b5e900e8d4f7b
2,718
package edu.ttu; import org.apache.commons.lang3.StringUtils; import org.apache.commons.math3.ml.clustering.Cluster; import org.apache.commons.math3.ml.clustering.Clusterable; import org.apache.commons.math3.ml.clustering.DBSCANClusterer; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Hello world! */ public class App { static class MemRequest implements Clusterable { private int index; private long memaddress; public MemRequest(int index, long memaddress) { this.index = index; this.memaddress = memaddress; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public long getMemaddress() { return memaddress; } public void setMemaddress(long memaddress) { this.memaddress = memaddress; } public double[] getPoint() { return new double[]{this.index, this.memaddress}; } } public static Collection<MemRequest> readMemRequest(String filepath) { final AtomicInteger i = new AtomicInteger(0); try(Stream<String> stream = Files.lines(Paths.get(filepath))) { return stream.map(line -> new MemRequest(i.incrementAndGet(), Long.decode(line.split(":")[3]))) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String hex = "0x00000000FFFFFFFF"; System.out.println(Long.decode(hex)); if (args.length >= 3) { double eps = StringUtils.isBlank(args[0]) ? 2048.0 : Double.valueOf(args[0]); int minpts = StringUtils.isBlank(args[1]) ? 100 : Integer.valueOf(args[1]); String filePath = args[2]; System.out.println(filePath); if (StringUtils.isBlank(filePath)) { System.err.println("The file path is not provided."); System.exit(0); } DBSCANClusterer<MemRequest> clusterer = new DBSCANClusterer<>(eps, minpts); List<Cluster<MemRequest>> cluster = clusterer.cluster(readMemRequest(filePath)); cluster.forEach(c -> System.out.println(String.format("Cluster %d with size = %d", c.hashCode(), c.getPoints().size()))); System.out.println("Hello World!"); } } }
28.914894
107
0.609272
23a7460b90995cec407e138c1858e760ce1397ad
23,719
package xreliquary.items; import com.google.common.collect.ImmutableMap; import lib.enderwizards.sandstone.init.ContentInit; import lib.enderwizards.sandstone.items.ItemToggleable; import lib.enderwizards.sandstone.util.ContentHelper; import lib.enderwizards.sandstone.util.InventoryHelper; import lib.enderwizards.sandstone.util.LanguageHelper; import lib.enderwizards.sandstone.util.NBTHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityLargeFireball; import net.minecraft.entity.projectile.EntitySmallFireball; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.*; import net.minecraft.world.World; import org.lwjgl.input.Keyboard; import xreliquary.Reliquary; import xreliquary.lib.Names; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by Xeno on 10/11/2014. */ @ContentInit public class ItemPyromancerStaff extends ItemToggleable { public ItemPyromancerStaff() { super(Names.pyromancer_staff); this.setCreativeTab(Reliquary.CREATIVE_TAB); this.setMaxStackSize(1); canRepair = false; } @Override public boolean isFull3D(){ return true; } @Override public void onUpdate(ItemStack ist, World world, Entity e, int i, boolean f) { if (!(e instanceof EntityPlayer)) return; EntityPlayer player = (EntityPlayer) e; doFireballAbsorbEffect(ist, player); if (!this.isEnabled(ist)) doExtinguishEffect(player); else scanForFireChargeAndBlazePowder(ist, player); } @Override public void addInformation(ItemStack ist, EntityPlayer player, List list, boolean par4) { //maps the contents of the Pyromancer's staff to a tooltip, so the player can review the torches stored within. if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) return; String charges = "0"; String blaze = "0"; NBTTagCompound tagCompound = NBTHelper.getTag(ist); if (tagCompound != null) { NBTTagList tagList = tagCompound.getTagList("Items", 10); for (int i = 0; i < tagList.tagCount(); ++i) { NBTTagCompound tagItemData = tagList.getCompoundTagAt(i); String itemName = tagItemData.getString("Name"); Item containedItem = Reliquary.CONTENT.getItem(itemName); int quantity = tagItemData.getInteger("Quantity"); if (containedItem == Items.blaze_powder) { blaze = Integer.toString(quantity); } else if (containedItem == Items.fire_charge) { charges = Integer.toString(quantity); } } } this.formatTooltip(ImmutableMap.of("charges", charges, "blaze", blaze), ist, list); if(this.isEnabled(ist)) LanguageHelper.formatTooltip("tooltip.absorb_active", ImmutableMap.of("item", EnumChatFormatting.RED + Items.blaze_powder.getItemStackDisplayName(new ItemStack(Items.blaze_powder)) + EnumChatFormatting.WHITE + " & " + EnumChatFormatting.RED + Items.fire_charge.getItemStackDisplayName(new ItemStack(Items.fire_charge))), ist, list); LanguageHelper.formatTooltip("tooltip.absorb", null, ist, list); } @Override public int getMaxItemUseDuration(ItemStack par1ItemStack) { return 11; } @Override public EnumAction getItemUseAction(ItemStack ist) { return EnumAction.block; } public String getMode(ItemStack ist) { if (NBTHelper.getString("mode", ist).equals("")) { setMode(ist, "blaze"); } return NBTHelper.getString("mode", ist); } public void setMode(ItemStack ist, String s) { NBTHelper.setString("mode", ist, s); } public void cycleMode(ItemStack ist) { if (getMode(ist).equals("blaze")) setMode(ist, "charge"); else if (getMode(ist).equals("charge")) setMode(ist, "eruption"); else if (getMode(ist).equals("eruption")) setMode(ist, "flint_and_steel"); else setMode(ist, "blaze"); } @Override public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack ist) { if (entityLiving.worldObj.isRemote) return true; if (!(entityLiving instanceof EntityPlayer)) return true; EntityPlayer player = (EntityPlayer)entityLiving; if (player.isSneaking()) { cycleMode(ist); } return false; } @Override public ItemStack onItemRightClick(ItemStack ist, World world, EntityPlayer player) { if (player.isSneaking()) super.onItemRightClick(ist, world, player); else { if (getMode(ist).equals("blaze")) { if (player.isSwingInProgress) return ist; player.swingItem(); Vec3 lookVec = player.getLookVec(); //blaze fireball! if (removeItemFromInternalStorage(ist, Items.blaze_powder, getBlazePowderCost(), player.worldObj.isRemote)) { player.worldObj.playAuxSFXAtEntity(player, 1009, (int)player.posX, (int)player.posY, (int)player.posZ, 0); EntitySmallFireball fireball = new EntitySmallFireball(player.worldObj, player, lookVec.xCoord, lookVec.yCoord, lookVec.zCoord); fireball.accelerationX = lookVec.xCoord; fireball.accelerationY = lookVec.yCoord; fireball.accelerationZ = lookVec.zCoord; fireball.posX += lookVec.xCoord; fireball.posY += lookVec.yCoord; fireball.posZ += lookVec.zCoord; fireball.posY = player.posY + player.getEyeHeight(); player.worldObj.spawnEntityInWorld(fireball); } } else if (getMode(ist).equals("charge")) { if (player.isSwingInProgress) return ist; player.swingItem(); Vec3 lookVec = player.getLookVec(); //ghast fireball! if (removeItemFromInternalStorage(ist, Items.fire_charge, getFireChargeCost(), player.worldObj.isRemote)) { player.worldObj.playAuxSFXAtEntity(player, 1008, (int)player.posX, (int)player.posY, (int)player.posZ, 0); EntityLargeFireball fireball = new EntityLargeFireball(player.worldObj, player, lookVec.xCoord, lookVec.yCoord, lookVec.zCoord); fireball.accelerationX = lookVec.xCoord; fireball.accelerationY = lookVec.yCoord; fireball.accelerationZ = lookVec.zCoord; fireball.posX += lookVec.xCoord; fireball.posY += lookVec.yCoord; fireball.posZ += lookVec.zCoord; fireball.posY = player.posY + player.getEyeHeight(); player.worldObj.spawnEntityInWorld(fireball); } } else player.setItemInUse(ist, this.getMaxItemUseDuration(ist)); } return ist; } //a longer ranged version of "getMovingObjectPositionFromPlayer" basically public MovingObjectPosition getEruptionBlockTarget(World world, EntityPlayer player) { float f = 1.0F; float f1 = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * f; float f2 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double)f; double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double)f + (double)(world.isRemote ? player.getEyeHeight() - player.getDefaultEyeHeight() : player.getEyeHeight()); // isRemote check to revert changes to ray trace position due to adding the eye height clientside and player yOffset differences double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double)f; Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); float f4 = MathHelper.sin(-f2 * 0.017453292F - (float)Math.PI); float f5 = -MathHelper.cos(-f1 * 0.017453292F); float f6 = MathHelper.sin(-f1 * 0.017453292F); float f7 = f4 * f5; float f8 = f3 * f5; double d3 = 12.0D; Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3); return world.func_147447_a(vec3, vec31, true, false, false); } @Override public void onUsingTick(ItemStack ist, EntityPlayer player, int count) { //mop call and fakes onItemUse, getting read to do the eruption effect. If the item is enabled, it just sets a bunch of fires! MovingObjectPosition mop = this.getEruptionBlockTarget(player.worldObj, player); if (mop != null && mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { if (getMode(ist).equals("eruption")) { count -= 1; count = getMaxItemUseDuration(ist) - count; doEruptionAuxEffects(player, mop.blockX, mop.blockY, mop.blockZ, 5D); if (count % 10 == 0) { if (removeItemFromInternalStorage(ist, Items.blaze_powder, getBlazePowderCost(), player.worldObj.isRemote)) { doEruptionEffect(player, mop.blockX, mop.blockY, mop.blockZ, 5D); } } } else if (getMode(ist).equals("flint_and_steel")) { this.onItemUse(ist, player, player.worldObj, mop.blockX, mop.blockY, mop.blockZ, mop.sideHit, (float)player.posX, (float)player.posY, (float)player.posZ); } } } public boolean onItemUse(ItemStack ist, EntityPlayer player, World world, int x, int y, int z, int sideHit, float xOff, float yOff, float zOff) { //while enabled only, if disabled, it will do an eruption effect instead. //if (this.isEnabled(ist)) { if (getMode(ist).equals("flint_and_steel")) { if (sideHit == 0) { --y; } if (sideHit == 1) { ++y; } if (sideHit == 2) { --z; } if (sideHit == 3) { ++z; } if (sideHit == 4) { --x; } if (sideHit == 5) { ++x; } if (!player.canPlayerEdit(x, y, z, sideHit, ist)) { return false; } else { if (world.isAirBlock(x, y, z)) { world.playSoundEffect((double) x + 0.5D, (double) y + 0.5D, (double) z + 0.5D, "fire.ignite", 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); world.setBlock(x, y, z, Blocks.fire); } return false; } } return false; } public void doEruptionAuxEffects(EntityPlayer player, int x, int y, int z, double areaCoefficient) { double soundX = x; double soundY = y; double soundZ = z; player.worldObj.playSound(soundX + 0.5D, soundY + 0.5D, soundZ + 0.5D, "mob.ghast.fireball", 0.2F, 0.03F + (0.07F * itemRand.nextFloat()), false); for (int particleCount = 0; particleCount < 2; ++particleCount) { double randX = (x + 0.5D) + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient; double randZ = (z + 0.5D) + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient; if (Math.abs(randX - (x + 0.5D)) >= 4.0D && Math.abs(randZ - (z + 0.5D)) >= 4.0D) continue; player.worldObj.spawnParticle("lava", randX, y + 1D, randZ, 0D,0D,0D); } for (int particleCount = 0; particleCount < 4; ++particleCount) { double randX = x + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient / 2D; double randZ = z + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient / 2D; if (Math.abs(randX - (x + 0.5D)) >= 4.0D && Math.abs(randZ - (z + 0.5D)) >= 4.0D) continue; player.worldObj.spawnParticle("lava", randX, y + 1D, randZ, 0D,0D,0D); } for (int particleCount = 0; particleCount < 6; ++particleCount) { double randX = x + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient; double randZ = z + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient; if (Math.abs(randX - (x + 0.5D)) >= 4.0D && Math.abs(randZ - (z + 0.5D)) >= 4.0D) continue; player.worldObj.spawnParticle("flame", randX, y + 1D, randZ, player.worldObj.rand.nextGaussian() * 0.2D, player.worldObj.rand.nextGaussian() * 0.2D, player.worldObj.rand.nextGaussian() * 0.2D); } for (int particleCount = 0; particleCount < 8; ++particleCount) { double randX = x + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient / 2D; double randZ = z + 0.5D + (player.worldObj.rand.nextFloat() - 0.5F) * areaCoefficient / 2D; if (Math.abs(randX - (x + 0.5D)) >= 4.0D && Math.abs(randZ - (z + 0.5D)) >= 4.0D) continue; player.worldObj.spawnParticle("flame", randX, y + 1D, randZ, player.worldObj.rand.nextGaussian() * 0.2D, player.worldObj.rand.nextGaussian() * 0.2D, player.worldObj.rand.nextGaussian() * 0.2D); } } public void doEruptionEffect(EntityPlayer player, int x, int y, int z, double areaCoefficient) { double lowerX = x - areaCoefficient + 0.5D; double lowerZ = z - areaCoefficient + 0.5D; double upperX = x + areaCoefficient + 0.5D; double upperY = y + areaCoefficient; double upperZ = z + areaCoefficient + 0.5D; List eList = player.worldObj.getEntitiesWithinAABB(EntityLiving.class, AxisAlignedBB.getBoundingBox(lowerX, y, lowerZ, upperX, upperY, upperZ)); Iterator iterator = eList.iterator(); while (iterator.hasNext()) { Entity e = (Entity)iterator.next(); if (e instanceof EntityLivingBase && !e.isEntityEqual(player)) { e.setFire(40); if (!e.isImmuneToFire()) e.attackEntityFrom(DamageSource.causePlayerDamage(player), 4F); } } } private void scanForFireChargeAndBlazePowder(ItemStack ist, EntityPlayer player) { List<Item> absorbItems = new ArrayList<Item>(); absorbItems.add(Items.fire_charge); absorbItems.add(Items.blaze_powder); for (Item absorbItem : absorbItems) { if (!isInternalStorageFullOfItem(ist, absorbItem) && InventoryHelper.consumeItem(absorbItem, player)) { addItemToInternalStorage(ist, absorbItem, false); } } } private void addItemToInternalStorage(ItemStack ist, Item item, boolean isAbsorb) { int quantityIncrease = item == Items.fire_charge ? (isAbsorb ? getGhastAbsorbWorth() : getFireChargeWorth()) : (isAbsorb ? getBlazeAbsorbWorth() : getBlazePowderWorth()); NBTTagCompound tagCompound = NBTHelper.getTag(ist); if (tagCompound.getTag("Items") == null) tagCompound.setTag("Items", new NBTTagList()); NBTTagList tagList = tagCompound.getTagList("Items", 10); boolean added = false; for (int i = 0; i < tagList.tagCount(); ++i) { NBTTagCompound tagItemData = tagList.getCompoundTagAt(i); String itemName = tagItemData.getString("Name"); if (itemName.equals(ContentHelper.getIdent(item))) { int quantity = tagItemData.getInteger("Quantity"); tagItemData.setInteger("Quantity", quantity + quantityIncrease); added = true; } } if (!added) { NBTTagCompound newTagData = new NBTTagCompound(); newTagData.setString("Name", ContentHelper.getIdent(item)); newTagData.setInteger("Quantity", quantityIncrease); tagList.appendTag(newTagData); } tagCompound.setTag("Items", tagList); NBTHelper.setTag(ist, tagCompound); } public boolean removeItemFromInternalStorage(ItemStack ist, Item item, int cost, boolean simulate) { if (hasItemInInternalStorage(ist, item, cost)) { NBTTagCompound tagCompound = NBTHelper.getTag(ist); NBTTagList tagList = tagCompound.getTagList("Items", 10); NBTTagList replacementTagList = new NBTTagList(); for (int i = 0; i < tagList.tagCount(); ++i) { NBTTagCompound tagItemData = tagList.getCompoundTagAt(i); String itemName = tagItemData.getString("Name"); if (itemName.equals(ContentHelper.getIdent(item))) { int quantity = tagItemData.getInteger("Quantity"); if (!simulate) tagItemData.setInteger("Quantity", quantity - cost); } replacementTagList.appendTag(tagItemData); } tagCompound.setTag("Items", replacementTagList); NBTHelper.setTag(ist, tagCompound); return true; } return false; } private boolean hasItemInInternalStorage(ItemStack ist, Item item, int cost) { NBTTagCompound tagCompound = NBTHelper.getTag(ist); if (tagCompound.hasNoTags()) { tagCompound.setTag("Items", new NBTTagList()); return false; } NBTTagList tagList = tagCompound.getTagList("Items", 10); for (int i = 0; i < tagList.tagCount(); ++i) { NBTTagCompound tagItemData = tagList.getCompoundTagAt(i); String itemName = tagItemData.getString("Name"); if (itemName.equals(ContentHelper.getIdent(item))) { int quantity = tagItemData.getInteger("Quantity"); return quantity >= cost; } } return false; } private boolean isInternalStorageFullOfItem(ItemStack ist, Item item) { int quantityLimit = item == Items.fire_charge ? getFireChargeLimit() : getBlazePowderLimit(); if (hasItemInInternalStorage(ist, item, 1)) { NBTTagCompound tagCompound = NBTHelper.getTag(ist); NBTTagList tagList = tagCompound.getTagList("Items", 10); for (int i = 0; i < tagList.tagCount(); ++i) { NBTTagCompound tagItemData = tagList.getCompoundTagAt(i); String itemName = tagItemData.getString("Name"); if (itemName.equals(ContentHelper.getIdent(item))) { int quantity = tagItemData.getInteger("Quantity"); return quantity >= quantityLimit; } } } return false; } private int getFireChargeWorth() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "fire_charge_worth"); } private int getFireChargeCost() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "fire_charge_cost"); } private int getFireChargeLimit() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "fire_charge_limit"); } private int getBlazePowderWorth() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "blaze_powder_worth"); } private int getBlazePowderCost() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "blaze_powder_cost"); } private int getBlazePowderLimit() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "blaze_powder_limit"); } private int getBlazeAbsorbWorth() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "blaze_absorb_worth"); } private int getGhastAbsorbWorth() { return Reliquary.CONFIG.getInt(Names.pyromancer_staff, "ghast_absorb_worth"); } private void doExtinguishEffect(EntityPlayer player) { if (player.isBurning()) { player.extinguish(); } int x = (int) Math.floor(player.posX); int y = (int) Math.floor(player.posY); int z = (int) Math.floor(player.posZ); for (int xOff = -3; xOff <= 3; xOff++) { for (int yOff = -3; yOff <= 3; yOff++) { for (int zOff = -3; zOff <= 3; zOff++) if (ContentHelper.getIdent(player.worldObj.getBlock(x + xOff, y + yOff, z + zOff)).equals(ContentHelper.getIdent(Blocks.fire))) { player.worldObj.setBlock(x + xOff, y + yOff, z + zOff, Blocks.air); player.worldObj.playSoundEffect(x + xOff + 0.5D, y + yOff + 0.5D, z + zOff + 0.5D, "random.fizz", 0.5F, 2.6F + (player.worldObj.rand.nextFloat() - player.worldObj.rand.nextFloat()) * 0.8F); } } } } private void doFireballAbsorbEffect(ItemStack ist, EntityPlayer player) { List ghastFireballs = player.worldObj.getEntitiesWithinAABB(EntityLargeFireball.class, AxisAlignedBB.getBoundingBox(player.posX - 5, player.posY - 5, player.posZ - 5, player.posX + 5, player.posY + 5, player.posZ + 5)); Iterator fire1 = ghastFireballs.iterator(); while (fire1.hasNext()) { EntityLargeFireball fireball = (EntityLargeFireball) fire1.next(); if (fireball.shootingEntity == player) continue; if (player.getDistanceToEntity(fireball) < 4) { if (!isInternalStorageFullOfItem(ist, Items.fire_charge) && InventoryHelper.consumeItem(Items.fire_charge, player)) { addItemToInternalStorage(ist, Items.fire_charge, true); player.worldObj.playSoundEffect(fireball.posX, fireball.posY, fireball.posZ, "random.fizz", 0.5F, 2.6F + (player.worldObj.rand.nextFloat() - player.worldObj.rand.nextFloat()) * 0.8F); } fireball.setDead(); } } List blazeFireballs = player.worldObj.getEntitiesWithinAABB(EntitySmallFireball.class, AxisAlignedBB.getBoundingBox(player.posX - 3, player.posY - 3, player.posZ - 3, player.posX + 3, player.posY + 3, player.posZ + 3)); Iterator fire2 = blazeFireballs.iterator(); while (fire2.hasNext()) { EntitySmallFireball fireball = (EntitySmallFireball) fire2.next(); if (fireball.shootingEntity == player) continue; for (int particles = 0; particles < 4; particles++) { player.worldObj.spawnParticle("reddust", fireball.posX, fireball.posY, fireball.posZ, 0.0D, 1.0D, 1.0D); } player.worldObj.playSoundEffect(fireball.posX, fireball.posY, fireball.posZ, "random.fizz", 0.5F, 2.6F + (player.worldObj.rand.nextFloat() - player.worldObj.rand.nextFloat()) * 0.8F); if (!isInternalStorageFullOfItem(ist, Items.blaze_powder) && InventoryHelper.consumeItem(Items.blaze_powder, player)) { addItemToInternalStorage(ist, Items.blaze_powder, true); } fireball.setDead(); } } }
46.145914
344
0.608584
080f3a46e308246966e6523d32f7b53a78f6dc9c
3,292
package com.theflopguyproductions.ticktrack.dialogs; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import androidx.constraintlayout.widget.ConstraintLayout; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.theflopguyproductions.ticktrack.R; import com.theflopguyproductions.ticktrack.ui.utils.TickTrackProgressBar; import com.theflopguyproductions.ticktrack.utils.database.TickTrackDatabase; import java.util.Objects; public class ProgressBarDialog extends BottomSheetDialog { private Activity activity; public TickTrackProgressBar tickTrackProgressBar; public TextView titleText, contentText; private ConstraintLayout rootLayout; private TickTrackDatabase tickTrackDatabase; private int themeSet = 1; public ProgressBarDialog(Activity activity) { super(activity); this.activity = activity; } private void initVariables(View view) { titleText = view.findViewById(R.id.progressBarTitleTickTrack); contentText = view.findViewById(R.id.progressBarContentTickTrack); tickTrackProgressBar = view.findViewById(R.id.tickTrackProgressBar); rootLayout = findViewById(R.id.progressBarTickTrackRootLayout); tickTrackProgressBar.spin(); } private void setupTheme() { if(themeSet==1){ rootLayout.setBackgroundResource(R.color.LightGray); titleText.setTextColor(activity.getResources().getColor(R.color.DarkText)); contentText.setTextColor(activity.getResources().getColor(R.color.DarkText)); } else { rootLayout.setBackgroundResource(R.color.Gray); contentText.setTextColor(activity.getResources().getColor(R.color.LightText)); titleText.setTextColor(activity.getResources().getColor(R.color.LightText)); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = activity.getLayoutInflater().inflate(R.layout.dialog_progress_bar_layout, new ConstraintLayout(activity), false); setContentView(view); Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); int width = Math.min(metrics.widthPixels, 1280); int height = -1; // MATCH_PARENT getWindow().setLayout(width, height); initVariables(view); tickTrackDatabase = new TickTrackDatabase(activity); themeSet = tickTrackDatabase.getThemeMode(); setupTheme(); setCancelable(false); } public void setTitleText(String titleText){ this.titleText.setText(titleText); } public void setContentText(String contentText){ this.contentText.setText(contentText); } }
35.021277
133
0.735115
8e36ca86616fd19e0369ab553dfdc4dc25e615cf
8,714
package com.haibin.calendarviewproject.range; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.CalendarLayout; import com.haibin.calendarview.CalendarView; import com.haibin.calendarviewproject.R; import com.haibin.calendarviewproject.base.activity.BaseActivity; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyRangeActivity extends BaseActivity implements CalendarView.OnCalendarInterceptListener, CalendarView.OnCalendarRangeSelectListener, CalendarView.OnMonthChangeListener, View.OnClickListener { CalendarLayout mCalendarLayout; CalendarView mCalendarView; private TextView tv_time; private int mCalendarHeight; public static void show(Context context) { context.startActivity(new Intent(context, MyRangeActivity.class)); } @Override protected int getLayoutId() { return R.layout.activity_range_my; } @SuppressLint("SetTextI18n") @Override protected void initView() { setStatusBarDarkMode(); tv_time = findViewById(R.id.tv_time); findViewById(R.id.iv_left).setOnClickListener(this); findViewById(R.id.iv_right).setOnClickListener(this); mCalendarLayout = findViewById(R.id.calendarLayout); mCalendarView = findViewById(R.id.calendarView); mCalendarView.setOnCalendarRangeSelectListener(this); mCalendarView.setOnMonthChangeListener(this); //设置日期拦截事件,当前有效 mCalendarView.setOnCalendarInterceptListener(this); findViewById(R.id.tv_commit).setOnClickListener(this); mCalendarHeight = dipToPx(this, 50); mCalendarView.post(new Runnable() { @Override public void run() { mCalendarView.scrollToCurrent(); } }); } @Override protected void initData() { int year = mCalendarView.getCurYear(); int month = mCalendarView.getCurMonth(); tv_time.setText(year+"年"+month+"月"); int day = mCalendarView.getCurDay(); Map<String, Calendar> map = new HashMap<>(); map.put(getSchemeCalendar(year, month, 1, 0xFFff0000, "休").toString(), getSchemeCalendar(year, month, 1, 0xFFff0000, "休")); map.put(getSchemeCalendar(year, month, 2, 0xFFff0000, "休").toString(), getSchemeCalendar(year, month, 2, 0xFFff0000, "休")); map.put(getSchemeCalendar(year, month, 3, 0xFFff0000, "休").toString(), getSchemeCalendar(year, month, 3, 0xFFff0000, "休")); map.put(getSchemeCalendar(year, month, 4, 0xFFff0000, "休").toString(), getSchemeCalendar(year, month, 4, 0xFFff0000, "休")); map.put(getSchemeCalendar(year, month, 5, 0xFFff0000, "休").toString(), getSchemeCalendar(year, month, 5, 0xFFff0000, "休")); map.put(getSchemeCalendar(year, month, 8, 0xFFff0000, "班").toString(), getSchemeCalendar(year, month, 8, 0xFFff0000, "班")); map.put(getSchemeCalendar(2021, 6, 12, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 6, 12, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 6, 13, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 6, 13, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 6, 14, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 6, 14, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 9, 18, 0xFFff0000, "班").toString(), getSchemeCalendar(2021, 9, 18, 0xFFff0000, "班")); map.put(getSchemeCalendar(2021, 9, 19, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 9, 19, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 9, 20, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 9, 20, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 9, 21, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 9, 21, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 9, 26, 0xFFff0000, "班").toString(), getSchemeCalendar(2021, 9, 26, 0xFFff0000, "班")); map.put(getSchemeCalendar(2021, 10, 1, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 1, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 2, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 2, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 3, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 3, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 4, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 4, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 5, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 5, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 6, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 6, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 7, 0xFFff0000, "休").toString(), getSchemeCalendar(2021, 10, 7, 0xFFff0000, "休")); map.put(getSchemeCalendar(2021, 10, 9, 0xFFff0000, "班").toString(), getSchemeCalendar(2021, 10, 9, 0xFFff0000, "班")); //此方法在巨大的数据量上不影响遍历性能,推荐使用 mCalendarView.setSchemeDate(map); } private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) { Calendar calendar = new Calendar(); calendar.setYear(year); calendar.setMonth(month); calendar.setDay(day); calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色 calendar.setScheme(text); calendar.addScheme(new Calendar.Scheme()); calendar.addScheme(0xFF008800, "假"); calendar.addScheme(0xFF008800, "节"); return calendar; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_left: mCalendarView.scrollToPre(); break; case R.id.iv_right: mCalendarView.scrollToNext(); break; case R.id.tv_commit: List<Calendar> calendars = mCalendarView.getSelectCalendarRange(); if (calendars == null || calendars.size() == 0) { Toast.makeText(this, "请选择开始时间和结束时间", Toast.LENGTH_SHORT).show(); return; } for (Calendar c : calendars) { Log.e("SelectCalendarRange", c.toString() + " -- " + c.getTimeInMillis() + " -- " + c.getLunar()); } Toast.makeText(this, String.format("选择了%s个日期: %s —— %s", calendars.size(), calendars.get(0).toString(), calendars.get(calendars.size() - 1).toString()), Toast.LENGTH_SHORT).show(); break; } } private static int dipToPx(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 屏蔽某些不可点击的日期,可根据自己的业务自行修改 * 如 calendar > 2018年1月1日 && calendar <= 2020年12月31日 * @param calendar calendar * @return 是否屏蔽某些不可点击的日期,MonthView和WeekView有类似的API可调用 */ @Override public boolean onCalendarIntercept(Calendar calendar) { return false; //return calendar.getTimeInMillis()<getCurrentDayMill() ; } @Override public void onCalendarInterceptClick(Calendar calendar, boolean isClick) { Toast.makeText(this, calendar.toString() + (isClick ? "拦截不可点击" : "拦截设定为无效日期"), Toast.LENGTH_SHORT).show(); } @Override public void onMonthChange(int year, int month) { Log.e("onMonthChange", " -- " + year + " -- " + month); tv_time.setText(year+"年"+month+"月"); } @Override public void onCalendarSelectOutOfRange(Calendar calendar) { } @Override public void onSelectOutOfRange(Calendar calendar, boolean isOutOfMinRange) { Toast.makeText(this, calendar.toString() + (isOutOfMinRange ? "小于最小选择范围" : "超过最大选择范围"), Toast.LENGTH_SHORT).show(); } @SuppressLint("SetTextI18n") @Override public void onCalendarRangeSelect(Calendar calendar, boolean isEnd) { } }
40.910798
101
0.617397
7653ef8f5d009420b9ddc93b2337a2870c73a014
823
/** * @Author: ouyangyameng * @Date: 2021/4/20 1:43 下午 * @Version 1.0 */ public class FindtheDuplicateNumber278 { public static void main(String[] args) { FindtheDuplicateNumber278 o = new FindtheDuplicateNumber278(); o.findDuplicate(new int[]{}); } public int findDuplicate(int[] nums) { for (int i = 0; i < nums.length; i++) { int value = Math.abs(nums[i]); if (nums[value-1] < 0) { return value; } nums[value-1] = -nums[value-1]; } return 0; } public int findDuplicate2(int[] nums) { int[] t = new int[nums.length]; for (int i = 0; i < nums.length; i++) { if (t[nums[i]]++ > 0) { return nums[i]; } } return 0; } }
24.939394
70
0.486027
eebae4ac6b8e8885fb158297555371d8746f8374
2,821
package test.com.sagui.model.pages.employee.tabular; import java.util.ArrayList; import java.util.List; import test.com.sagui.model.pages.crud.employee.Employee; import test.com.sagui.model.pages.employee.model.EmployeeDataModel; import com.sagui.dataset.commons.dataset.IBookmark; import com.sagui.dataset.commons.field.IField; import com.sagui.forms.tabular.FatuAbstractTabularForm; import com.sagui.model.FatuComponent; import com.sagui.model.action.IFatuActionEvent; import com.sagui.model.datamodel.FatuAbstractTableModel; import com.sagui.model.datasource.FatuAbstractDataSource; import com.sagui.model.datasource.FatuRowIndexDataModelDataSource; import com.sagui.model.editable.editbox.FatuTextBox; import com.sagui.model.editable.list.checkbox.FatuCheckbox; public class EmployeeTabularTestForm extends FatuAbstractTabularForm { private final EmployeeDataModel dataModel; public EmployeeTabularTestForm() { this.dataModel = new EmployeeDataModel(); this.dataModel.reload(); super.createUI(); } @Override public void btnNewOnClick(IFatuActionEvent evt) { this.dataModel.createNewEmployee(); } @Override public void btnSaveOnClick(IFatuActionEvent evt) { this.dataModel.saveAll(); } @Override public void btnDeleteOnClick(IFatuActionEvent evt) { List<IBookmark<Employee>> toRemoveList = new ArrayList<IBookmark<Employee>>(); for (int row = 0; row < dataModel.getRowCount(); row++) { Boolean value = dataModel.isSelected(row); if (value != null && value == true) { IBookmark<Employee> emp = dataModel.getBookmark(row); toRemoveList.add(emp); } } for (IBookmark<Employee> toRemove : toRemoveList) { this.dataModel.remove(toRemove); } } @Override protected <V> FatuComponent getCellComponent(int row, int col, FatuAbstractDataSource<V> datasource) { IField<Employee> theField = dataModel.getColumn(col); if (theField == dataModel.selectField) { FatuAbstractDataSource<Boolean> ds = new FatuRowIndexDataModelDataSource<Employee, Boolean>(dataModel, row, theField); FatuCheckbox ckBox = new FatuCheckbox(ds); return ckBox; } else { FatuAbstractDataSource<String> ds = new FatuRowIndexDataModelDataSource<Employee, String>(dataModel, row, theField); return new FatuTextBox(ds); } } @Override protected <T> FatuAbstractTableModel<T> getDataModel() { return (FatuAbstractTableModel<T>) this.dataModel; } @Override protected FatuComponent getColumnHeader(int i) { return null; } }
35.708861
131
0.680964
68fbad775fdde62b021e633e9dafbc0109352c15
600
package com.thinkgem.jeesite.modules.ips.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional(readOnly = true) @Lazy(false) public class TaskService { @Autowired private ReptileTaskService reptileTaskService; @Scheduled(cron = "0/30 * * * * ?") public void saveTaskData(){ System.out.println(1); } }
28.571429
64
0.773333
c27e6c2d1aa9ab84f17487e57ba1f3105639a528
6,260
package net.whg.we.net.server; import java.io.IOException; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.whg.we.net.IDataHandler; import net.whg.we.net.IPacket; import net.whg.we.net.IServerSocket; /** * A standard implementation for a TCP, multithreaded server. */ public class SimpleServer implements IServer { private static final Logger logger = LoggerFactory.getLogger(SimpleServer.class); private final List<IConnectedClient> connectedClients = Collections.synchronizedList(new ArrayList<>()); private final BlockingQueue<IPacket> packets = new ArrayBlockingQueue<>(256); private IClientHandler clientHandler; private IDataHandler dataHandler; private IServerSocket socket; private volatile boolean activeServerThread; @Override public void setClientHandler(IClientHandler handler) { if (isRunning()) throw new IllegalStateException("Server is running!"); clientHandler = handler; } @Override public void setDataHandler(IDataHandler handler) { if (isRunning()) throw new IllegalStateException("Server is running!"); dataHandler = handler; } @Override public void start(IServerSocket socket, int port) throws IOException { if (isRunning()) throw new IllegalStateException("Server is already running!"); if (!socket.isClosed()) throw new IllegalArgumentException("Server socket already open!"); if (clientHandler == null) throw new IllegalStateException("Client handler not defined!"); if (dataHandler == null) throw new IllegalStateException("Data handler not defined!"); this.socket = socket; startServerSocket(port); } private void startServerSocket(int port) throws IOException { socket.start(port); logger.info("Started server socket on port {}.", socket.getLocalPort()); activeServerThread = true; var thread = new Thread(new ListenerThread()); thread.setName("server-thread"); thread.setDaemon(false); thread.start(); } @Override public void stop() { if (!isRunning()) return; activeServerThread = false; kickAllClients(); tryCloseSocket(); packets.clear(); } private void tryCloseSocket() { try { socket.close(); } catch (IOException e) { logger.error("Failed to close server socket!", e); } } /** * Kicks all clients currently connected. */ public void kickAllClients() { while (!connectedClients.isEmpty()) { var client = connectedClients.get(0); try { client.kick(); } catch (IOException e) { var ip = client.getConnection() .getIP(); logger.error("Failed to kick client {}!", ip, e); } } } @Override public boolean isRunning() { return socket != null && !socket.isClosed(); } @Override public List<IConnectedClient> getConnectedClients() { return Collections.unmodifiableList(connectedClients); } @Override public void handlePackets() { if (!isRunning()) return; int count = packets.size(); for (int i = 0; i < count; i++) { var packet = packets.poll(); packet.handle(); } } /** * The thread in charge of listening for incoming client connections. */ private class ListenerThread implements Runnable { @Override public void run() { try { listenForClients(); } catch (SocketException e) { logger.info("Closed server socket."); } catch (Exception e) { logger.error("Failed to accept client socket!", e); } finally { tryCloseSocket(); } } private void listenForClients() throws IOException { while (activeServerThread) { var s = socket.waitForClient(); var client = new ServerClient(s, dataHandler); var ip = s.getIP(); logger.info("Client '{}' connected.", ip); var thread = new Thread(new ClientThread(client)); thread.setName("client-" + ip); thread.setDaemon(true); thread.start(); } } } /** * The thread in charge of receiving incoming data from clients. */ private class ClientThread implements Runnable { private final IConnectedClient client; public ClientThread(IConnectedClient client) { this.client = client; } @Override public void run() { connectedClients.add(client); try { clientHandler.onClientConnected(client); while (activeServerThread) packets.put(client.readPacket()); } catch (SocketException e) { // Client disconnected } catch (Exception e) { logger.error("Failed to read incoming packet!", e); } finally { try { client.kick(); } catch (IOException e) { logger.error("Failed to close server socket!", e); } clientHandler.onClientDisconnected(client); connectedClients.remove(client); } } } }
25.241935
108
0.541853
881488c620b71268b821aaa4a76b652ab26db70d
3,349
package com.pengyifan.brat; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; import com.google.common.testing.EqualsTester; public class BratEntityTest { private static final String LINE = "T1\tOrganization 48 53;56 57\tSony"; private static final String ID = "T1"; private static final String TYPE = "Organization"; private static final String TEXT = "Sony"; private static final String ID_2 = "T2"; private static final String TYPE_2 = "Organization2"; private static final String TEXT_2 = "Sony2"; private static final Range<Integer> SPAN_1 = Range.closedOpen(48, 53); private static final Range<Integer> SPAN_2 = Range.closedOpen(56, 57); private static final Range<Integer> SPAN_3 = Range.closedOpen(23, 30); private BratEntity base; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { base = new BratEntity(); base.setId(ID); base.addSpan(SPAN_1); base.addSpan(SPAN_2.lowerEndpoint(), SPAN_2.upperEndpoint()); base.setText(TEXT); base.setType(TYPE); } @Test public void testEquals() { BratEntity baseCopy = new BratEntity(base); BratEntity diffId = new BratEntity(base); diffId.setId(ID_2); BratEntity diffType = new BratEntity(base); diffType.setType(TYPE_2); BratEntity diffSpan = new BratEntity(base); diffSpan.addSpan(SPAN_3); BratEntity diffText = new BratEntity(base); diffText.setText(TEXT_2); new EqualsTester() .addEqualityGroup(base, baseCopy) .addEqualityGroup(diffId) .addEqualityGroup(diffType) .addEqualityGroup(diffSpan) .addEqualityGroup(diffText) .testEquals(); } @Test public void testAllFields() { assertEquals(ID, base.getId()); assertEquals(TEXT, base.getText()); assertEquals(TYPE, base.getType()); assertEquals(SPAN_1.lowerEndpoint().intValue(), base.beginPosition()); assertEquals(SPAN_2.upperEndpoint().intValue(), base.endPosition()); RangeSet<Integer> actual = TreeRangeSet.create(); actual.add(SPAN_1); actual.add(SPAN_2); assertEquals(actual, base.getSpans()); assertEquals(actual.span(), base.totalSpan()); } @Test public void testParseEntity() { assertEquals(base, BratEntity.parseEntity(LINE)); } @Test public void testAddSpan() { Range<Integer> span = Range.closed(23, 30); thrown.expect(IllegalArgumentException.class); base.addSpan(span); span = Range.openClosed(23, 30); thrown.expect(IllegalArgumentException.class); base.addSpan(span); } @Test public void testSetId() { thrown.expect(NullPointerException.class); base.setId(null); thrown.expect(IllegalArgumentException.class); base.setId("E21"); } @Test public void testShift() { BratEntity entity = BratEntity.shift(base, 2); Range<Integer> range = entity.totalSpan(); assertEquals(50, range.lowerEndpoint().intValue()); assertEquals(59, range.upperEndpoint().intValue()); } @Test public void testToBratString() { assertEquals(LINE, base.toBratString()); } }
27.008065
74
0.702896
93770cef086a422793b846e504a7423032b316f5
487
package com.chat.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Bean public BCryptPasswordEncoder bcpe(){ return new BCryptPasswordEncoder(); } }
28.647059
75
0.788501
75947d027f92370726b21292a40776a7200fcc6e
801
package statisticsCalculator; import dbmanagement.Database; import domain.Comment; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by Jorge on 28/03/2017. */ @Service public class CommentsProcessor{ @Autowired private Database dat; @Autowired private ProposalsProcessor propPorc; private Long amount; @Autowired public CommentsProcessor( Database dat, ProposalsProcessor propPorc){ this.dat=dat; amount=dat.countComments(); this.propPorc=propPorc; } public Long getAmount() { return amount; } public void updateCreate(String data){ amount++; propPorc.updateTopCommented(); } public void updateVote(String data){} }
20.538462
73
0.697878
74a2c4708a594ee79808ffe3a8f0cafd4ccef0f7
315
package chav1961.merc.api.interfaces.front; /** * <p>This enumeration describes resource types available for the world.</p> * @see Mercury landing project * @author Alexander Chernomyrdin aka chav1961 * @since 0.0.1 */ @MerLan public enum ResourceClass { None, Liquid, Solid, Electricity }
19.6875
77
0.701587
3e94c4a2213693033bee6b1b2ef99d2e4398dda0
51
package com.github.houbb.sandglass.test.springboot;
51
51
0.862745
0a076272c8026ca057b13ca7153719ef086d09fb
1,415
/* * Copyright 2021 Patrik Karlström. * * 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.mapton.addon.photos.ui; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import org.mapton.addon.photos.api.MapoSource; import se.trixon.almond.nbp.fx.FxDialogPanel; /** * * @author Patrik Karlström */ public class SourcePanel extends FxDialogPanel { private BorderPane mRoot; private SourceView mSourceView; public SourcePanel() { } public void load(MapoSource source) { mSourceView.load(source); } public void save(MapoSource source) { mSourceView.save(source); } @Override protected void fxConstructor() { setScene(createScene()); mRoot.setCenter(mSourceView = new SourceView(mNotifyDescriptor)); } private Scene createScene() { return new Scene(mRoot = new BorderPane()); } }
26.203704
75
0.706714
c6405849e1e812f1f1d3929b305b22f7ad7c6180
33,385
package net.kurobako.gesturefx; import java.util.Objects; import java.util.Optional; import java.util.function.DoubleConsumer; import javafx.animation.Interpolator; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.DefaultProperty; import javafx.beans.binding.DoubleBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.WritableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.geometry.BoundingBox; import javafx.geometry.Bounds; import javafx.geometry.Dimension2D; import javafx.geometry.Point2D; import javafx.scene.AccessibleAttribute; import javafx.scene.AccessibleRole; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Control; import javafx.scene.control.ScrollBar; import javafx.scene.control.Skin; import javafx.scene.layout.Region; import javafx.scene.transform.Affine; import javafx.scene.transform.NonInvertibleTransformException; import javafx.util.Duration; import static net.kurobako.gesturefx.GesturePane.FitMode.FIT; import static net.kurobako.gesturefx.GesturePane.FitMode.UNBOUNDED; import static net.kurobako.gesturefx.GesturePane.ScrollBarPolicy.AS_NEEDED; import static net.kurobako.gesturefx.GesturePane.ScrollMode.PAN; /** * Pane that applies transformations to some implementation of {@link Transformable} when a * gesture is applied * <p> * Terms: * <ol> * <li>Target - the actual object that receives transformation</li> * <li>Viewport - the view area of the target(not counting vertical and horizontal scrollbars)</li> * </ol> * <p> * The measured size of the node defaults the the target's size, you can use the usual * {@link Region#setPrefSize(double, double)} and related methods/bindings to * provide alternative dimensions. * To listen for transformation changes, register event listeners for {@link AffineEvent}, for * example: * <pre> * {@code * GesturePane pane = //... * pane.addEventHandler(AffineEvent.CHANGED, e ->{ ... }); * } * </pre> * See documentation for the {@link AffineEvent} for more information on the methods provided in * the event */ @SuppressWarnings({"unused", "WeakerAccess"}) @DefaultProperty("content") public class GesturePane extends Control implements GesturePaneOps { private static final BoundingBox ZERO_BOX = new BoundingBox(0, 0, 0, 0); private static final String DEFAULT_STYLE_CLASS = "gesture-pane"; public static final double DEFAULT_MIN_SCALE = 0.5f; public static final double DEFAULT_MAX_SCALE = 10f; public static final double DEFAULT_ZOOM_FACTOR = 1f; final Affine affine = new Affine(); private boolean inhibitPropEvent = false; private boolean clampExternalScale = true; // XXX in general, these should be written like the JDK counterpart(lazy instantiation of // properties), but, life is too short for these kind of things. If I feel like it, I would // rewrite this entire library in Scala (thus, properties can all be `lazy val` and what not) // exposed properties final BooleanProperty fitWidth = new SimpleBooleanProperty(true); final BooleanProperty fitHeight = new SimpleBooleanProperty(true); final ObjectProperty<ScrollBarPolicy> vbarPolicy = new SimpleObjectProperty<>(AS_NEEDED); final ObjectProperty<ScrollBarPolicy> hbarPolicy = new SimpleObjectProperty<>(AS_NEEDED); final BooleanProperty gestureEnabled = new SimpleBooleanProperty(true); final BooleanProperty clipEnabled = new SimpleBooleanProperty(true); final BooleanProperty changing = new SimpleBooleanProperty(false); final ObjectProperty<ScrollMode> scrollMode = new SimpleObjectProperty<>(PAN); final ObjectProperty<FitMode> fitMode = new SimpleObjectProperty<>(FIT); final BooleanProperty invertScrollTranslate = new SimpleBooleanProperty(false); final DoubleProperty scaleX = new SimpleDoubleProperty(1); final DoubleProperty scaleY = new SimpleDoubleProperty(1); final DoubleProperty scrollZoomFactor = new SimpleDoubleProperty(DEFAULT_ZOOM_FACTOR); final BooleanProperty lockScaleX = new SimpleBooleanProperty(false); final BooleanProperty lockScaleY = new SimpleBooleanProperty(false); final BooleanProperty bindScale = new SimpleBooleanProperty(false); private final DoubleProperty minScale = new SimpleDoubleProperty(DEFAULT_MIN_SCALE); private final DoubleProperty maxScale = new SimpleDoubleProperty(DEFAULT_MAX_SCALE); final ObjectProperty<Transformable> target = new SimpleObjectProperty<>(); final ObjectProperty<Node> content = new SimpleObjectProperty<>(); final ObjectProperty<Bounds> targetRect = new SimpleObjectProperty<>(ZERO_BOX); // internal properties final DoubleProperty targetWidth = new SimpleDoubleProperty(); final DoubleProperty targetHeight = new SimpleDoubleProperty(); final ObjectProperty<Bounds> viewport = new SimpleObjectProperty<>(ZERO_BOX); /** * Create a new {@link GesturePane} with the specified {@link Transformable} * * @param target the transformable to apply the transforms to */ public GesturePane(Transformable target) { this(); setTarget(target); } /** * Creates a new {@link GesturePane} with the specified node as children(i.e the node gets * added to the pane) * * @param target the node to apply transforms to */ public GesturePane(Node target) { this(); setContent(target); } public GesturePane() { super(); // can't use bindBidirectional here because we need to clamp // scale -> mxx,myy but not the other way around affine.mxxProperty().addListener(o -> scaleX.set(affine.getMxx())); affine.myyProperty().addListener(o -> scaleY.set(affine.getMyy())); scaleX.addListener(e -> { if (clampExternalScale) clampAtBound(true); affine.setMxx(scaleX.get()); if (!inhibitPropEvent) fireAffineEvent(AffineEvent.CHANGED); boolean bind = bindScale.get(); if(bind) { scaleY.set(scaleX.get()); } }); scaleY.addListener(e -> { if (clampExternalScale) clampAtBound(true); affine.setMyy(scaleY.get()); if (!inhibitPropEvent) fireAffineEvent(AffineEvent.CHANGED); }); getStyleClass().setAll(DEFAULT_STYLE_CLASS); setAccessibleRole(AccessibleRole.SCROLL_PANE); target.addListener((o, p, n) -> { if (n == null) return; runLaterOrNowIfOnFXThread(() -> { content.set(null); getChildren().removeIf(x -> !(x instanceof ScrollBar)); n.setTransform(affine); targetWidth.set(n.width()); targetHeight.set(n.height()); }); }); final ChangeListener<Bounds> layoutBoundsListener = (o, p, n) -> { targetWidth.set(n.getWidth()); targetHeight.set(n.getHeight()); }; content.addListener((o, p, n) -> { if (p != null){ runLaterOrNowIfOnFXThread(() -> { p.layoutBoundsProperty().removeListener(layoutBoundsListener); getChildren().remove(p); }); } if (n == null) return; target.set(null); if(n instanceof Parent){ ((Parent) n).layout(); } n.applyCss(); runLaterOrNowIfOnFXThread(() -> { getChildren().add(0, n); n.getTransforms().add(affine); n.layoutBoundsProperty().addListener(layoutBoundsListener); targetWidth.set(n.getLayoutBounds().getWidth()); targetHeight.set(n.getLayoutBounds().getHeight()); }); }); } private static void runLaterOrNowIfOnFXThread(Runnable r) { if (Platform.isFxApplicationThread()) r.run(); else Platform.runLater(r); } @Override protected Skin<?> createDefaultSkin() { return new GesturePaneSkin(this); } // apparently, performance is an issue here, see // https://bitbucket.org/controlsfx/controlsfx/pull-requests/519/this-is-the-fix-for-https // -javafx/diff private String stylesheet; @Override public String getUserAgentStylesheet() { if (stylesheet == null) stylesheet = GesturePane.class.getResource("gesturepane.css").toExternalForm(); return stylesheet; } /** * Centre of the current viewport. * <br> * This equivalent to : * <pre> * {@code new Point2D(getViewportWidth()/2, getViewportHeight()/2) }) * </pre> * * @return a new point located at the centre of the viewport */ public Point2D viewportCentre() { return new Point2D(getViewportWidth() / 2, getViewportHeight() / 2); } /** * The point on the target at which the current centre point of the viewport is. * * @return a point on the target using target's coordinate system */ public Point2D targetPointAtViewportCentre() { try { return affine.inverseTransform(viewportCentre()); } catch (NonInvertibleTransformException e) { // TODO what can be done? throw new RuntimeException(e); } } /** * Computes the point on the target at the given viewport point. * * @param viewportPoint a point on the viewport * @return a point on the target that corresponds to the viewport point or empty if the point * is not within the the bound returned by {@link #getViewportBound()} */ public Optional<Point2D> targetPointAt(Point2D viewportPoint) { if (!getViewportBound().contains(viewportPoint)) return Optional.empty(); try { return Optional.of(affine.inverseTransform(viewportPoint)); } catch (NonInvertibleTransformException e) { // TODO does this ever happen with just translate and scale? return Optional.empty(); } } /** * Computes the point on the viewport at the given target point. * * @param targetPoint a point on the target * @return a point on the viewport that corresponds to the target point */ public Point2D viewportPointAt(Point2D targetPoint) { return affine.transform(targetPoint); } @Override public void translateBy(Dimension2D targetAmount) { fireAffineEvent(AffineEvent.CHANGE_STARTED); atomicallyChange(() -> { // target coordinate, so append; origin is top left so we we flip signs affine.appendTranslation(-targetAmount.getWidth(), -targetAmount.getHeight()); clampAtBound(true); }); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void centreOn(Point2D pointOnTarget) { // move to centre point and apply scale Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } @Override public void centreOnX(double pointOnTarget) { // move to centre point and apply scale double delta = pointOnTarget - targetPointAtViewportCentre().getX(); translateBy(new Dimension2D(delta, 0)); } @Override public void centreOnY(double pointOnTarget) { // move to centre point and apply scale double delta = pointOnTarget - targetPointAtViewportCentre().getY(); translateBy(new Dimension2D(0, delta)); } @Override public void zoomTo(double scaleX,double scaleY, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale(scaleX / getCurrentScaleX(),scaleY / getCurrentScaleY(), viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void zoomToX(double scaleX, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale(scaleX / getCurrentScaleX(),1, viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void zoomToY(double scaleY, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale(1,scaleY / getCurrentScaleY(), viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void zoomBy(double amountX,double amountY, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale( (amountX + getCurrentScaleX()) / getCurrentScaleX(), (amountY + getCurrentScaleY()) / getCurrentScaleY(), viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void zoomByX(double amountX, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale((amountX + getCurrentScaleX()) / getCurrentScaleX(), 1, viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } @Override public void zoomByY(double amountY, Point2D pivotOnTarget) { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale(1, (amountY + getCurrentScaleY()) / getCurrentScaleY(), viewportPointAt(pivotOnTarget)); fireAffineEvent(AffineEvent.CHANGE_FINISHED); } /** * Animate changes for all operations supported in {@link GesturePaneOps}. * <br> * Animations does not compose so starting an new animation while one is already running will * result in the first animation being stopped arbitrary for the second animation to start. * <br> * The method returns a type-safe builder that will limit access to only the available builder * methods, for example: * <pre> * {@code * animate(Duration.millis(300)) * .interpolateWith(Interpolator.EASE_IN) * .afterFinished(() -> System.out.println("Done!")) * .zoomTo(2f); * } * </pre> * * @param duration the duration of the animation; must not be null * @return a type-safe builder that will allow various options to be set */ public AnimationInterpolatorBuilder animate(Duration duration) { Objects.requireNonNull(duration); // keep the builder to one object instantiation return new AnimationInterpolatorBuilder() { private Runnable afterFinished; private Runnable beforeStart; private Interpolator interpolator; @Override public AnimationStartBuilder interpolateWith(Interpolator interpolator) { this.interpolator = Objects.requireNonNull(interpolator); return this; } @Override public AnimationEndBuilder beforeStart(Runnable action) { this.beforeStart = Objects.requireNonNull(action); return this; } @Override public GesturePaneOps afterFinished(Runnable action) { this.afterFinished = Objects.requireNonNull(action); return this; } @Override public void centreOn(Point2D pointOnTarget) { // find the delta between current centre and the point and then animate the delta Point2D delta = pointOnTarget.subtract(targetPointAtViewportCentre()); translateBy(new Dimension2D(delta.getX(), delta.getY())); } @Override public void centreOnX(double pointOnTarget) { // move to centre point and apply scale double delta = pointOnTarget - targetPointAtViewportCentre().getX(); translateBy(new Dimension2D(delta, 0)); } @Override public void centreOnY(double pointOnTarget) { // move to centre point and apply scale double delta = pointOnTarget - targetPointAtViewportCentre().getY(); translateBy(new Dimension2D(0, delta)); } private void markStart() { changing.set(true); if (beforeStart != null) beforeStart.run(); fireAffineEvent(AffineEvent.CHANGE_STARTED); inhibitPropEvent = true; clampExternalScale = false; } private void markEnd() { inhibitPropEvent = false; clampExternalScale = true; fireAffineEvent(AffineEvent.CHANGE_FINISHED); if (afterFinished != null) afterFinished.run(); changing.set(false); } @Override public void translateBy(Dimension2D targetAmount) { // target coordinate so we will be setting tx and ty manually(append) so manually // scale the target amount first double vx = -targetAmount.getWidth() * getCurrentScaleX(); double vy = -targetAmount.getHeight() * getCurrentScaleY(); double tx = affine.getTx(); // fixed point double ty = affine.getTy(); // fixed point markStart(); animateValue(duration, interpolator, v -> { affine.setTx(tx + vx * v); affine.setTy(ty + vy * v); clampAtBound(true); }, e -> markEnd()); } @Override public void zoomTo(double targetScaleX,double targetScaleY, Point2D pivotOnTarget) { double initialScaleX = scaleX.get(); // fixed point double initialScaleY = scaleY.get(); // fixed point double dsX = clamp(getMinScale(), getMaxScale(), targetScaleX) - initialScaleX; // delta double dsY = clamp(getMinScale(), getMaxScale(), targetScaleY) - initialScaleY; // delta Point2D pv = viewportPointAt(pivotOnTarget); markStart(); animateValue(duration, interpolator, v -> { // so, prependScale with pivot is: // prependTranslate->prependScale->prependTranslate // 1. prependTranslate affine.setTx(affine.getTx() - pv.getX()); affine.setTy(affine.getTy() - pv.getY()); // 2. prependScale, but extract the coefficient to scale the translation first double dssX = initialScaleX + dsX * v; double dssY = initialScaleY + dsY * v; double currentScaleX = scaleX.get(); double currentScaleY = scaleY.get(); affine.setTx(affine.getTx() * (dssX / currentScaleX)); affine.setTy(affine.getTy() * (dssY / currentScaleY)); scaleX.set(dssX); scaleY.set(dssY); // 3. prependTranslate affine.setTx(affine.getTx() + pv.getX()); affine.setTy(affine.getTy() + pv.getY()); clampAtBound(false); fireAffineEvent(AffineEvent.CHANGED); }, e -> markEnd()); } @Override public void zoomToX(double scaleX, Point2D pivotOnTarget) { zoomTo(scaleX, scaleY.get(), pivotOnTarget); } @Override public void zoomToY(double scaleY, Point2D pivotOnTarget) { zoomTo(scaleX.get(), scaleY, pivotOnTarget); } @Override public void zoomBy(double scaleX, double scaleY, Point2D pivotOnTarget) { zoomTo(getCurrentScaleX() + scaleX, getCurrentScaleY() + scaleY, pivotOnTarget); } @Override public void zoomByX(double scaleX, Point2D pivotOnTarget) { zoomTo(getCurrentScaleX() + scaleX, getCurrentScaleY(), pivotOnTarget); } @Override public void zoomByY(double scaleY, Point2D pivotOnTarget) { zoomTo(getCurrentScaleX(), getCurrentScaleY() + scaleY, pivotOnTarget); } }; } public interface AnimationInterpolatorBuilder extends AnimationStartBuilder { /** * @param interpolator the interpolator to use for the animation * @return the next group of configurable options in a type-safe builder */ AnimationStartBuilder interpolateWith(Interpolator interpolator); } public interface AnimationStartBuilder extends AnimationEndBuilder { /** * @param action the action to execute <b>before</b> the animation starts * @return the next group of configurable options in a type-safe builder */ AnimationEndBuilder beforeStart(Runnable action); } public interface AnimationEndBuilder extends GesturePaneOps { /** * @param action the action to execute <b>after</b> the animation finishes * @return the next group of configurable options in a type-safe builder */ GesturePaneOps afterFinished(Runnable action); } /** * Resets zoom to minimum scale */ public final void reset() { zoomTo(getMinScale(), targetPointAtViewportCentre()); } /** * Resets zoom to the minimum scale and conditionally centres the image depending on the * current * {@link FitMode} */ public void cover() { fireAffineEvent(AffineEvent.CHANGE_STARTED); scale(getMinScale() / getCurrentScaleX(),getMinScale() / getCurrentScaleY(), viewportPointAt(targetPointAtViewportCentre())); if (fitMode.get() == FitMode.COVER) { double width = getViewportWidth(); double height = getViewportHeight(); double scale = getCurrentScaleX(); affine.setTy((height - scale * getTargetHeight()) / 2); if (height >= scale * getTargetHeight()) affine.setTx((width - scale * getTargetWidth()) / 2); } fireAffineEvent(AffineEvent.CHANGE_FINISHED); } final void scale(double factor, Point2D origin) { scale(factor, factor, origin); } final void scale(double factorX, double factorY, Point2D origin) { atomicallyChange(() -> { double deltaX = factorX; double deltaY = factorY; if (lockScaleX.get()) deltaX = 1; if (lockScaleY.get()) deltaY = 1; double scaleX = getCurrentScaleX() * factorX; double scaleY = getCurrentScaleY() * factorY; // clamp at min and max if (scaleX > getMaxScale()) deltaX = getMaxScale() / getCurrentScaleX(); if (scaleX < getMinScale()) deltaX = getMinScale() / getCurrentScaleX(); if (scaleY > getMaxScale()) deltaY = getMaxScale() / getCurrentScaleY(); if (scaleY < getMinScale()) deltaY = getMinScale() / getCurrentScaleY(); affine.prependScale(deltaX, 1, origin); affine.prependScale(1, deltaY, origin); clampAtBound(factorX >= 1 || factorY >= 1); }); } final void translate(double x, double y) { atomicallyChange(() -> { affine.prependTranslation(x, y); clampAtBound(true); }); } private static double clamp(double min, double max, double value) { return Math.max(min, Math.min(max, value)); } final void clampAtBound(boolean zoomPositive) { double scaleX = getCurrentScaleX(); double scaleY = getCurrentScaleY(); double targetWidth = getTargetWidth(); double targetHeight = getTargetHeight(); double scaledWidth = scaleX * targetWidth; double scaledHeight = scaleY * targetHeight; double width = getViewportWidth(); double height = getViewportHeight(); // clamp translation double minX = width - scaledWidth; double minY = height - scaledHeight; double tx = affine.getTx(); double ty = affine.getTy(); double tsX = scaleX; double tsY = scaleY; if (fitMode.get() != UNBOUNDED) { tx = clamp(minX, 0, tx); ty = clamp(minY, 0, ty); if (width >= scaledWidth) tx = (width - scaleX * targetWidth) / 2; if (height >= scaledHeight) ty = (height - scaleY * targetHeight) / 2; } // clamp scale switch (fitMode.get()) { case COVER: if (width < scaledWidth && height < scaledHeight) break; tsX = tsY = targetWidth <= 0 || targetHeight <= 0 ? 1 : Math.max(width / targetWidth, height / targetHeight); break; case FIT: double fitScale = (targetWidth <= 0 || targetHeight <= 0) ? 0 : Math.min(width / targetWidth, height / targetHeight); if (zoomPositive || scaleX > fitScale) break; tx = (width - fitScale * targetWidth) / 2; ty = (height - fitScale * targetHeight) / 2; tsX = tsY = fitScale; break; default: break; } // to prevent excessive affine events as we don't have access to the atomic change field affine.setTx(tx); affine.setTy(ty); this.scaleX.set(tsX); this.scaleY.set(tsY); } private final Timeline timeline = new Timeline(); private void animateValue(Duration duration, Interpolator interpolator, DoubleConsumer consumer, EventHandler<ActionEvent> l) { timeline.stop(); timeline.getKeyFrames().clear(); KeyValue keyValue = new KeyValue(new WritableValue<Double>() { @Override public Double getValue() { return 0.0; } @Override public void setValue(Double value) { consumer.accept(value); } }, 1.0, interpolator == null ? Interpolator.LINEAR : interpolator); timeline.getKeyFrames().add(new KeyFrame(duration, keyValue)); timeline.setOnFinished(l); timeline.play(); } private void atomicallyChange(Runnable e) { inhibitPropEvent = true; e.run(); inhibitPropEvent = false; fireAffineEvent(AffineEvent.CHANGED); } Affine lastAffine = null; final void fireAffineEvent(EventType<AffineEvent> type) { if (type == AffineEvent.CHANGED && lastAffine != null && affine.similarTo(lastAffine, getViewportBound(), 0.001)) return; Dimension2D dimension = new Dimension2D(getTargetWidth(), getTargetHeight()); Affine snapshot = getAffine(); fireEvent(new AffineEvent(type, snapshot, lastAffine, dimension)); lastAffine = snapshot; } /** * @return the current target/content node's width if set; 0 if unset. */ public double getTargetWidth() { if (target.get() != null) return target.get().width(); else if (content.get() != null) return content.get().getLayoutBounds().getWidth(); else return 0; } /** * @return the current target/content node's height if set; 0 if unset. */ public double getTargetHeight() { if (target.get() != null) return target.get().height(); else if (content.get() != null) return content.get().getLayoutBounds().getHeight(); else return 0; } public double getViewportWidth() { return viewport.get().getWidth(); } public double getViewportHeight() { return viewport.get().getHeight(); } public Bounds getViewportBound() { return viewport.get(); } public ReadOnlyObjectProperty<Bounds> viewportBoundProperty() { return viewport; } /** * @return the current target if set; null if unset. * <b>NOTE</b>: Targets and content nodes are mutually exclusive, if one is set, the other one * is automatically set to null */ public Transformable getTarget() { return target.get(); } public ObjectProperty<Transformable> targetProperty() { return target; } public void setTarget(Transformable target) { this.target.set(target); } /** * @return the current content node if set; null if unset * <b>NOTE</b>: Targets and content nodes are mutually exclusive, if one is set, the other one * is automatically set to null */ public Node getContent() { return content.get(); } public ObjectProperty<Node> contentProperty() { return content; } public void setContent(Node content) { this.content.set(content); } /** * @return which scrollbar policy the vertical scrollbar uses */ public ScrollBarPolicy getVbarPolicy() { return vbarPolicy.get(); } public ObjectProperty<ScrollBarPolicy> vbarPolicyProperty() { return vbarPolicy; } public void setVbarPolicy(ScrollBarPolicy policy) { this.vbarPolicy.set(policy); } /** * @return which scrollbar policy the horizontal scrollbar uses */ public ScrollBarPolicy getHbarPolicy() { return hbarPolicy.get(); } public ObjectProperty<ScrollBarPolicy> hbarPolicyProperty() { return hbarPolicy; } public void setHbarPolicy(ScrollBarPolicy policy) { this.hbarPolicy.set(policy); } /** * Sets the same scrollbar policy for both vbar and hbar * @param policy the policy to use */ public void setScrollBarPolicy(ScrollBarPolicy policy) { setHbarPolicy(policy); setVbarPolicy(policy); } /** * @return whether there is an on-going animation or gesture */ public boolean isChanging() { return changing.get(); } public ReadOnlyBooleanProperty changingProperty() { return changing; } /** * @return whether gesture inputs are enabled; this only affects inputs and does not lock the * affine transform itself */ public boolean isGestureEnabled() { return gestureEnabled.get(); } public BooleanProperty gestureEnabledProperty() { return gestureEnabled; } public void setGestureEnabled(boolean enable) { this.gestureEnabled.set(enable); } /** * @return whether the content node (if set) will be clipped with {@link Node#setClip(Node)} * using a viewport-sized rectangle */ public boolean isClipEnabled() { return clipEnabled.get(); } public BooleanProperty clipEnabledProperty() { return clipEnabled; } public void setClipEnabled(boolean enable) { this.clipEnabled.set(enable); } public boolean isFitWidth() { return fitWidth.get(); } public BooleanProperty fitWidthProperty() { return fitWidth; } public void setFitWidth(boolean fitWidth) { this.fitWidth.set(fitWidth); } public boolean isFitHeight() { return fitHeight.get(); } public BooleanProperty fitHeightProperty() { return fitHeight; } public void setFitHeight(boolean fitHeight) { this.fitHeight.set(fitHeight); } /** * @return the current {@link FitMode} */ public FitMode getFitMode() { return fitMode.get(); } public ObjectProperty<FitMode> fitModeProperty() { return fitMode; } public void setFitMode(FitMode mode) { this.fitMode.set(mode); } /** * @return the current {@link ScrollMode} */ public ScrollMode getScrollMode() { return scrollMode.get(); } public ObjectProperty<ScrollMode> scrollModeProperty() { return scrollMode; } public void setScrollMode(ScrollMode mode) { this.scrollMode.set(mode); } public boolean isInvertScrollTranslate() { return invertScrollTranslate.get(); } public BooleanProperty invertScrollTranslateProperty() { return invertScrollTranslate; } public void setInvertScrollTranslate(boolean invertScrollTranslate) { this.invertScrollTranslate.set(invertScrollTranslate); } public boolean isLockScaleX() { return lockScaleX.get(); } public BooleanProperty lockScaleXProperty() { return lockScaleX; } public void setLockScaleX(boolean lockScaleX) { this.lockScaleX.set(lockScaleX); } public boolean isLockScaleY() { return lockScaleY.get(); } public BooleanProperty lockScaleYProperty() { return lockScaleY; } public void setLockScaleY(boolean lockScaleY) { this.lockScaleY.set(lockScaleY); } /** * @return the current x axis scale (x == y iff bindScale is true); defaults to 1.0 initially unless the selected {@link FitMode} * disallows this */ public double getCurrentScale() { return scaleX.get(); } public DoubleProperty currentScaleProperty() { return scaleX; } public boolean isBindScale() { return bindScale.get(); } public BooleanProperty bindScaleProperty() { return bindScale; } public void setBindScale(boolean bindScale) { this.bindScale.set(bindScale); } /** * @return the current minimum scale; defaults to {@link GesturePane#DEFAULT_MIN_SCALE} */ public double getMinScale() { return minScale.get(); } public DoubleProperty minScaleProperty() { return minScale; } public void setMinScale(double scale) { this.minScale.set(scale); } /** * @return the current maximum scale; defaults to {@link GesturePane#DEFAULT_MAX_SCALE} */ public double getMaxScale() { return maxScale.get(); } public DoubleProperty maxScaleProperty() { return maxScale; } public void setMaxScale(double scale) { this.maxScale.set(scale); } /** * @return the current x axis scale; defaults to 1.0 initially unless the selected {@link FitMode} * disallows this */ public double getCurrentScaleX() { return scaleX.get(); } public DoubleProperty currentScaleXProperty() { return scaleX; } /** * @return the current y axis scale; defaults to 1.0 initially unless the selected {@link FitMode} * disallows this */ public double getCurrentScaleY() { return scaleY.get(); } public DoubleProperty currentScaleYProperty() { return scaleY; } /** * @return the current x axis offset in <b>target coordinates</b>, see * {@link GesturePane#getTargetViewport()} */ public double getCurrentX() { return affine.getTx() / getCurrentScaleX(); } public DoubleBinding currentXProperty() { return affine.txProperty().divide(scaleX); } /** * @return the current y axis offset in <b>target coordinates</b>, see * {@link GesturePane#getTargetViewport()} */ public double getCurrentY() { return affine.getTy() / getCurrentScaleY(); } public DoubleBinding currentYProperty() { return affine.tyProperty().divide(scaleY); } /** * @return the scroll zoom factor controlling the constant factor of how much each scroll * event affects the transformation; defaults to 1 */ public double getScrollZoomFactor() { return scrollZoomFactor.get(); } public DoubleProperty scrollZoomFactorProperty() { return scrollZoomFactor; } public void setScrollZoomFactor(double factor) { this.scrollZoomFactor.set(factor); } /** * @return the viewport bounding box in <b>target coordinates</b> */ public Bounds getTargetViewport() { return targetRect.get(); } public ObjectProperty<Bounds> targetViewportProperty() { return targetRect; } /** * @return a <b>copy</b> of the current affine transformation */ public Affine getAffine() { return new Affine(affine); } @Override public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) { if (attribute == AccessibleAttribute.CONTENTS) return getContent(); return super.queryAccessibleAttribute(attribute, parameters); } /** * Modes for different minimum scales */ public enum FitMode { /** * Node will be scaled to cover the entire pane */ COVER, /** * Node will be scaled such that any of the edge touches the pane */ FIT, /** * Node will not be scaled but constrained to the center of the viewport */ CENTER, /** * Node will not be scaled nor constrained; this also disables both vertical and * horizontal scrollbar if enabled */ UNBOUNDED } /** * Modes for interpreting scroll events */ public enum ScrollMode { /** * Treat scroll as zoom */ ZOOM, /** * Treat scroll as pan */ PAN } public enum ScrollBarPolicy { /** * No scrollbar */ NEVER, /** * Always enable scrollbar */ ALWAYS, /** * Show scrollbar when viewport is panning */ AS_NEEDED; } /** * A target that can be transformed */ public interface Transformable { /** * @return the target width, must not be negative */ double width(); /** * @return the target height, must not be negative */ double height(); /** * Sets the transformation for the target, will only happen once * * @param affine the transformation; never null */ default void setTransform(Affine affine) {} } }
33.96236
130
0.725805
f75d905167b2b4152e8980a011ef2da04763e441
2,433
package uk.gov.hmcts.reform.civil.assertion; import org.assertj.core.api.AbstractAssert; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class DayAssert extends AbstractAssert<DayAssert, LocalDate> { public DayAssert(LocalDate actual) { super(actual, DayAssert.class); } public static DayAssert assertThat(LocalDate actual) { return new DayAssert(actual); } public static DayAssert assertThat(LocalDateTime actual) { return new DayAssert(actual.toLocalDate()); } public DayAssert isWeekday() { DayOfWeek day = actual.getDayOfWeek(); if (day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) { failWithMessage("Expected weekday but was <%s>", actual.getDayOfWeek()); } return this; } public DayAssert isMonday() { return isDay(DayOfWeek.MONDAY); } public DayAssert isTuesday() { return isDay(DayOfWeek.TUESDAY); } public DayAssert isWednesday() { return isDay(DayOfWeek.WEDNESDAY); } public DayAssert isThursday() { return isDay(DayOfWeek.THURSDAY); } public DayAssert isFriday() { return isDay(DayOfWeek.FRIDAY); } private DayAssert isDay(DayOfWeek expectedDay) { isNotNull(); if (actual.getDayOfWeek() != expectedDay) { failWithMessage("Expected <%s> but was <%s>", expectedDay, actual.getDayOfWeek()); } return this; } public DayAssert isTheSame(LocalDate date) { isNotNull(); if (!actual.isEqual(date)) { failWithMessage("Expected <%s> but was <%s>", date.toString(), actual.toString()); } return this; } public DayAssert isTheSame(LocalDateTime date) { return isTheSame(date.toLocalDate()); } public DayAssert isNumberOfDaysSince(int expectedDiff, LocalDate issuedOn) { isNotNull(); long actuallyDaysBetween = ChronoUnit.DAYS.between(issuedOn, actual); if (actuallyDaysBetween != expectedDiff) { failWithMessage("Expected <%d> but was <%d>", expectedDiff, actuallyDaysBetween); } return this; } public DayAssert isNumberOfDaysSince(int expectedDiff, LocalDateTime issuedOn) { return isNumberOfDaysSince(expectedDiff, issuedOn.toLocalDate()); } }
27.033333
94
0.650226
4433e53127e106d6a9abc9d4bf303bcf59f5c548
290
package dev.patika.schoolmanagementsystem.dataaccess; import dev.patika.schoolmanagementsystem.entities.PermanentInstructor; import org.springframework.stereotype.Repository; @Repository public interface PermanentInstructorRepository extends InstructorRepository<PermanentInstructor> { }
32.222222
98
0.882759
e36d81a47303bf976b1724faf81ba128ec4dc1c4
8,893
/* * Copyright 2014-2021 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.samples; import io.aeron.LogBuffers; import io.aeron.logbuffer.FrameDescriptor; import io.aeron.logbuffer.LogBufferDescriptor; import io.aeron.protocol.DataHeaderFlyweight; import org.agrona.BitUtil; import org.agrona.DirectBuffer; import org.agrona.concurrent.UnsafeBuffer; import java.io.PrintStream; import java.util.Date; import static io.aeron.logbuffer.LogBufferDescriptor.*; import static io.aeron.protocol.DataHeaderFlyweight.HEADER_LENGTH; import static java.lang.Math.min; /** * Command line utility for inspecting a log buffer to see what terms and messages it contains. */ public class LogInspector { /** * Data format for fragments which can be ASCII or HEX. */ public static final String AERON_LOG_DATA_FORMAT_PROP_NAME = "aeron.log.inspector.data.format"; public static final String AERON_LOG_DATA_FORMAT = System.getProperty( AERON_LOG_DATA_FORMAT_PROP_NAME, "hex").toLowerCase(); /** * Should the default header be skipped for output. */ public static final String AERON_LOG_SKIP_DEFAULT_HEADER_PROP_NAME = "aeron.log.inspector.skipDefaultHeader"; public static final boolean AERON_LOG_SKIP_DEFAULT_HEADER = Boolean.getBoolean( AERON_LOG_SKIP_DEFAULT_HEADER_PROP_NAME); /** * Should zeros be skipped in the output to reduce noise. */ public static final String AERON_LOG_SCAN_OVER_ZEROES_PROP_NAME = "aeron.log.inspector.scanOverZeroes"; public static final boolean AERON_LOG_SCAN_OVER_ZEROES = Boolean.getBoolean(AERON_LOG_SCAN_OVER_ZEROES_PROP_NAME); private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** * Main method for launching the process. * * @param args passed to the process. */ public static void main(final String[] args) { final PrintStream out = System.out; if (args.length < 1) { out.println("Usage: LogInspector <logFileName> [dump limit in bytes per message]"); return; } final String logFileName = args[0]; final int messageDumpLimit = args.length >= 2 ? Integer.parseInt(args[1]) : Integer.MAX_VALUE; try (LogBuffers logBuffers = new LogBuffers(logFileName)) { out.println("======================================================================"); out.format("%s Inspection dump for %s%n", new Date(), logFileName); out.println("======================================================================"); final DataHeaderFlyweight dataHeaderFlyweight = new DataHeaderFlyweight(); final UnsafeBuffer[] termBuffers = logBuffers.duplicateTermBuffers(); final int termLength = logBuffers.termLength(); final UnsafeBuffer metaDataBuffer = logBuffers.metaDataBuffer(); final int initialTermId = initialTermId(metaDataBuffer); out.format(" Is Connected: %s%n", isConnected(metaDataBuffer)); out.format("Initial term id: %d%n", initialTermId); out.format(" Term Count: %d%n", activeTermCount(metaDataBuffer)); out.format(" Active index: %d%n", indexByTermCount(activeTermCount(metaDataBuffer))); out.format(" Term length: %d%n", termLength); out.format(" MTU length: %d%n", mtuLength(metaDataBuffer)); out.format(" Page Size: %d%n", pageSize(metaDataBuffer)); out.format(" EOS Position: %d%n%n", endOfStreamPosition(metaDataBuffer)); if (!AERON_LOG_SKIP_DEFAULT_HEADER) { dataHeaderFlyweight.wrap(defaultFrameHeader(metaDataBuffer)); out.format("default %s%n", dataHeaderFlyweight); } out.println(); for (int i = 0; i < PARTITION_COUNT; i++) { final long rawTail = rawTailVolatile(metaDataBuffer, i); final long termOffset = rawTail & 0xFFFF_FFFFL; final int termId = termId(rawTail); final int offset = (int)Math.min(termOffset, termLength); final int positionBitsToShift = LogBufferDescriptor.positionBitsToShift(termLength); out.format( "Index %d Term Meta Data termOffset=%d termId=%d rawTail=%d position=%d%n", i, termOffset, termId, rawTail, LogBufferDescriptor.computePosition(termId, offset, positionBitsToShift, initialTermId)); } for (int i = 0; i < PARTITION_COUNT; i++) { out.println(); out.println("======================================================================"); out.format("Index %d Term Data%n%n", i); final UnsafeBuffer termBuffer = termBuffers[i]; int offset = 0; do { dataHeaderFlyweight.wrap(termBuffer, offset, termLength - offset); out.println(offset + ": " + dataHeaderFlyweight.toString()); final int frameLength = dataHeaderFlyweight.frameLength(); if (frameLength < DataHeaderFlyweight.HEADER_LENGTH) { if (0 == frameLength && AERON_LOG_SCAN_OVER_ZEROES) { offset += FrameDescriptor.FRAME_ALIGNMENT; continue; } try { final int limit = min(termLength - (offset + HEADER_LENGTH), messageDumpLimit); out.println(formatBytes(termBuffer, offset + HEADER_LENGTH, limit)); } catch (final Exception ex) { System.err.printf("frameLength=%d offset=%d%n", frameLength, offset); ex.printStackTrace(); } break; } final int limit = min(frameLength - HEADER_LENGTH, messageDumpLimit); out.println(formatBytes(termBuffer, offset + HEADER_LENGTH, limit)); offset += BitUtil.align(frameLength, FrameDescriptor.FRAME_ALIGNMENT); } while (offset < termLength); } } } /** * Format bytes in a buffer to a char array. * * @param buffer containing the bytes to be formatted. * @param offset in the buffer at which the bytes begin. * @param length of the bytes in the buffer. * @return a char array of the formatted bytes. */ public static char[] formatBytes(final DirectBuffer buffer, final int offset, final int length) { switch (AERON_LOG_DATA_FORMAT) { case "us-ascii": case "us_ascii": case "ascii": return bytesToAscii(buffer, offset, length); default: return bytesToHex(buffer, offset, length); } } private static char[] bytesToAscii(final DirectBuffer buffer, final int offset, final int length) { final char[] chars = new char[length]; for (int i = 0; i < length; i++) { byte b = buffer.getByte(offset + i); if (b < 0) { b = 0; } chars[i] = (char)b; } return chars; } /** * Format bytes to HEX for printing. * * @param buffer containing the bytes. * @param offset in the buffer at which the bytes begin. * @param length of the bytes in the buffer. * @return a char array of the formatted bytes in HEX. */ public static char[] bytesToHex(final DirectBuffer buffer, final int offset, final int length) { final char[] chars = new char[length * 2]; for (int i = 0; i < length; i++) { final int b = buffer.getByte(offset + i) & 0xFF; chars[i * 2] = HEX_ARRAY[b >>> 4]; chars[i * 2 + 1] = HEX_ARRAY[b & 0x0F]; } return chars; } }
38.497835
118
0.573035
ccd2c907d40aabb25484ccac3c31a8d8c47bca87
605
package com.yoloho.enhanced.common.util.aes; import org.junit.Assert; import org.junit.Test; import com.yoloho.enhanced.common.util.aes.AESUtil; public class AESUtilTest { @Test public void encryptTest() { Assert.assertEquals("f06a6dc21b8be9d31cab476251eb375630c731455cbe771f9b5de7877cd755d96ac66d05296556d531003633b8eb41d3", AESUtil.encrypt("ts=123123123123&uid=234234324234", "pass")); Assert.assertEquals("ts=123123123123&uid=234234324234", AESUtil.decrypt("f06a6dc21b8be9d31cab476251eb375630c731455cbe771f9b5de7877cd755d96ac66d05296556d531003633b8eb41d3", "pass")); } }
40.333333
189
0.804959
b67ca9955ebc199a860990c490ce13327ce58e72
1,475
package com.magneton.api2.scanner; import java.nio.file.Path; import java.util.regex.Pattern; import lombok.Getter; /** * 文件扫描器 * * 文件扫描器会为二阶段扫描 * * 首先扫描{@link #subordinatePaths}文件 * * 然后再扫描{@link #primaryPaths}文件 * * @author zhangmingshuang * @since 2019/9/28 */ @Getter public class FileScannerBuilder { /** * 文件规则过滤器 * 所以被过滤的文件都会垃圾文件回收器采集 */ private Pattern filter; /** * 过滤文件采集器 */ private FilterCollector[] filterCollector; /** * 所有文件采集器 */ private FileCollector[] fileCollector; /** * 主要扫描目录 */ private Path[] primaryPaths; /** * 次要扫描目录 */ private Path[] subordinatePaths; public FileScannerBuilder subordinatePaths(Path... subordinatePaths) { this.subordinatePaths = subordinatePaths; return this; } public FileScannerBuilder primaryPaths(Path... primaryPaths) { this.primaryPaths = primaryPaths; return this; } public FileScannerBuilder filterCollector(FilterCollector[] filterCollector) { this.filterCollector = filterCollector; return this; } public FileScannerBuilder fileCollector(FileCollector[] fileCollector) { this.fileCollector = fileCollector; return this; } public FileScannerBuilder filter(Pattern filter) { this.filter = filter; return this; } public Scanner build() { return new FileScanner(this); } }
20.205479
82
0.639322
e824ca8df1e94bc409c3b64cd22abfe05d738a9c
2,329
/** * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 ch.rasc.wamp2spring.pubsub; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import ch.rasc.wamp2spring.WampPublisher; import ch.rasc.wamp2spring.config.DestinationMatch; import ch.rasc.wamp2spring.message.PublishMessage; /** * Memory only implementation of the {@link EventStore} interface. Used for storing * retention messages. Only publishMessages coming from the internal {@link WampPublisher} * are stored in the retention store. */ public class MemoryEventStore implements EventStore { protected final Map<String, PublishMessage> eventRetention = new ConcurrentHashMap<>(); @Override public void retain(PublishMessage publishMessage) { if (publishMessage.getWebSocketSessionId() == null) { this.eventRetention.put(publishMessage.getTopic(), publishMessage); } } @Override public List<PublishMessage> getRetained(DestinationMatch query) { if (query.getMatchPolicy() == MatchPolicy.EXACT) { PublishMessage publishMessage = this.eventRetention .get(query.getDestination()); if (publishMessage != null) { return Collections.singletonList(publishMessage); } return Collections.emptyList(); } if (query.getMatchPolicy() == MatchPolicy.PREFIX || query.getMatchPolicy() == MatchPolicy.WILDCARD) { List<PublishMessage> matchedMessages = new ArrayList<>(); this.eventRetention.forEach((topic, publishMessage) -> { if (query.matches(topic)) { matchedMessages.add(publishMessage); } }); return matchedMessages; } return Collections.emptyList(); } }
33.753623
91
0.72821
a2f7b55ce5047ea75affbda92359fc99aeb8de8d
1,764
package gearth.ui.info; import gearth.Main; import javafx.event.ActionEvent; import javafx.scene.control.Hyperlink; import gearth.ui.SubForm; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * Created by Jonas on 06/04/18. */ public class Info extends SubForm { public ImageView img_logo; public Hyperlink link_sng; public Hyperlink link_darkbox; public Hyperlink link_d_harble; public Hyperlink link_g_gearth; public Hyperlink link_g_tanji; public Hyperlink link_d_bonnie; public Label version; // this is a TEMPORARY info tab public static void activateHyperlink(Hyperlink link) { link.setOnAction((ActionEvent event) -> { Hyperlink h = (Hyperlink) event.getTarget(); String s = h.getTooltip().getText(); Main.main.getHostServices().showDocument(s); event.consume(); }); } public void initialize() { version.setText(version.getText().replace("$version", Main.version)); img_logo.setImage(new Image("/gearth/G-EarthLogo.png")); link_sng.setTooltip(new Tooltip("https://www.sngforum.info")); link_darkbox.setTooltip(new Tooltip("https://darkbox.nl")); link_g_gearth.setTooltip(new Tooltip("https://github.com/sirjonasxx/G-Earth")); link_g_tanji.setTooltip(new Tooltip("https://github.com/ArachisH/Tanji")); link_d_harble.setTooltip(new Tooltip("https://discord.gg/Vyc2gFC")); // activateHyperlink(link_d_harble); activateHyperlink(link_g_gearth); activateHyperlink(link_g_tanji); activateHyperlink(link_sng); activateHyperlink(link_darkbox); } }
32.666667
87
0.693311
d9b3c77800d80e717ebd4ff9c6dfbc09ab544148
13,078
/** * 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 wssec; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.axis.Message; import org.apache.axis.MessageContext; import org.apache.axis.client.AxisClient; import org.apache.axis.configuration.NullProvider; import org.apache.axis.message.SOAPEnvelope; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSConfig; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.WSPasswordCallback; import org.apache.ws.security.WSSecurityEngine; import org.apache.ws.security.components.crypto.Crypto; import org.apache.ws.security.components.crypto.CryptoFactory; import org.apache.ws.security.handler.RequestData; import org.apache.ws.security.handler.WSHandlerConstants; import org.apache.ws.security.message.WSSecHeader; import org.apache.ws.security.message.WSSecSignature; import org.apache.ws.security.message.WSSecUsernameToken; import org.apache.ws.security.util.WSSecurityUtil; import org.apache.xml.security.signature.XMLSignature; import org.w3c.dom.Document; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Vector; /** * WS-Security Test Case for UsernameToken Key Derivation, as defined in the * UsernameTokenProfile 1.1 specification. The derived keys are used for signature. * Note that this functionality is different to the TestWSSecurityUTDK test case, * which uses the derived key in conjunction with wsc:DerivedKeyToken. It's also * different to TestWSSecurityNew13, which derives a key for signature using a * non-standard implementation. */ public class TestWSSecurityUTSignature extends TestCase implements CallbackHandler { private static final Log LOG = LogFactory.getLog(TestWSSecurityUTSignature.class); private static final String SOAPMSG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<SOAP-ENV:Envelope " + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + "<SOAP-ENV:Body>" + "<add xmlns=\"http://ws.apache.org/counter/counter_port_type\">" + "<value xmlns=\"\">15</value>" + "</add>" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>"; private WSSecurityEngine secEngine = new WSSecurityEngine(); private Crypto crypto = CryptoFactory.getInstance(); private MessageContext msgContext; private SOAPEnvelope unsignedEnvelope; /** * TestWSSecurity constructor * <p/> * * @param name name of the test */ public TestWSSecurityUTSignature(String name) { super(name); } /** * JUnit suite * <p/> * * @return a junit test suite */ public static Test suite() { return new TestSuite(TestWSSecurityUTSignature.class); } /** * Setup method * <p/> * * @throws Exception Thrown when there is a problem in setup */ protected void setUp() throws Exception { AxisClient tmpEngine = new AxisClient(new NullProvider()); msgContext = new MessageContext(tmpEngine); unsignedEnvelope = getSOAPEnvelope(); } /** * Constructs a soap envelope * <p/> * * @return soap envelope * @throws java.lang.Exception if there is any problem constructing the soap envelope */ protected SOAPEnvelope getSOAPEnvelope() throws Exception { InputStream in = new ByteArrayInputStream(SOAPMSG.getBytes()); Message msg = new Message(in); msg.setMessageContext(msgContext); return msg.getSOAPEnvelope(); } /** * Test using a UsernameToken derived key for signing a SOAP body */ public void testSignature() throws Exception { Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); WSSecUsernameToken builder = new WSSecUsernameToken(); builder.setUserInfo("bob", "security"); builder.addDerivedKey(true, null, 1000); builder.prepare(doc); WSSecSignature sign = new WSSecSignature(); sign.setUsernameToken(builder); sign.setKeyIdentifierType(WSConstants.UT_SIGNING); sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1); Document signedDoc = sign.build(doc, null, secHeader); builder.prependToHeader(secHeader); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); assertTrue(outputString.indexOf("wsse:Username") != -1); assertTrue(outputString.indexOf("wsse:Password") == -1); assertTrue(outputString.indexOf("wsse11:Salt") != -1); assertTrue(outputString.indexOf("wsse11:Iteration") != -1); if (LOG.isDebugEnabled()) { LOG.debug(outputString); } Vector results = verify(signedDoc); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.UT_SIGN); java.security.Principal principal = (java.security.Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); assertTrue(principal.getName().indexOf("bob") != -1); } /** * Test using a UsernameToken derived key for signing a SOAP body. In this test the * user is "alice" rather than "bob", and so signature verification should fail. */ public void testBadUserSignature() throws Exception { Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); WSSecUsernameToken builder = new WSSecUsernameToken(); builder.setUserInfo("alice", "security"); builder.addDerivedKey(true, null, 1000); builder.prepare(doc); WSSecSignature sign = new WSSecSignature(); sign.setUsernameToken(builder); sign.setKeyIdentifierType(WSConstants.UT_SIGNING); sign.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1); Document signedDoc = sign.build(doc, null, secHeader); builder.prependToHeader(secHeader); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); if (LOG.isDebugEnabled()) { LOG.debug(outputString); } try { verify(signedDoc); throw new Exception("Failure expected on a bad derived signature"); } catch (WSSecurityException ex) { assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION); // expected } } /** * Test using a UsernameToken derived key for signing a SOAP body via WSHandler */ public void testHandlerSignature() throws Exception { final WSSConfig cfg = WSSConfig.getNewInstance(); RequestData reqData = new RequestData(); reqData.setWssConfig(cfg); java.util.Map messageContext = new java.util.TreeMap(); messageContext.put(WSHandlerConstants.PW_CALLBACK_REF, this); messageContext.put(WSHandlerConstants.USE_DERIVED_KEY, "true"); reqData.setMsgContext(messageContext); reqData.setUsername("bob"); final java.util.Vector actions = new java.util.Vector(); actions.add(new Integer(WSConstants.UT_SIGN)); Document doc = unsignedEnvelope.getAsDocument(); MyHandler handler = new MyHandler(); handler.send( WSConstants.UT_SIGN, doc, reqData, actions, true ); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); assertTrue(outputString.indexOf("wsse:Username") != -1); assertTrue(outputString.indexOf("wsse:Password") == -1); assertTrue(outputString.indexOf("wsse11:Salt") != -1); assertTrue(outputString.indexOf("wsse11:Iteration") != -1); if (LOG.isDebugEnabled()) { LOG.debug(outputString); } Vector results = verify(doc); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.UT_SIGN); java.security.Principal principal = (java.security.Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); assertTrue(principal.getName().indexOf("bob") != -1); } /** * Test using a UsernameToken derived key for signing a SOAP body via WSHandler */ public void testHandlerSignatureIterations() throws Exception { final WSSConfig cfg = WSSConfig.getNewInstance(); RequestData reqData = new RequestData(); reqData.setWssConfig(cfg); java.util.Map messageContext = new java.util.TreeMap(); messageContext.put(WSHandlerConstants.PW_CALLBACK_REF, this); messageContext.put(WSHandlerConstants.USE_DERIVED_KEY, "true"); messageContext.put(WSHandlerConstants.DERIVED_KEY_ITERATIONS, "1234"); reqData.setMsgContext(messageContext); reqData.setUsername("bob"); final java.util.Vector actions = new java.util.Vector(); actions.add(new Integer(WSConstants.UT_SIGN)); Document doc = unsignedEnvelope.getAsDocument(); MyHandler handler = new MyHandler(); handler.send( WSConstants.UT_SIGN, doc, reqData, actions, true ); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); assertTrue(outputString.indexOf("wsse:Username") != -1); assertTrue(outputString.indexOf("wsse:Password") == -1); assertTrue(outputString.indexOf("wsse11:Salt") != -1); assertTrue(outputString.indexOf("wsse11:Iteration") != -1); assertTrue(outputString.indexOf("1234") != -1); if (LOG.isDebugEnabled()) { LOG.debug(outputString); } Vector results = verify(doc); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.UT_SIGN); java.security.Principal principal = (java.security.Principal) actionResult.get(WSSecurityEngineResult.TAG_PRINCIPAL); assertTrue(principal.getName().indexOf("bob") != -1); } /** * Verifies the soap envelope. * * @param env soap envelope * @throws java.lang.Exception Thrown when there is a problem in verification */ private Vector verify(Document doc) throws Exception { return secEngine.processSecurityHeader(doc, null, this, crypto); } public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof WSPasswordCallback) { WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN_UNKNOWN && "bob".equals(pc.getIdentifier())) { pc.setPassword("security"); } else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN && "bob".equals(pc.getIdentifier())) { pc.setPassword("security"); } else { throw new IOException("Authentication failed"); } } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } } }
39.273273
94
0.660269
671931ed153aa74b87bc19b96f92ca028fd141ff
5,685
package saga.netflix.conductor.travelservice.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import saga.netflix.conductor.travelservice.error.BookingNotFound; import saga.netflix.conductor.travelservice.error.ErrorType; import saga.netflix.conductor.travelservice.error.TravelException; import saga.netflix.conductor.travelservice.model.BookingStatus; import saga.netflix.conductor.travelservice.model.RejectionReason; import saga.netflix.conductor.travelservice.model.TripInformation; import saga.netflix.conductor.travelservice.model.TripInformationRepository; import saga.netflix.conductor.travelservice.saga.bookTripSaga.BookTripSagaData; import saga.netflix.conductor.travelservice.saga.SagaInstanceFactory; import java.util.LinkedList; import java.util.List; import java.util.Optional; @Service("TravelService") public class TravelService implements ITravelService { private static final Logger logger = LoggerFactory.getLogger(TravelService.class); @Autowired private final TripInformationRepository tripInformationRepository; @Autowired private final SagaInstanceFactory sagaInstanceFactory; public TravelService(final TripInformationRepository tripInformationRepository, final SagaInstanceFactory sagaInstanceFactory) { this.tripInformationRepository = tripInformationRepository; this.sagaInstanceFactory = sagaInstanceFactory; } @Override public List<TripInformation> getTripsInformation() { logger.info("Get trip bookings from Repository."); List<TripInformation> trips = new LinkedList<>(); Iterable<TripInformation> tripsInformation = tripInformationRepository.findAll(); for (TripInformation tripInformation : tripsInformation) { trips.add(tripInformation); } return trips; } @Override public TripInformation getTripInformation(final Long tripId) throws TravelException { logger.info(String.format("Get trip booking (ID: %d) from Repository.", tripId)); Optional<TripInformation> tripInformation = tripInformationRepository.findById(tripId); if (!tripInformation.isPresent()) { String message = String.format("The trip booking (ID: %d) does not exist.", tripId); logger.info(message); throw new TravelException(ErrorType.NON_EXISTING_ITEM, message); } return tripInformation.get(); } @Override public TripInformation bookTrip(final TripInformation tripInformation) { logger.info("Saving the booked Trip: " + tripInformation); // ensure idempotence of trip bookings TripInformation alreadyExistingTripBooking = checkIfBookingAlreadyExists(tripInformation); if (alreadyExistingTripBooking != null) { return alreadyExistingTripBooking; } tripInformationRepository.save(tripInformation); // create and start the BookTripSaga with necessary information BookTripSagaData bookTripSagaData = new BookTripSagaData(tripInformation.getId(), tripInformation); sagaInstanceFactory.startBookTripSaga(bookTripSagaData); return tripInformation; } @Override public void rejectTrip(final Long tripId, final RejectionReason rejectionReason) { logger.info("Rejecting the booked trip with ID " + tripId); try { TripInformation tripInformation = getTripInformation(tripId); BookingStatus newBookingStatus = convertToBookingStatus(rejectionReason); tripInformation.reject(newBookingStatus); tripInformationRepository.save(tripInformation); } catch (TravelException exception) { throw new BookingNotFound(tripId); } } @Override public void confirmTripBooking(final Long tripId, final long hotelId, final long flightId) { logger.info("Confirming the booked trip with ID " + tripId); try { TripInformation tripInformation = getTripInformation(tripId); tripInformation.setHotelId(hotelId); tripInformation.setFlightId(flightId); tripInformation.confirm(); tripInformationRepository.save(tripInformation); } catch (TravelException exception) { throw new BookingNotFound(tripId); } } // ensure idempotence of trip bookings private TripInformation checkIfBookingAlreadyExists(final TripInformation tripInformation) { List<TripInformation> customerTrips = tripInformationRepository.findByTravellerName(tripInformation.getTravellerName()); Optional<TripInformation> savedTripBooking = customerTrips.stream().filter(tripInfo -> tripInfo.equals(tripInformation)).findFirst(); if (!savedTripBooking.isPresent()) { return null; } logger.info("Trip has already been booked: " + savedTripBooking.toString()); return savedTripBooking.get(); } private BookingStatus convertToBookingStatus(final RejectionReason rejectionReason) { switch (rejectionReason) { case NO_HOTEL_AVAILABLE: return BookingStatus.REJECTED_NO_HOTEL_AVAILABLE; case NO_FLIGHT_AVAILABLE: return BookingStatus.REJECTED_NO_FLIGHT_AVAILABLE; case CUSTOMER_VALIDATION_FAILED: return BookingStatus.REJECTED_CUSTOMER_VALIDATION_FAILED; default: return BookingStatus.REJECTED_UNKNOWN; } } }
38.673469
107
0.720141
2aacb20df9a142def7d612b08c07d535649ee2a8
1,056
package me.yohanfernando.samples.pdf.init; import junit.framework.TestCase; import org.junit.*; import org.junit.rules.TestName; /** * Created by yohanfernando on 04/10/2014. * * Contain tests for StartupController which will be the first point of control (at least during the setup phase) */ public class StartupControllerTest { @Rule public TestName testName = new TestName(); @Before public void setUp() throws Exception { System.out.println("Running test " + testName.getMethodName()); } @Test public void testSayHelloWithName() { StartupController sc = new StartupController(); Assert.assertEquals("Hello Test", sc.sayHello("Test")); } @Test public void testSayHelloWithNull() { StartupController sc = new StartupController(); Assert.assertEquals("Hello", sc.sayHello(null)); } @Test public void testSayHelloWithEmptyString() { StartupController sc = new StartupController(); Assert.assertEquals("Hello", sc.sayHello("")); } }
25.756098
113
0.679924
b0d5b54ddbe194ef7e5c87b7d7a54956b91eaac5
2,759
package com.github.mustachejava.util; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.DefaultMustacheVisitor; import com.github.mustachejava.Mustache; import com.github.mustachejava.TemplateContext; import com.github.mustachejava.codes.IterableCode; import com.github.mustachejava.codes.NotIterableCode; import com.github.mustachejava.codes.ValueCode; import java.io.Writer; /** * Grab a map of values returned from calls */ public class CapturingMustacheVisitor extends DefaultMustacheVisitor { private final Captured captured; public interface Captured { void value(String name, String value); void arrayStart(String name); void arrayEnd(); void objectStart(); void objectEnd(); } public CapturingMustacheVisitor(DefaultMustacheFactory cf, Captured captured) { super(cf); this.captured = captured; } @Override public void value(TemplateContext tc, String variable, boolean encoded) { list.add(new ValueCode(tc, df, variable, encoded) { @Override public Object get(Object[] scopes) { Object o = super.get(scopes); if (o != null) { captured.value(name, o.toString()); } return o; } }); } @Override public void iterable(TemplateContext tc, String variable, Mustache mustache) { list.add(new IterableCode(tc, df, mustache, variable) { @Override public Writer execute(Writer writer, Object[] scopes) { Writer execute = super.execute(writer, scopes); captured.arrayEnd(); return execute; } @Override public Writer next(Writer writer, Object next, Object... scopes) { captured.objectStart(); Writer nextObject = super.next(writer, next, scopes); captured.objectEnd(); return nextObject; } @Override public Object get(Object[] scopes) { Object o = super.get(scopes); captured.arrayStart(name); return o; } }); } @Override public void notIterable(TemplateContext tc, String variable, Mustache mustache) { list.add(new NotIterableCode(tc, df, mustache, variable) { boolean called; @Override public Object get(Object[] scopes) { return super.get(scopes); } @Override public Writer next(Writer writer, Object object, Object[] scopes) { called = true; return super.next(writer, object, scopes); } @Override public Writer execute(Writer writer, Object[] scopes) { Writer execute = super.execute(writer, scopes); if (called) { captured.arrayStart(name); captured.arrayEnd(); } return execute; } }); } }
25.785047
83
0.654223
61311233765546a6a0026668d4a77cceab65bde7
759
package net.seiko_comb.combS8214808.joiss2016.multiclass; import static net.seiko_comb.combS8214808.joiss2016.Vector.$; import org.junit.Test; @SuppressWarnings("unused") public class DataTest { @Test public void test() { DataFactory dataSet = new DataFactory(3, 3); Data data = new Data(dataSet, $(4, 2, 3), 0); data = new Data(dataSet, $(1, 3, 2), 2); } @Test(expected=InvalidClassIndexException.class) public void testException(){ DataFactory dataSet = new DataFactory(3, 3); Data data = new Data(dataSet, $(4, 2, 3), 4); } @Test(expected=RuntimeException.class) public void invalidInputDimension(){ DataFactory dataSet = new DataFactory(3, 3); Data data = new Data(dataSet, $(4, 2, 3, 1), 4); } }
26.172414
62
0.675889
324fac6e720520ecf18a1a4b8578a875662962f2
1,126
package net.script.utils; import com.jfoenix.animation.alert.JFXAlertAnimation; import com.jfoenix.controls.JFXAlert; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDialogLayout; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.stage.Modality; import javafx.stage.Stage; import java.util.Optional; public class CommonFXUtils { public static Optional noDataPopup(String title, String body, Scene scene) { JFXAlert alert = new JFXAlert((Stage) scene.getWindow()); JFXDialogLayout layout = new JFXDialogLayout(); JFXButton closeButton = new JFXButton("Close"); closeButton.setButtonType(JFXButton.ButtonType.FLAT); closeButton.setOnAction(event -> alert.hideWithAnimation()); layout.setHeading(new Label(title)); layout.setBody(new Label(body)); layout.setActions(closeButton); alert.setAnimation(JFXAlertAnimation.CENTER_ANIMATION); alert.initModality(Modality.WINDOW_MODAL); alert.setOverlayClose(true); alert.setContent(layout); return alert.showAndWait(); } }
36.322581
80
0.735346
ee13c6b4d3e9d77e12ee539d5d01f26726ee6330
7,033
// Copyright 2018 Google 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.google.firebase.database.core; import com.google.firebase.FirebaseApp; import com.google.firebase.database.DatabaseException; import com.google.firebase.database.Logger; import java.util.List; /** * TODO: Merge this class with Context and clean this up. Some methods may need to be re-added to * FirebaseDatabase if we want to still expose them. */ public class DatabaseConfig extends Context { // TODO: Remove this from the public API since we currently can't pass logging // across AIDL interface. /** * If you would like to provide a custom log target, pass an object that implements the {@link * com.google.firebase.database.Logger Logger} interface. * * @hide * @param logger The custom logger that will be called with all log messages */ public synchronized void setLogger(com.google.firebase.database.logging.Logger logger) { assertUnfrozen(); this.logger = logger; } /** * In the default setup, the Firebase Database library will create a thread to handle all * callbacks. On Android, it will attempt to use the main <a * href="http://developer.android.com/reference/android/os/Looper.html" * target="_blank">Looper</a>. <br> * <br> * In the event that you would like more control over how your callbacks are triggered, you can * provide an object that implements {@link EventTarget EventTarget}. It will be passed a {@link * java.lang.Runnable Runnable} for each callback. * * @param eventTarget The object that will be responsible for triggering callbacks */ public synchronized void setEventTarget(EventTarget eventTarget) { assertUnfrozen(); this.eventTarget = eventTarget; } /** * By default, this is set to {@link Logger.Level#INFO INFO}. This includes any internal errors * ({@link Logger.Level#ERROR ERROR}) and any security debug messages ({@link Logger.Level#INFO * INFO}) that the client receives. Set to {@link Logger.Level#DEBUG DEBUG} to turn on the * diagnostic logging, and {@link Logger.Level#NONE NONE} to disable all logging. * * @param logLevel The desired minimum log level */ public synchronized void setLogLevel(Logger.Level logLevel) { assertUnfrozen(); switch (logLevel) { case DEBUG: this.logLevel = com.google.firebase.database.logging.Logger.Level.DEBUG; break; case INFO: this.logLevel = com.google.firebase.database.logging.Logger.Level.INFO; break; case WARN: this.logLevel = com.google.firebase.database.logging.Logger.Level.WARN; break; case ERROR: this.logLevel = com.google.firebase.database.logging.Logger.Level.ERROR; break; case NONE: this.logLevel = com.google.firebase.database.logging.Logger.Level.NONE; break; default: throw new IllegalArgumentException("Unknown log level: " + logLevel); } } /** * Used primarily for debugging. Limits the debug output to the specified components. By default, * this is null, which enables logging from all components. Setting this explicitly will also set * the log level to {@link Logger.Level#DEBUG DEBUG}. * * @param debugComponents A list of components for which logs are desired, or null to enable all * components */ public synchronized void setDebugLogComponents(List<String> debugComponents) { assertUnfrozen(); setLogLevel(Logger.Level.DEBUG); loggedComponents = debugComponents; } public void setRunLoop(RunLoop runLoop) { this.runLoop = runLoop; } public void setAuthTokenProvider(TokenProvider provider) { this.authTokenProvider = provider; } public void setAppCheckTokenProvider(TokenProvider provider) { this.appCheckTokenProvider = provider; } /** * Sets the session identifier for this Firebase Database connection. * * <p>Use session identifiers to enable multiple persisted authentication sessions on the same * device. There is no need to use this method if there will only be one user per device. * * @param sessionKey The session key to identify the session with. * @since 1.1 */ public synchronized void setSessionPersistenceKey(String sessionKey) { assertUnfrozen(); if (sessionKey == null || sessionKey.isEmpty()) { throw new IllegalArgumentException("Session identifier is not allowed to be empty or null!"); } this.persistenceKey = sessionKey; } /** * By default the Firebase Database client will keep data in memory while your application is * running, but not when it is restarted. By setting this value to `true`, the data will be * persisted to on-device (disk) storage and will thus be available again when the app is * restarted (even when there is no network connectivity at that time). Note that this method must * be called before creating your first Database reference and only needs to be called once per * application. * * @since 2.3 * @param isEnabled Set to true to enable disk persistence, set to false to disable it. */ public synchronized void setPersistenceEnabled(boolean isEnabled) { assertUnfrozen(); this.persistenceEnabled = isEnabled; } /** * By default Firebase Database will use up to 10MB of disk space to cache data. If the cache * grows beyond this size, Firebase Database will start removing data that hasn't been recently * used. If you find that your application caches too little or too much data, call this method to * change the cache size. This method must be called before creating your first Database reference * and only needs to be called once per application. * * <p>Note that the specified cache size is only an approximation and the size on disk may * temporarily exceed it at times. * * @since 2.3 * @param cacheSizeInBytes The new size of the cache in bytes. */ public synchronized void setPersistenceCacheSizeBytes(long cacheSizeInBytes) { assertUnfrozen(); if (cacheSizeInBytes < 1024 * 1024) { throw new DatabaseException("The minimum cache size must be at least 1MB"); } if (cacheSizeInBytes > 100 * 1024 * 1024) { throw new DatabaseException( "Firebase Database currently doesn't support a cache size larger than 100MB"); } this.cacheSize = cacheSizeInBytes; } public synchronized void setFirebaseApp(FirebaseApp app) { this.firebaseApp = app; } }
39.072222
100
0.717048
5813fa7cb0539cfb5ce6c065fe259b2d2bcebfa6
8,200
package com.luckynick.android.test; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.media.MediaPlayer; import android.os.Build; import com.luckynick.shared.PureFunctionalInterface; import com.luckynick.shared.enums.SoundProductionUnit; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.luckynick.custom.Utils.*; public class SoundGenerator { public interface Listener { void playStopped(); } /** * Path where existing audio record is stored. */ private String recordPath; /** * Array of frequencies. Indexes of array represent decimal code of ASCII symbols. * Value is actual frequency which correspond to this symbol. If value is -1, then * symbol is not used in program. */ public static final String LOG_TAG = "Generator"; public static List<Listener> playStoppedSubs = new ArrayList<>(); SoundGenerator(String rec) { recordPath = rec; } /** * Play message on loudspeakers. This method wraps message in START_TAG and END_TAG, * encodes text to frequencies and creates audio data, which is further played through speakers. * @param m text message which has to be encoded and played */ public void playMessage(int freqBindingBase, double freqBindingScale, String m) { int frequenciesArr[] = BaseActivity.getFreqBinding(freqBindingScale); String message = JUNK_RIGHT + START_TAG; //junk here for test message += toHex(m); message += END_TAG + JUNK_RIGHT; Log(LOG_TAG, "Playing new message: " + message); if(m.equals("")) return; int numSamples = SAMPLE_RATE * BEEP_DURATION / 1000; double[][] mSound = new double[message.length()][numSamples]; short[][] mBuffer = new short[message.length()][numSamples]; for (int i = 0; i < message.length(); i++) { int index = (int)message.charAt(i); double currentFreq; if(index >= frequenciesArr.length) currentFreq = frequenciesArr[ERROR_CHAR] + freqBindingBase; else currentFreq = frequenciesArr[message.charAt(i)] + freqBindingBase; if(currentFreq == -1.0) currentFreq = frequenciesArr[ERROR_CHAR] + freqBindingBase; Log(LOG_TAG, "Freq for symb '" + message.charAt(i) + "' num " + i + ": " + currentFreq); for (int j = 0; j < mSound[i].length; j++) { mSound[i][j] = Math.sin(2.0 * Math.PI * j / (SAMPLE_RATE / currentFreq)); mBuffer[i][j] = (short) (mSound[i][j] * Short.MAX_VALUE); } } AudioTrack mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE_OUT, AudioTrack.MODE_STREAM); mAudioTrack.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume()); for(short[] arr : mBuffer) { play(mAudioTrack, arr); } mAudioTrack.release(); for (Listener sub : playStoppedSubs) { sub.playStopped(); } } /** * * @param m * @param loudnessLevel from 0 to 100 */ public void playMessage(int freqBindingBase, double freqBindingScale, String m, final int loudnessLevel, boolean wrapInTags) { int frequenciesArr[] = BaseActivity.getFreqBinding(freqBindingScale); String message = JUNK_RIGHT + START_TAG; //junk here for test message += toHex(m); message += END_TAG + JUNK_RIGHT + JUNK_RIGHT; if(!wrapInTags) message = toHex(m); /*String message; if(wrapInTags) { message = JUNK_RIGHT + START_TAG; //junk here for test message += toHex(m); message += END_TAG + JUNK_RIGHT + JUNK_RIGHT; } else { message = toHex(m); }*/ Log(LOG_TAG, "Playing new message: " + message); if(m.equals("")) return; int numSamples = SAMPLE_RATE * BEEP_DURATION / 1000; double[][] mSound = new double[message.length()][numSamples]; short[][] mBuffer = new short[message.length()][numSamples]; for (int i = 0; i < message.length(); i++) { int index = (int)message.charAt(i); double currentFreq; if(index >= frequenciesArr.length) currentFreq = frequenciesArr[ERROR_CHAR] + freqBindingBase; else currentFreq = frequenciesArr[message.charAt(i)] + freqBindingBase; if(currentFreq == -1.0) currentFreq = frequenciesArr[ERROR_CHAR] + freqBindingBase; Log(LOG_TAG, "Freq for symb '" + message.charAt(i) + "' num " + i + ": " + currentFreq); for (int j = 0; j < mSound[i].length; j++) { mSound[i][j] = Math.sin(2.0 * Math.PI * j / (SAMPLE_RATE / currentFreq)); mBuffer[i][j] = (short) (mSound[i][j] * Short.MAX_VALUE); } } AudioTrack mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE_OUT, AudioTrack.MODE_STREAM); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { float log1=(float)(Math.log(100-loudnessLevel)/Math.log(100)); mAudioTrack.setVolume(1-log1); //mAudioTrack.setVolume(loudness); } else { float deviceLoudness = (loudnessLevel / 100.0f) * AudioTrack.getMaxVolume(); mAudioTrack.setStereoVolume(deviceLoudness, deviceLoudness); } for(short[] arr : mBuffer) { play(mAudioTrack, arr); } mAudioTrack.release(); for (Listener sub : playStoppedSubs) { sub.playStopped(); } } /** * Play raw data. * This version of overloaded method is needed if record * is played multiple times (AudioTrack object can't be used after * it is released) * @param buffer raw data which contains sound */ public void play(short[] buffer) { AudioTrack mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE_OUT, AudioTrack.MODE_STREAM); mAudioTrack.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume()); mAudioTrack.play(); mAudioTrack.write(buffer, 0, buffer.length); mAudioTrack.stop(); mAudioTrack.release(); } /** * Play raw data. * This method of audio output is used when newly encoded messages have * to be played. * @param mAudioTrack * @param buffer raw data which contains sound */ public void play(AudioTrack mAudioTrack, short[] buffer) { if(buffer == null) System.out.println("buffer is null"); //mAudioTrack.setStereoVolume(AudioTrack.getMaxVolume(), AudioTrack.getMaxVolume()); mAudioTrack.play(); mAudioTrack.write(buffer, 0, buffer.length); mAudioTrack.stop(); } /** * Play existing audio record. Used for playing previously recorder message from sender. * For debug purpose. * @return false if there is no record */ public boolean playMediaPlayer() { if(!new File(recordPath).exists()) return false; MediaPlayer mp = new MediaPlayer(); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mp.setDataSource(recordPath); mp.prepare(); } catch (IOException e) { e.printStackTrace(); } mp.start(); while(mp.isPlaying()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } mp.release(); return true; } public static void subscribePlayStoppedEvent(Listener sub) { playStoppedSubs.add(sub); } }
38.139535
106
0.610976
0a28ed89e4f75d5e49f91623cf47c7a6d62faec4
2,772
package seedu.guilttrip.ui.reminder; import java.util.Comparator; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.guilttrip.model.entry.Income; import seedu.guilttrip.model.entry.Period; import seedu.guilttrip.model.reminders.EntryReminder; import seedu.guilttrip.model.util.Frequency; import seedu.guilttrip.ui.UiPart; /** * Displays entry pf EntryReminder */ public class IncomeReminderCard extends UiPart<Region> { private static final String FXML = "income/IncomeCard.fxml"; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exception will be thrown by JavaFX during runtime. * * @see <a href="https://github.com/se-edu/addressbook-level4/issues/336">The issue on GuiltTrip level 4</a> */ public final Income income; public final Period period; public final Frequency freq; private EntryReminder reminder; @javafx.fxml.FXML private HBox cardPane; @FXML private Label desc; @FXML private Label id; @FXML private Label date; @FXML private Label amt; @FXML private Label category; @FXML private FlowPane tags; public IncomeReminderCard(EntryReminder entryReminder, int displayedIndex) { super(FXML); this.reminder = entryReminder; this.income = (Income) entryReminder.getEntry(); this.period = entryReminder.getPeriod(); this.freq = entryReminder.getFrequency(); id.setText(displayedIndex + ". "); String descWithType = entryReminder.getHeader().toString() + " ~ " + income.getDesc().fullDesc; desc.setText(descWithType); date.setText(income.getDate().toString() + "period: " + period + " freq: " + freq.toString()); amt.setText("$" + income.getAmount().value); category.setText(income.getCategory().getCategoryName()); income.getTags().stream() .sorted(Comparator.comparing(tag -> tag.tagName)) .forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof IncomeReminderCard)) { return false; } // state check IncomeReminderCard card = (IncomeReminderCard) other; return id.getText().equals(card.id.getText()) && reminder.equals(card.reminder); } }
31.862069
112
0.663059
de59a3214c10490f8b0f3bb3b820b4d198146733
615
package com.swingfrog.summer.client; import java.util.ArrayList; import java.util.List; public class ClientGroup { private int next = -1; private List<Client> clientList; public ClientGroup() { clientList = new ArrayList<>(); } public void addClient(Client client) { clientList.add(client); } public Client getClientWithNext() { int size = clientList.size(); if (size > 0) { if (size == 1) { return clientList.get(0); } next ++; next = next % size; return clientList.get(next % size); } return null; } public List<Client> listClients() { return clientList; } }
17.083333
39
0.658537
bbc7b4b7fdee43e019f06fa8671318dcf0d54315
102,542
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.management.vanilla.network; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.Response; import com.azure.core.management.exception.ManagementException; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.PollerFlux; import com.azure.management.vanilla.network.implementation.ApplicationGatewaysImpl; import com.azure.management.vanilla.network.models.ApplicationGateway; import com.azure.management.vanilla.network.models.ApplicationGatewayAvailableSslOptions; import com.azure.management.vanilla.network.models.ApplicationGatewayAvailableWafRuleSetsResult; import com.azure.management.vanilla.network.models.ApplicationGatewayBackendHealth; import com.azure.management.vanilla.network.models.ApplicationGatewayBackendHealthOnDemand; import com.azure.management.vanilla.network.models.ApplicationGatewayOnDemandProbe; import com.azure.management.vanilla.network.models.ApplicationGatewaySslPredefinedPolicy; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** Initializes a new instance of the asynchronous NetworkManagementClient type. */ @ServiceClient(builder = NetworkManagementClientBuilder.class) public final class ApplicationGatewaysAsyncClient { private ApplicationGatewaysImpl serviceClient; /** Initializes an instance of ApplicationGateways client. */ ApplicationGatewaysAsyncClient(ApplicationGatewaysImpl serviceClient) { this.serviceClient = serviceClient; } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> deleteWithResponse( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.deleteWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> deleteWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.deleteWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginDelete(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginDelete(resourceGroupName, applicationGatewayName); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginDelete( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginDelete(resourceGroupName, applicationGatewayName, context); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.deleteAsync(resourceGroupName, applicationGatewayName); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> delete(String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.deleteAsync(resourceGroupName, applicationGatewayName, context); } /** * Gets the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified application gateway. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> getByResourceGroupWithResponse( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.getByResourceGroupWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Gets the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified application gateway. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> getByResourceGroupWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this .serviceClient .getByResourceGroupWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Gets the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified application gateway. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> getByResourceGroup(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.getByResourceGroupAsync(resourceGroupName, applicationGatewayName); } /** * Gets the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified application gateway. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> getByResourceGroup( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.getByResourceGroupAsync(resourceGroupName, applicationGatewayName, context); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters) { return this .serviceClient .createOrUpdateWithResponseAsync(resourceGroupName, applicationGatewayName, parameters); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters, Context context) { return this .serviceClient .createOrUpdateWithResponseAsync(resourceGroupName, applicationGatewayName, parameters, context); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGateway>, ApplicationGateway> beginCreateOrUpdate( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters) { return this.serviceClient.beginCreateOrUpdate(resourceGroupName, applicationGatewayName, parameters); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGateway>, ApplicationGateway> beginCreateOrUpdate( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters, Context context) { return this.serviceClient.beginCreateOrUpdate(resourceGroupName, applicationGatewayName, parameters, context); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> createOrUpdate( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters) { return this.serviceClient.createOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> createOrUpdate( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters, Context context) { return this.serviceClient.createOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters, context); } /** * Updates the specified application gateway tags. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param tags Resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> updateTagsWithResponse( String resourceGroupName, String applicationGatewayName, Map<String, String> tags) { return this.serviceClient.updateTagsWithResponseAsync(resourceGroupName, applicationGatewayName, tags); } /** * Updates the specified application gateway tags. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param tags Resource tags. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> updateTagsWithResponse( String resourceGroupName, String applicationGatewayName, Map<String, String> tags, Context context) { return this.serviceClient.updateTagsWithResponseAsync(resourceGroupName, applicationGatewayName, tags, context); } /** * Updates the specified application gateway tags. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param tags Resource tags. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> updateTags( String resourceGroupName, String applicationGatewayName, Map<String, String> tags) { return this.serviceClient.updateTagsAsync(resourceGroupName, applicationGatewayName, tags); } /** * Updates the specified application gateway tags. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param tags Resource tags. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> updateTags( String resourceGroupName, String applicationGatewayName, Map<String, String> tags, Context context) { return this.serviceClient.updateTagsAsync(resourceGroupName, applicationGatewayName, tags, context); } /** * Lists all application gateways in a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listByResourceGroupSinglePage(String resourceGroupName) { return this.serviceClient.listByResourceGroupSinglePageAsync(resourceGroupName); } /** * Lists all application gateways in a resource group. * * @param resourceGroupName The name of the resource group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listByResourceGroupSinglePage( String resourceGroupName, Context context) { return this.serviceClient.listByResourceGroupSinglePageAsync(resourceGroupName, context); } /** * Lists all application gateways in a resource group. * * @param resourceGroupName The name of the resource group. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGateway> listByResourceGroup(String resourceGroupName) { return this.serviceClient.listByResourceGroupAsync(resourceGroupName); } /** * Lists all application gateways in a resource group. * * @param resourceGroupName The name of the resource group. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGateway> listByResourceGroup(String resourceGroupName, Context context) { return this.serviceClient.listByResourceGroupAsync(resourceGroupName, context); } /** * Gets all the application gateways in a subscription. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all the application gateways in a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listSinglePage() { return this.serviceClient.listSinglePageAsync(); } /** * Gets all the application gateways in a subscription. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all the application gateways in a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listSinglePage(Context context) { return this.serviceClient.listSinglePageAsync(context); } /** * Gets all the application gateways in a subscription. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all the application gateways in a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGateway> list() { return this.serviceClient.listAsync(); } /** * Gets all the application gateways in a subscription. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all the application gateways in a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGateway> list(Context context) { return this.serviceClient.listAsync(context); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> startWithResponse(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.startWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> startWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.startWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginStart(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStart(resourceGroupName, applicationGatewayName); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginStart( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginStart(resourceGroupName, applicationGatewayName, context); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> start(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.startAsync(resourceGroupName, applicationGatewayName); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> start(String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.startAsync(resourceGroupName, applicationGatewayName, context); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> stopWithResponse(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.stopWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> stopWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.stopWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginStop(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStop(resourceGroupName, applicationGatewayName); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginStop( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginStop(resourceGroupName, applicationGatewayName, context); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stop(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.stopAsync(resourceGroupName, applicationGatewayName); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> stop(String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.stopAsync(resourceGroupName, applicationGatewayName, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> backendHealthWithResponse( String resourceGroupName, String applicationGatewayName, String expand) { return this.serviceClient.backendHealthWithResponseAsync(resourceGroupName, applicationGatewayName, expand); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> backendHealthWithResponse( String resourceGroupName, String applicationGatewayName, String expand, Context context) { return this .serviceClient .backendHealthWithResponseAsync(resourceGroupName, applicationGatewayName, expand, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGatewayBackendHealth>, ApplicationGatewayBackendHealth> beginBackendHealth( String resourceGroupName, String applicationGatewayName, String expand) { return this.serviceClient.beginBackendHealth(resourceGroupName, applicationGatewayName, expand); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGatewayBackendHealth>, ApplicationGatewayBackendHealth> beginBackendHealth( String resourceGroupName, String applicationGatewayName, String expand, Context context) { return this.serviceClient.beginBackendHealth(resourceGroupName, applicationGatewayName, expand, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> backendHealth( String resourceGroupName, String applicationGatewayName, String expand) { return this.serviceClient.backendHealthAsync(resourceGroupName, applicationGatewayName, expand); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> backendHealth( String resourceGroupName, String applicationGatewayName, String expand, Context context) { return this.serviceClient.backendHealthAsync(resourceGroupName, applicationGatewayName, expand, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> backendHealth( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.backendHealthAsync(resourceGroupName, applicationGatewayName); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> backendHealthOnDemandWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand) { return this .serviceClient .backendHealthOnDemandWithResponseAsync(resourceGroupName, applicationGatewayName, probeRequest, expand); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> backendHealthOnDemandWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand, Context context) { return this .serviceClient .backendHealthOnDemandWithResponseAsync( resourceGroupName, applicationGatewayName, probeRequest, expand, context); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGatewayBackendHealthOnDemand>, ApplicationGatewayBackendHealthOnDemand> beginBackendHealthOnDemand( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand) { return this .serviceClient .beginBackendHealthOnDemand(resourceGroupName, applicationGatewayName, probeRequest, expand); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ApplicationGatewayBackendHealthOnDemand>, ApplicationGatewayBackendHealthOnDemand> beginBackendHealthOnDemand( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand, Context context) { return this .serviceClient .beginBackendHealthOnDemand(resourceGroupName, applicationGatewayName, probeRequest, expand, context); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> backendHealthOnDemand( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand) { return this .serviceClient .backendHealthOnDemandAsync(resourceGroupName, applicationGatewayName, probeRequest, expand); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> backendHealthOnDemand( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand, Context context) { return this .serviceClient .backendHealthOnDemandAsync(resourceGroupName, applicationGatewayName, probeRequest, expand, context); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> backendHealthOnDemand( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest) { return this.serviceClient.backendHealthOnDemandAsync(resourceGroupName, applicationGatewayName, probeRequest); } /** * Lists all available server variables. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableServerVariables API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableServerVariablesWithResponse() { return this.serviceClient.listAvailableServerVariablesWithResponseAsync(); } /** * Lists all available server variables. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableServerVariables API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableServerVariablesWithResponse(Context context) { return this.serviceClient.listAvailableServerVariablesWithResponseAsync(context); } /** * Lists all available server variables. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableServerVariables API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableServerVariables() { return this.serviceClient.listAvailableServerVariablesAsync(); } /** * Lists all available server variables. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableServerVariables API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableServerVariables(Context context) { return this.serviceClient.listAvailableServerVariablesAsync(context); } /** * Lists all available request headers. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableRequestHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableRequestHeadersWithResponse() { return this.serviceClient.listAvailableRequestHeadersWithResponseAsync(); } /** * Lists all available request headers. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableRequestHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableRequestHeadersWithResponse(Context context) { return this.serviceClient.listAvailableRequestHeadersWithResponseAsync(context); } /** * Lists all available request headers. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableRequestHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableRequestHeaders() { return this.serviceClient.listAvailableRequestHeadersAsync(); } /** * Lists all available request headers. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableRequestHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableRequestHeaders(Context context) { return this.serviceClient.listAvailableRequestHeadersAsync(context); } /** * Lists all available response headers. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableResponseHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableResponseHeadersWithResponse() { return this.serviceClient.listAvailableResponseHeadersWithResponseAsync(); } /** * Lists all available response headers. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableResponseHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<List<String>>> listAvailableResponseHeadersWithResponse(Context context) { return this.serviceClient.listAvailableResponseHeadersWithResponseAsync(context); } /** * Lists all available response headers. * * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableResponseHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableResponseHeaders() { return this.serviceClient.listAvailableResponseHeadersAsync(); } /** * Lists all available response headers. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ErrorException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableResponseHeaders API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<List<String>> listAvailableResponseHeaders(Context context) { return this.serviceClient.listAvailableResponseHeadersAsync(context); } /** * Lists all available web application firewall rule sets. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableWafRuleSets API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayAvailableWafRuleSetsResult>> listAvailableWafRuleSetsWithResponse() { return this.serviceClient.listAvailableWafRuleSetsWithResponseAsync(); } /** * Lists all available web application firewall rule sets. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableWafRuleSets API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayAvailableWafRuleSetsResult>> listAvailableWafRuleSetsWithResponse( Context context) { return this.serviceClient.listAvailableWafRuleSetsWithResponseAsync(context); } /** * Lists all available web application firewall rule sets. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableWafRuleSets API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayAvailableWafRuleSetsResult> listAvailableWafRuleSets() { return this.serviceClient.listAvailableWafRuleSetsAsync(); } /** * Lists all available web application firewall rule sets. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableWafRuleSets API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayAvailableWafRuleSetsResult> listAvailableWafRuleSets(Context context) { return this.serviceClient.listAvailableWafRuleSetsAsync(context); } /** * Lists available Ssl options for configuring Ssl policy. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayAvailableSslOptions>> listAvailableSslOptionsWithResponse() { return this.serviceClient.listAvailableSslOptionsWithResponseAsync(); } /** * Lists available Ssl options for configuring Ssl policy. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayAvailableSslOptions>> listAvailableSslOptionsWithResponse(Context context) { return this.serviceClient.listAvailableSslOptionsWithResponseAsync(context); } /** * Lists available Ssl options for configuring Ssl policy. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayAvailableSslOptions> listAvailableSslOptions() { return this.serviceClient.listAvailableSslOptionsAsync(); } /** * Lists available Ssl options for configuring Ssl policy. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayAvailableSslOptions> listAvailableSslOptions(Context context) { return this.serviceClient.listAvailableSslOptionsAsync(context); } /** * Lists all SSL predefined policies for configuring Ssl policy. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGatewaySslPredefinedPolicy>> listAvailableSslPredefinedPoliciesSinglePage() { return this.serviceClient.listAvailableSslPredefinedPoliciesSinglePageAsync(); } /** * Lists all SSL predefined policies for configuring Ssl policy. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGatewaySslPredefinedPolicy>> listAvailableSslPredefinedPoliciesSinglePage( Context context) { return this.serviceClient.listAvailableSslPredefinedPoliciesSinglePageAsync(context); } /** * Lists all SSL predefined policies for configuring Ssl policy. * * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGatewaySslPredefinedPolicy> listAvailableSslPredefinedPolicies() { return this.serviceClient.listAvailableSslPredefinedPoliciesAsync(); } /** * Lists all SSL predefined policies for configuring Ssl policy. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ApplicationGatewaySslPredefinedPolicy> listAvailableSslPredefinedPolicies(Context context) { return this.serviceClient.listAvailableSslPredefinedPoliciesAsync(context); } /** * Gets Ssl predefined policy with the specified policy name. * * @param predefinedPolicyName Name of Ssl predefined policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return ssl predefined policy with the specified policy name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewaySslPredefinedPolicy>> getSslPredefinedPolicyWithResponse( String predefinedPolicyName) { return this.serviceClient.getSslPredefinedPolicyWithResponseAsync(predefinedPolicyName); } /** * Gets Ssl predefined policy with the specified policy name. * * @param predefinedPolicyName Name of Ssl predefined policy. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return ssl predefined policy with the specified policy name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewaySslPredefinedPolicy>> getSslPredefinedPolicyWithResponse( String predefinedPolicyName, Context context) { return this.serviceClient.getSslPredefinedPolicyWithResponseAsync(predefinedPolicyName, context); } /** * Gets Ssl predefined policy with the specified policy name. * * @param predefinedPolicyName Name of Ssl predefined policy. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return ssl predefined policy with the specified policy name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewaySslPredefinedPolicy> getSslPredefinedPolicy(String predefinedPolicyName) { return this.serviceClient.getSslPredefinedPolicyAsync(predefinedPolicyName); } /** * Gets Ssl predefined policy with the specified policy name. * * @param predefinedPolicyName Name of Ssl predefined policy. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return ssl predefined policy with the specified policy name. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewaySslPredefinedPolicy> getSslPredefinedPolicy( String predefinedPolicyName, Context context) { return this.serviceClient.getSslPredefinedPolicyAsync(predefinedPolicyName, context); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginDeleteWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginDeleteWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginDeleteWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this .serviceClient .beginDeleteWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginDeleteWithoutPolling(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginDeleteWithoutPollingAsync(resourceGroupName, applicationGatewayName); } /** * Deletes the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginDeleteWithoutPolling( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginDeleteWithoutPollingAsync(resourceGroupName, applicationGatewayName, context); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> beginCreateOrUpdateWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters) { return this .serviceClient .beginCreateOrUpdateWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName, parameters); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGateway>> beginCreateOrUpdateWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters, Context context) { return this .serviceClient .beginCreateOrUpdateWithoutPollingWithResponseAsync( resourceGroupName, applicationGatewayName, parameters, context); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> beginCreateOrUpdateWithoutPolling( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters) { return this .serviceClient .beginCreateOrUpdateWithoutPollingAsync(resourceGroupName, applicationGatewayName, parameters); } /** * Creates or updates the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param parameters Application gateway resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return application gateway resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGateway> beginCreateOrUpdateWithoutPolling( String resourceGroupName, String applicationGatewayName, ApplicationGateway parameters, Context context) { return this .serviceClient .beginCreateOrUpdateWithoutPollingAsync(resourceGroupName, applicationGatewayName, parameters, context); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginStartWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStartWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginStartWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this .serviceClient .beginStartWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginStartWithoutPolling(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStartWithoutPollingAsync(resourceGroupName, applicationGatewayName); } /** * Starts the specified application gateway. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginStartWithoutPolling( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginStartWithoutPollingAsync(resourceGroupName, applicationGatewayName, context); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginStopWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStopWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Void>> beginStopWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, Context context) { return this .serviceClient .beginStopWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName, context); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginStopWithoutPolling(String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginStopWithoutPollingAsync(resourceGroupName, applicationGatewayName); } /** * Stops the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> beginStopWithoutPolling( String resourceGroupName, String applicationGatewayName, Context context) { return this.serviceClient.beginStopWithoutPollingAsync(resourceGroupName, applicationGatewayName, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayBackendHealth>> beginBackendHealthWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, String expand) { return this .serviceClient .beginBackendHealthWithoutPollingWithResponseAsync(resourceGroupName, applicationGatewayName, expand); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayBackendHealth>> beginBackendHealthWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, String expand, Context context) { return this .serviceClient .beginBackendHealthWithoutPollingWithResponseAsync( resourceGroupName, applicationGatewayName, expand, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> beginBackendHealthWithoutPolling( String resourceGroupName, String applicationGatewayName, String expand) { return this .serviceClient .beginBackendHealthWithoutPollingAsync(resourceGroupName, applicationGatewayName, expand); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> beginBackendHealthWithoutPolling( String resourceGroupName, String applicationGatewayName, String expand, Context context) { return this .serviceClient .beginBackendHealthWithoutPollingAsync(resourceGroupName, applicationGatewayName, expand, context); } /** * Gets the backend health of the specified application gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health of the specified application gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealth> beginBackendHealthWithoutPolling( String resourceGroupName, String applicationGatewayName) { return this.serviceClient.beginBackendHealthWithoutPollingAsync(resourceGroupName, applicationGatewayName); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayBackendHealthOnDemand>> beginBackendHealthOnDemandWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand) { return this .serviceClient .beginBackendHealthOnDemandWithoutPollingWithResponseAsync( resourceGroupName, applicationGatewayName, probeRequest, expand); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ApplicationGatewayBackendHealthOnDemand>> beginBackendHealthOnDemandWithoutPollingWithResponse( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand, Context context) { return this .serviceClient .beginBackendHealthOnDemandWithoutPollingWithResponseAsync( resourceGroupName, applicationGatewayName, probeRequest, expand, context); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> beginBackendHealthOnDemandWithoutPolling( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand) { return this .serviceClient .beginBackendHealthOnDemandWithoutPollingAsync( resourceGroupName, applicationGatewayName, probeRequest, expand); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @param expand Expands BackendAddressPool and BackendHttpSettings referenced in backend health. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> beginBackendHealthOnDemandWithoutPolling( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest, String expand, Context context) { return this .serviceClient .beginBackendHealthOnDemandWithoutPollingAsync( resourceGroupName, applicationGatewayName, probeRequest, expand, context); } /** * Gets the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. * * @param resourceGroupName The name of the resource group. * @param applicationGatewayName The name of the application gateway. * @param probeRequest Details of on demand test probe request. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the backend health for given combination of backend pool and http setting of the specified application * gateway in a resource group. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ApplicationGatewayBackendHealthOnDemand> beginBackendHealthOnDemandWithoutPolling( String resourceGroupName, String applicationGatewayName, ApplicationGatewayOnDemandProbe probeRequest) { return this .serviceClient .beginBackendHealthOnDemandWithoutPollingAsync(resourceGroupName, applicationGatewayName, probeRequest); } /** * Get the next page of items. * * @param nextLink null * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listNextSinglePage(String nextLink) { return this.serviceClient.listNextSinglePageAsync(nextLink); } /** * Get the next page of items. * * @param nextLink null * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listNextSinglePage(String nextLink, Context context) { return this.serviceClient.listNextSinglePageAsync(nextLink, context); } /** * Get the next page of items. * * @param nextLink null * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listAllNextSinglePage(String nextLink) { return this.serviceClient.listAllNextSinglePageAsync(nextLink); } /** * Get the next page of items. * * @param nextLink null * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListApplicationGateways API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGateway>> listAllNextSinglePage(String nextLink, Context context) { return this.serviceClient.listAllNextSinglePageAsync(nextLink, context); } /** * Get the next page of items. * * @param nextLink null * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGatewaySslPredefinedPolicy>> listAvailableSslPredefinedPoliciesNextSinglePage( String nextLink) { return this.serviceClient.listAvailableSslPredefinedPoliciesNextSinglePageAsync(nextLink); } /** * Get the next page of items. * * @param nextLink null * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ApplicationGatewayAvailableSslOptions API service call. */ @ServiceMethod(returns = ReturnType.COLLECTION) public Mono<PagedResponse<ApplicationGatewaySslPredefinedPolicy>> listAvailableSslPredefinedPoliciesNextSinglePage( String nextLink, Context context) { return this.serviceClient.listAvailableSslPredefinedPoliciesNextSinglePageAsync(nextLink, context); } }
52.504864
120
0.745538
bf7e8dc0dd0e5875fe96c9723ed0fb4731a6cded
1,287
// Note: only +, - operations // Parameters: // Variables: 5 // Baselines: 50 // If-Branches: 1 public void reduce(Text prefix, Iterator<IntWritable> iter, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException { int a000 = 0; int a001 = 0; int a002 = 0; int a003 = 0; int a004 = 0; int cur = 0; while (iter.hasNext()) { cur = iter.next().get(); a004 -= a003; a000 -= a001; a001 = 1 - a003; a003 = cur - -1; a000 = a004 + a000; a003 -= a002; cur = cur + a003; a000 += a002; cur = -3 - cur; cur += a000; a001 = a003 - cur; a004 = cur + a004; a002 = a000 + a004; a004 += a000; a004 -= cur; a004 += a003; a004 = a004 * -5; cur -= -4; a001 = cur - cur; a004 += a001; cur -= a001; if (a000 <= a001) { a002 += a003; a004 = a003 + a002; cur -= a003; a003 += cur; a001 = cur - a002; cur += a000; cur = a000 + a002; a003 = a003 + a002; a001 -= a001; a004 = a003 - a000; a003 = a002 + a003; } else { a000 += a004; a002 = cur - a000; a002 = a002 - a000; a003 = cur * 0; a000 = a001 - a001; a003 = a000 + cur; } a000 += a002; a002 = a002 + a000; a003 -= 3; a000 -= a002; a001 = a002 + 2; a000 = a003 + -2; a003 -= cur; cur += a000; a004 = a003 - a004; a004 += a002; a000 = cur + 1; a000 = a003 + a003; } output.collect(prefix, new IntWritable(cur)); }
17.391892
91
0.589744
372ce26ead773d3f7debd9e45ebcea27f1ef52f5
4,529
package com.github.sunnybat.paxchecker.setup; import com.github.sunnybat.commoncode.email.account.EmailAccount; import com.github.sunnybat.commoncode.email.account.GmailAccount; import com.github.sunnybat.commoncode.email.account.SmtpAccount; import com.github.sunnybat.commoncode.oauth.OauthStatusUpdater; import com.github.sunnybat.paxchecker.check.TwitterAccount; import com.github.sunnybat.paxchecker.resources.ResourceConstants; import twitter4j.Twitter; /** * * @author SunnyBat */ public class SetupAuto implements Setup { private String[] args; public SetupAuto(String[] args) { this.args = new String[args.length]; System.arraycopy(args, 0, this.args, 0, args.length); } @Override public void promptForSettings() { // Do not need to do anything } private boolean hasArg(String arg) { for (String s : args) { if (s.equals(arg)) { return true; } } return false; } private String getArg(String arg) { return getArg(arg, 1); } private String getArg(String arg, int indexesOut) { for (int i = 0; i < args.length; i++) { if (args[i].equals(arg) && i < args.length - indexesOut) { return args[i + indexesOut]; } } return ""; // Probably shouldn't return null? } @Override public EmailAccount getEmailAccount() { EmailAccount toAuth; if (hasArg("-gmailapi")) { GmailAccount gmailAccount = new GmailAccount("PAXChecker", ResourceConstants.RESOURCE_LOCATION, ResourceConstants.CLIENT_SECRET_JSON_PATH); if (!gmailAccount.checkAutoAuth()) { return null; } toAuth = gmailAccount; } else { String username = getArg("-username"); String password = getArg("-password"); if (username != null && password != null) { SmtpAccount smtpAccount = new SmtpAccount(username, password); if (!smtpAccount.checkAuthentication()) { return null; } toAuth = smtpAccount; } else { return null; } } String emails = getArg("-cellnum"); if (emails != null) { toAuth.addBccEmailAddress(emails); return toAuth; } else { return null; } } @Override public boolean shouldCheckPAXWebsite() { return !hasArg("-nopax"); } @Override public boolean shouldCheckShowclix() { return !hasArg("-noshowclix"); } @Override public boolean shouldCheckKnownEvents() { return !hasArg("-noknownevents"); } @Override public boolean shouldCheckTwitter() { return !hasArg("-notwitter"); } @Override public boolean shouldFilterShowclix() { return hasArg("-filtershowclix"); } @Override public boolean shouldFilterTwitter() { return hasArg("-filtertwitter"); } @Override public boolean shouldTextTweets() { return hasArg("-texttweets"); } @Override public boolean shouldPlayAlarm() { return hasArg("-alarm"); } @Override public int timeBetweenChecks() { try { return Integer.parseInt(getArg("-delay")); } catch (NumberFormatException nfe) { return 10; } } @Override public String getExpoToCheck() { return getArg("-expo"); } @Override public Twitter getTwitterAccount() { final TwitterAccount myAccount; if (hasArg("-twitterkeys")) { myAccount = new TwitterAccount(getArg("-twitterkeys", 1), getArg("-twitterkeys", 2), getArg("-twitterkeys", 3), getArg("-twitterkeys", 4)); } else { myAccount = new TwitterAccount(); } // TODO Timeout after 60 seconds myAccount.authenticate(new OauthStatusUpdater() { @Override public void authFailure() { System.out.println("Unable to authenticate Twitter account."); } @Override public void authSuccess() { System.out.println("Twitter account authenticated"); } @Override public void setAuthUrl(String url) { System.out.println("Authorization URL: " + url); System.out.println("You'll need to manually verify Twitter via command-line aruments before you can use it with auto-start."); myAccount.interrupt(); } @Override public String getAuthorizationPin() { return null; } @Override public void promptForAuthorizationPin() { System.out.println("PIN authorization request. Interrupting."); myAccount.interrupt(); } @Override public void cancelAuthorizationPinPrompt() { System.out.println("PIN cancellation request. Interrupting."); myAccount.interrupt(); } @Override public void updateStatus(String status) { System.out.println(status); } }, true, true); return myAccount.getAccount(); } @Override public boolean shouldCheckForUpdatesDaily() { return hasArg("-dailyupdates"); } }
23.225641
142
0.695959
2b9ac073be656a8263fec27d57dd63f6db58e8ce
138
package fr.ubordeaux.ddd.examples.domain; public class TokenWithConstructorAccess { public static EntityB one = new EntityB(null); }
23
50
0.782609
3b7991622997536100aeb559fb5e604a75851465
3,612
// 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 com.cloud.bridge.service.jclouds; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import com.cloud.bridge.service.EC2Engine; import com.cloud.bridge.util.ConfigurationHelper; import com.google.common.base.Supplier; /** * @author Kelven Yang */ public enum JCloudsServiceProvider implements Supplier<EC2Engine> { INSTANCE; private final Logger logger; private final Properties properties; private final String serviceEndpoint; private final JCloudsEC2Engine EC2Engine; JCloudsServiceProvider() { logger = Logger.getLogger(JCloudsServiceProvider.class); properties = loadStartupProperties(); serviceEndpoint = initialize(properties); // register service implementation object EC2Engine = new JCloudsEC2Engine(); } @Override public EC2Engine get() { return EC2Engine; } public String getServiceEndpoint() { return serviceEndpoint; } public Properties getStartupProperties() { return properties; } private String initialize(Properties properties) { if (logger.isInfoEnabled()) logger.info("Initializing JCloudsServiceProvider..."); File file = ConfigurationHelper.findConfigurationFile("log4j-cloud.xml"); if (file != null) { System.out.println("Log4j configuration from : " + file.getAbsolutePath()); DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000); } else { System.out.println("Configure log4j with default properties"); } if (logger.isInfoEnabled()) logger.info("ServiceProvider initialized"); return (String) properties.get("serviceEndpoint"); } private Properties loadStartupProperties() { File propertiesFile = ConfigurationHelper.findConfigurationFile("cloud-bridge.properties"); Properties properties = new Properties(); if (propertiesFile != null) { try { properties.load(new FileInputStream(propertiesFile)); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); } logger.info("Use startup properties file: " + propertiesFile.getAbsolutePath()); } else { if (logger.isInfoEnabled()) logger.info("Startup properties is not found."); } return properties; } public void shutdown() { if (logger.isInfoEnabled()) logger.info("ServiceProvider stopped"); } }
32.836364
98
0.704319
bfe74e9f33b7b7622dc13ecca4e41b626f649c22
1,311
// Copyright 2015-2021 Swim 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 swim.util; /** * An {@link OrderedMap} that memoizes partial combinations of sub-elements to * support efficient, incremental reduction of continuously mutating datasets. */ public interface ReducedMap<K, V, U> extends OrderedMap<K, V> { /** * Returns the reduction of this {@code ReducedMap}, combining all contained * elements with the given {@code accumulator} and {@code combiner} functions, * recomputing only what has changed since the last invocation of {@code * reduced}. Stores partial computations to accelerate repeated reduction * of continuously mutating datasets. */ U reduced(U identity, CombinerFunction<? super V, U> accumulator, CombinerFunction<U, U> combiner); }
39.727273
101
0.742944
a3334951af5d4397efd5650d39c8fed81430a5c3
47,610
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.transcribe.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/transcribe-2017-10-26/StartMedicalTranscriptionJob" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StartMedicalTranscriptionJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" by * themselves as the job name. The name must also be unique within an AWS account. If you try to create a medical * transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. * </p> */ private String medicalTranscriptionJobName; /** * <p> * The language code for the language spoken in the input media file. US English (en-US) is the valid value for * medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * </p> */ private String languageCode; /** * <p> * The sample rate, in Hertz, of the audio track in the input media file. * </p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you specify * the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you should leave * the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine the sample rate. * </p> */ private Integer mediaSampleRateHertz; /** * <p> * The audio format of the input media file. * </p> */ private String mediaFormat; private Media media; /** * <p> * The Amazon S3 location where the transcription is stored. * </p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription results. Your * transcript appears in the S3 location you specify. When you call the <a>GetMedicalTranscriptionJob</a>, the * operation returns this location in the <code>TranscriptFileUri</code> field. The S3 bucket must have permissions * that allow Amazon Transcribe Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using the * <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe Medical uses * the default Amazon S3 key for server-side encryption of transcripts that are placed in your S3 bucket. * </p> */ private String outputBucketName; /** * <p> * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of the * transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have permission to use * the specified KMS key. * </p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the default * Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. * </p> */ private String outputEncryptionKMSKeyId; /** * <p> * Optional settings for the medical transcription job. * </p> */ private MedicalTranscriptionSetting settings; /** * <p> * The medical specialty of any clinician speaking in the input media. * </p> */ private String specialty; /** * <p> * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or more * speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to single-speaker * dictated speech, e.g., for clinical notes. * </p> */ private String type; /** * <p> * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" by * themselves as the job name. The name must also be unique within an AWS account. If you try to create a medical * transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. * </p> * * @param medicalTranscriptionJobName * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" * by themselves as the job name. The name must also be unique within an AWS account. If you try to create a * medical transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. */ public void setMedicalTranscriptionJobName(String medicalTranscriptionJobName) { this.medicalTranscriptionJobName = medicalTranscriptionJobName; } /** * <p> * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" by * themselves as the job name. The name must also be unique within an AWS account. If you try to create a medical * transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. * </p> * * @return The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code> * " by themselves as the job name. The name must also be unique within an AWS account. If you try to create * a medical transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. */ public String getMedicalTranscriptionJobName() { return this.medicalTranscriptionJobName; } /** * <p> * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" by * themselves as the job name. The name must also be unique within an AWS account. If you try to create a medical * transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. * </p> * * @param medicalTranscriptionJobName * The name of the medical transcription job. You can't use the strings "<code>.</code>" or "<code>..</code>" * by themselves as the job name. The name must also be unique within an AWS account. If you try to create a * medical transcription job with the same name as a previous medical transcription job, you get a * <code>ConflictException</code> error. * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withMedicalTranscriptionJobName(String medicalTranscriptionJobName) { setMedicalTranscriptionJobName(medicalTranscriptionJobName); return this; } /** * <p> * The language code for the language spoken in the input media file. US English (en-US) is the valid value for * medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * </p> * * @param languageCode * The language code for the language spoken in the input media file. US English (en-US) is the valid value * for medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * @see LanguageCode */ public void setLanguageCode(String languageCode) { this.languageCode = languageCode; } /** * <p> * The language code for the language spoken in the input media file. US English (en-US) is the valid value for * medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * </p> * * @return The language code for the language spoken in the input media file. US English (en-US) is the valid value * for medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * @see LanguageCode */ public String getLanguageCode() { return this.languageCode; } /** * <p> * The language code for the language spoken in the input media file. US English (en-US) is the valid value for * medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * </p> * * @param languageCode * The language code for the language spoken in the input media file. US English (en-US) is the valid value * for medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * @return Returns a reference to this object so that method calls can be chained together. * @see LanguageCode */ public StartMedicalTranscriptionJobRequest withLanguageCode(String languageCode) { setLanguageCode(languageCode); return this; } /** * <p> * The language code for the language spoken in the input media file. US English (en-US) is the valid value for * medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * </p> * * @param languageCode * The language code for the language spoken in the input media file. US English (en-US) is the valid value * for medical transcription jobs. Any other value you enter for language code results in a * <code>BadRequestException</code> error. * @return Returns a reference to this object so that method calls can be chained together. * @see LanguageCode */ public StartMedicalTranscriptionJobRequest withLanguageCode(LanguageCode languageCode) { this.languageCode = languageCode.toString(); return this; } /** * <p> * The sample rate, in Hertz, of the audio track in the input media file. * </p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you specify * the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you should leave * the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine the sample rate. * </p> * * @param mediaSampleRateHertz * The sample rate, in Hertz, of the audio track in the input media file.</p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you * specify the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you * should leave the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine * the sample rate. */ public void setMediaSampleRateHertz(Integer mediaSampleRateHertz) { this.mediaSampleRateHertz = mediaSampleRateHertz; } /** * <p> * The sample rate, in Hertz, of the audio track in the input media file. * </p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you specify * the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you should leave * the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine the sample rate. * </p> * * @return The sample rate, in Hertz, of the audio track in the input media file.</p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you * specify the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you * should leave the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical * determine the sample rate. */ public Integer getMediaSampleRateHertz() { return this.mediaSampleRateHertz; } /** * <p> * The sample rate, in Hertz, of the audio track in the input media file. * </p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you specify * the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you should leave * the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine the sample rate. * </p> * * @param mediaSampleRateHertz * The sample rate, in Hertz, of the audio track in the input media file.</p> * <p> * If you do not specify the media sample rate, Amazon Transcribe Medical determines the sample rate. If you * specify the sample rate, it must match the rate detected by Amazon Transcribe Medical. In most cases, you * should leave the <code>MediaSampleRateHertz</code> field blank and let Amazon Transcribe Medical determine * the sample rate. * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withMediaSampleRateHertz(Integer mediaSampleRateHertz) { setMediaSampleRateHertz(mediaSampleRateHertz); return this; } /** * <p> * The audio format of the input media file. * </p> * * @param mediaFormat * The audio format of the input media file. * @see MediaFormat */ public void setMediaFormat(String mediaFormat) { this.mediaFormat = mediaFormat; } /** * <p> * The audio format of the input media file. * </p> * * @return The audio format of the input media file. * @see MediaFormat */ public String getMediaFormat() { return this.mediaFormat; } /** * <p> * The audio format of the input media file. * </p> * * @param mediaFormat * The audio format of the input media file. * @return Returns a reference to this object so that method calls can be chained together. * @see MediaFormat */ public StartMedicalTranscriptionJobRequest withMediaFormat(String mediaFormat) { setMediaFormat(mediaFormat); return this; } /** * <p> * The audio format of the input media file. * </p> * * @param mediaFormat * The audio format of the input media file. * @return Returns a reference to this object so that method calls can be chained together. * @see MediaFormat */ public StartMedicalTranscriptionJobRequest withMediaFormat(MediaFormat mediaFormat) { this.mediaFormat = mediaFormat.toString(); return this; } /** * @param media */ public void setMedia(Media media) { this.media = media; } /** * @return */ public Media getMedia() { return this.media; } /** * @param media * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withMedia(Media media) { setMedia(media); return this; } /** * <p> * The Amazon S3 location where the transcription is stored. * </p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription results. Your * transcript appears in the S3 location you specify. When you call the <a>GetMedicalTranscriptionJob</a>, the * operation returns this location in the <code>TranscriptFileUri</code> field. The S3 bucket must have permissions * that allow Amazon Transcribe Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using the * <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe Medical uses * the default Amazon S3 key for server-side encryption of transcripts that are placed in your S3 bucket. * </p> * * @param outputBucketName * The Amazon S3 location where the transcription is stored.</p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription * results. Your transcript appears in the S3 location you specify. When you call the * <a>GetMedicalTranscriptionJob</a>, the operation returns this location in the * <code>TranscriptFileUri</code> field. The S3 bucket must have permissions that allow Amazon Transcribe * Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using * the <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe * Medical uses the default Amazon S3 key for server-side encryption of transcripts that are placed in your * S3 bucket. */ public void setOutputBucketName(String outputBucketName) { this.outputBucketName = outputBucketName; } /** * <p> * The Amazon S3 location where the transcription is stored. * </p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription results. Your * transcript appears in the S3 location you specify. When you call the <a>GetMedicalTranscriptionJob</a>, the * operation returns this location in the <code>TranscriptFileUri</code> field. The S3 bucket must have permissions * that allow Amazon Transcribe Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using the * <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe Medical uses * the default Amazon S3 key for server-side encryption of transcripts that are placed in your S3 bucket. * </p> * * @return The Amazon S3 location where the transcription is stored.</p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription * results. Your transcript appears in the S3 location you specify. When you call the * <a>GetMedicalTranscriptionJob</a>, the operation returns this location in the * <code>TranscriptFileUri</code> field. The S3 bucket must have permissions that allow Amazon Transcribe * Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using * the <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe * Medical uses the default Amazon S3 key for server-side encryption of transcripts that are placed in your * S3 bucket. */ public String getOutputBucketName() { return this.outputBucketName; } /** * <p> * The Amazon S3 location where the transcription is stored. * </p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription results. Your * transcript appears in the S3 location you specify. When you call the <a>GetMedicalTranscriptionJob</a>, the * operation returns this location in the <code>TranscriptFileUri</code> field. The S3 bucket must have permissions * that allow Amazon Transcribe Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using the * <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe Medical uses * the default Amazon S3 key for server-side encryption of transcripts that are placed in your S3 bucket. * </p> * * @param outputBucketName * The Amazon S3 location where the transcription is stored.</p> * <p> * You must set <code>OutputBucketName</code> for Amazon Transcribe Medical to store the transcription * results. Your transcript appears in the S3 location you specify. When you call the * <a>GetMedicalTranscriptionJob</a>, the operation returns this location in the * <code>TranscriptFileUri</code> field. The S3 bucket must have permissions that allow Amazon Transcribe * Medical to put files in the bucket. For more information, see <a href= * "https://docs.aws.amazon.com/transcribe/latest/dg/security_iam_id-based-policy-examples.html#auth-role-iam-user" * >Permissions Required for IAM User Roles</a>. * </p> * <p> * You can specify an AWS Key Management Service (KMS) key to encrypt the output of your transcription using * the <code>OutputEncryptionKMSKeyId</code> parameter. If you don't specify a KMS key, Amazon Transcribe * Medical uses the default Amazon S3 key for server-side encryption of transcripts that are placed in your * S3 bucket. * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withOutputBucketName(String outputBucketName) { setOutputBucketName(outputBucketName); return this; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of the * transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have permission to use * the specified KMS key. * </p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the default * Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. * </p> * * @param outputEncryptionKMSKeyId * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of * the transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have * permission to use the specified KMS key.</p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the * default Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. */ public void setOutputEncryptionKMSKeyId(String outputEncryptionKMSKeyId) { this.outputEncryptionKMSKeyId = outputEncryptionKMSKeyId; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of the * transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have permission to use * the specified KMS key. * </p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the default * Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. * </p> * * @return The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of * the transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have * permission to use the specified KMS key.</p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the * default Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. */ public String getOutputEncryptionKMSKeyId() { return this.outputEncryptionKMSKeyId; } /** * <p> * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of the * transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have permission to use * the specified KMS key. * </p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the default * Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. * </p> * * @param outputEncryptionKMSKeyId * The Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key used to encrypt the output of * the transcription job. The user calling the <a>StartMedicalTranscriptionJob</a> operation must have * permission to use the specified KMS key.</p> * <p> * You use either of the following to identify a KMS key in the current account: * </p> * <ul> * <li> * <p> * KMS Key ID: "1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * KMS Key Alias: "alias/ExampleAlias" * </p> * </li> * </ul> * <p> * You can use either of the following to identify a KMS key in the current account or another account: * </p> * <ul> * <li> * <p> * Amazon Resource Name (ARN) of a KMS key in the current account or another account: * "arn:aws:kms:region:account ID:key/1234abcd-12ab-34cd-56ef-1234567890ab" * </p> * </li> * <li> * <p> * ARN of a KMS Key Alias: "arn:aws:kms:region:account ID:alias/ExampleAlias" * </p> * </li> * </ul> * <p> * If you don't specify an encryption key, the output of the medical transcription job is encrypted with the * default Amazon S3 key (SSE-S3). * </p> * <p> * If you specify a KMS key to encrypt your output, you must also specify an output location in the * <code>OutputBucketName</code> parameter. * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withOutputEncryptionKMSKeyId(String outputEncryptionKMSKeyId) { setOutputEncryptionKMSKeyId(outputEncryptionKMSKeyId); return this; } /** * <p> * Optional settings for the medical transcription job. * </p> * * @param settings * Optional settings for the medical transcription job. */ public void setSettings(MedicalTranscriptionSetting settings) { this.settings = settings; } /** * <p> * Optional settings for the medical transcription job. * </p> * * @return Optional settings for the medical transcription job. */ public MedicalTranscriptionSetting getSettings() { return this.settings; } /** * <p> * Optional settings for the medical transcription job. * </p> * * @param settings * Optional settings for the medical transcription job. * @return Returns a reference to this object so that method calls can be chained together. */ public StartMedicalTranscriptionJobRequest withSettings(MedicalTranscriptionSetting settings) { setSettings(settings); return this; } /** * <p> * The medical specialty of any clinician speaking in the input media. * </p> * * @param specialty * The medical specialty of any clinician speaking in the input media. * @see Specialty */ public void setSpecialty(String specialty) { this.specialty = specialty; } /** * <p> * The medical specialty of any clinician speaking in the input media. * </p> * * @return The medical specialty of any clinician speaking in the input media. * @see Specialty */ public String getSpecialty() { return this.specialty; } /** * <p> * The medical specialty of any clinician speaking in the input media. * </p> * * @param specialty * The medical specialty of any clinician speaking in the input media. * @return Returns a reference to this object so that method calls can be chained together. * @see Specialty */ public StartMedicalTranscriptionJobRequest withSpecialty(String specialty) { setSpecialty(specialty); return this; } /** * <p> * The medical specialty of any clinician speaking in the input media. * </p> * * @param specialty * The medical specialty of any clinician speaking in the input media. * @return Returns a reference to this object so that method calls can be chained together. * @see Specialty */ public StartMedicalTranscriptionJobRequest withSpecialty(Specialty specialty) { this.specialty = specialty.toString(); return this; } /** * <p> * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or more * speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to single-speaker * dictated speech, e.g., for clinical notes. * </p> * * @param type * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or * more speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to * single-speaker dictated speech, e.g., for clinical notes. * @see Type */ public void setType(String type) { this.type = type; } /** * <p> * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or more * speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to single-speaker * dictated speech, e.g., for clinical notes. * </p> * * @return The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or * more speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to * single-speaker dictated speech, e.g., for clinical notes. * @see Type */ public String getType() { return this.type; } /** * <p> * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or more * speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to single-speaker * dictated speech, e.g., for clinical notes. * </p> * * @param type * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or * more speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to * single-speaker dictated speech, e.g., for clinical notes. * @return Returns a reference to this object so that method calls can be chained together. * @see Type */ public StartMedicalTranscriptionJobRequest withType(String type) { setType(type); return this; } /** * <p> * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or more * speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to single-speaker * dictated speech, e.g., for clinical notes. * </p> * * @param type * The type of speech in the input audio. <code>CONVERSATION</code> refers to conversations between two or * more speakers, e.g., a conversations between doctors and patients. <code>DICTATION</code> refers to * single-speaker dictated speech, e.g., for clinical notes. * @return Returns a reference to this object so that method calls can be chained together. * @see Type */ public StartMedicalTranscriptionJobRequest withType(Type type) { this.type = type.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMedicalTranscriptionJobName() != null) sb.append("MedicalTranscriptionJobName: ").append(getMedicalTranscriptionJobName()).append(","); if (getLanguageCode() != null) sb.append("LanguageCode: ").append(getLanguageCode()).append(","); if (getMediaSampleRateHertz() != null) sb.append("MediaSampleRateHertz: ").append(getMediaSampleRateHertz()).append(","); if (getMediaFormat() != null) sb.append("MediaFormat: ").append(getMediaFormat()).append(","); if (getMedia() != null) sb.append("Media: ").append(getMedia()).append(","); if (getOutputBucketName() != null) sb.append("OutputBucketName: ").append(getOutputBucketName()).append(","); if (getOutputEncryptionKMSKeyId() != null) sb.append("OutputEncryptionKMSKeyId: ").append(getOutputEncryptionKMSKeyId()).append(","); if (getSettings() != null) sb.append("Settings: ").append(getSettings()).append(","); if (getSpecialty() != null) sb.append("Specialty: ").append(getSpecialty()).append(","); if (getType() != null) sb.append("Type: ").append(getType()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StartMedicalTranscriptionJobRequest == false) return false; StartMedicalTranscriptionJobRequest other = (StartMedicalTranscriptionJobRequest) obj; if (other.getMedicalTranscriptionJobName() == null ^ this.getMedicalTranscriptionJobName() == null) return false; if (other.getMedicalTranscriptionJobName() != null && other.getMedicalTranscriptionJobName().equals(this.getMedicalTranscriptionJobName()) == false) return false; if (other.getLanguageCode() == null ^ this.getLanguageCode() == null) return false; if (other.getLanguageCode() != null && other.getLanguageCode().equals(this.getLanguageCode()) == false) return false; if (other.getMediaSampleRateHertz() == null ^ this.getMediaSampleRateHertz() == null) return false; if (other.getMediaSampleRateHertz() != null && other.getMediaSampleRateHertz().equals(this.getMediaSampleRateHertz()) == false) return false; if (other.getMediaFormat() == null ^ this.getMediaFormat() == null) return false; if (other.getMediaFormat() != null && other.getMediaFormat().equals(this.getMediaFormat()) == false) return false; if (other.getMedia() == null ^ this.getMedia() == null) return false; if (other.getMedia() != null && other.getMedia().equals(this.getMedia()) == false) return false; if (other.getOutputBucketName() == null ^ this.getOutputBucketName() == null) return false; if (other.getOutputBucketName() != null && other.getOutputBucketName().equals(this.getOutputBucketName()) == false) return false; if (other.getOutputEncryptionKMSKeyId() == null ^ this.getOutputEncryptionKMSKeyId() == null) return false; if (other.getOutputEncryptionKMSKeyId() != null && other.getOutputEncryptionKMSKeyId().equals(this.getOutputEncryptionKMSKeyId()) == false) return false; if (other.getSettings() == null ^ this.getSettings() == null) return false; if (other.getSettings() != null && other.getSettings().equals(this.getSettings()) == false) return false; if (other.getSpecialty() == null ^ this.getSpecialty() == null) return false; if (other.getSpecialty() != null && other.getSpecialty().equals(this.getSpecialty()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMedicalTranscriptionJobName() == null) ? 0 : getMedicalTranscriptionJobName().hashCode()); hashCode = prime * hashCode + ((getLanguageCode() == null) ? 0 : getLanguageCode().hashCode()); hashCode = prime * hashCode + ((getMediaSampleRateHertz() == null) ? 0 : getMediaSampleRateHertz().hashCode()); hashCode = prime * hashCode + ((getMediaFormat() == null) ? 0 : getMediaFormat().hashCode()); hashCode = prime * hashCode + ((getMedia() == null) ? 0 : getMedia().hashCode()); hashCode = prime * hashCode + ((getOutputBucketName() == null) ? 0 : getOutputBucketName().hashCode()); hashCode = prime * hashCode + ((getOutputEncryptionKMSKeyId() == null) ? 0 : getOutputEncryptionKMSKeyId().hashCode()); hashCode = prime * hashCode + ((getSettings() == null) ? 0 : getSettings().hashCode()); hashCode = prime * hashCode + ((getSpecialty() == null) ? 0 : getSpecialty().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); return hashCode; } @Override public StartMedicalTranscriptionJobRequest clone() { return (StartMedicalTranscriptionJobRequest) super.clone(); } }
42.132743
156
0.627137
887958b5a7fbb4ee6c4eb47a48fb7b79cc9d8739
1,622
package com.bnd.math.domain.dynamics; import java.util.Date; import com.bnd.core.domain.um.User; import com.bnd.math.domain.rand.RandomDistribution; public class MultiRunAnalysisSpec<T> { private Long id; private Long version = new Long(1); private Date timeCreated = new Date(); private User createdBy; private String name; private SingleRunAnalysisSpec singleRunSpec; private RandomDistribution<T> initialStateDistribution; private Integer runNum; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public Date getTimeCreated() { return timeCreated; } public void setTimeCreated(Date timeCreated) { this.timeCreated = timeCreated; } public User getCreatedBy() { return createdBy; } public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } public String getName() { return name; } public void setName(String name) { this.name = name; } public SingleRunAnalysisSpec getSingleRunSpec() { return singleRunSpec; } public void setSingleRunSpec(SingleRunAnalysisSpec singleRunSpec) { this.singleRunSpec = singleRunSpec; } public RandomDistribution<T> getInitialStateDistribution() { return initialStateDistribution; } public void setInitialStateDistribution(RandomDistribution<T> initialStateDistribution) { this.initialStateDistribution = initialStateDistribution; } public Integer getRunNum() { return runNum; } public void setRunNum(Integer runNum) { this.runNum = runNum; } }
19.542169
90
0.751541
35cf2bff056ea3b0974c76ac8c6c6d22359beabd
3,383
package ctrmap.stdlib.fs.accessors.arc; import ctrmap.stdlib.fs.FSFile; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * A metadata file containing various information about an extracted ArcFile. */ public class DotArc { public static final String DOT_ARC_SIGNATURE = ".arc"; public CompressorBehavior defaultCompressionDirective = CompressorBehavior.AUTO; public Map<String, CompressorBehavior> compressionDirectives = new HashMap<>(); private FSFile source; public DotArc(FSFile dotArcFile) { try { source = dotArcFile; if (dotArcFile == null || !dotArcFile.exists()) { return; } BufferedReader reader = new BufferedReader(new InputStreamReader(dotArcFile.getInputStream().getInputStream())); if (reader.ready()) { String signature = reader.readLine(); if (signature.equals(DOT_ARC_SIGNATURE)) { while (reader.ready()) { String line = reader.readLine(); String[] cmds = line.split(" +"); switch (cmds[0]) { case "compress": switch (cmds[1]) { case "default": defaultCompressionDirective = CompressorBehavior.getCBByBId(cmds[2]); break; default: compressionDirectives.put(cmds[1], CompressorBehavior.getCBByBId(cmds[2])); break; } break; } } } } reader.close(); } catch (IOException ex) { Logger.getLogger(DotArc.class.getName()).log(Level.SEVERE, null, ex); } } public static void setCompressionDirectiveToFile(FSFile dotArc, String filePath, CompressorBehavior behavior){ if (dotArc != null && !dotArc.isDirectory()){ DotArc da = new DotArc(dotArc); da.addCompressionDirective(filePath, behavior); da.updateAndWrite(); } } public void addCompressionDirective(String path, CompressorBehavior behavior){ compressionDirectives.put(path, behavior); } public void updateAndWrite() { if (source != null) { try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(source.getOutputStream().getOutputStream())); writer.write(DOT_ARC_SIGNATURE); writer.write(System.lineSeparator()); writeCmprBehavior(defaultCompressionDirective, "default", writer); for (Map.Entry<String, CompressorBehavior> e : compressionDirectives.entrySet()) { writeCmprBehavior(e.getValue(), e.getKey(), writer); } writer.close(); } catch (IOException ex) { Logger.getLogger(DotArc.class.getName()).log(Level.SEVERE, null, ex); } } } private void writeCmprBehavior(CompressorBehavior bhv, String key, Writer writer) throws IOException { writer.write("compress "); writer.write(key); writer.write(' '); writer.write(bhv.behaviorId); writer.write(System.lineSeparator()); } public static enum CompressorBehavior { AUTO("auto"), COMPRESS("true"), DO_NOT_COMPRESS("false"); public final String behaviorId; private CompressorBehavior(String bId) { behaviorId = bId; } public static CompressorBehavior getCBByBId(String bId) { for (CompressorBehavior c : values()) { if (c.behaviorId.equals(bId)) { return c; } } return AUTO; } } }
27.504065
115
0.698197
8bad6221ab00c97ecca45607f19ff2a6ceb7a221
11,082
package com.github.dactiv.basic.authentication.controller; import com.github.dactiv.basic.authentication.config.ApplicationConfig; import com.github.dactiv.basic.authentication.domain.entity.SystemUserEntity; import com.github.dactiv.basic.authentication.domain.entity.UserAvatarHistoryEntity; import com.github.dactiv.basic.authentication.service.ConsoleUserService; import com.github.dactiv.basic.authentication.service.MemberUserService; import com.github.dactiv.basic.commons.enumeration.ResourceSourceEnum; import com.github.dactiv.framework.commons.Casts; import com.github.dactiv.framework.commons.RestResult; import com.github.dactiv.framework.commons.exception.SystemException; import com.github.dactiv.framework.idempotent.annotation.Idempotent; import com.github.dactiv.framework.minio.MinioTemplate; import com.github.dactiv.framework.minio.data.Bucket; import com.github.dactiv.framework.minio.data.FileObject; import com.github.dactiv.framework.spring.security.entity.SecurityUserDetails; import com.github.dactiv.framework.spring.security.enumerate.ResourceType; import com.github.dactiv.framework.spring.security.plugin.Plugin; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.CurrentSecurityContext; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.text.MessageFormat; import java.util.Map; import java.util.Objects; /** * 用户头像管理 * * @author maurice.chen */ @Slf4j @RestController @RequestMapping("user/avatar") @Plugin( name = "用户头像管理", id = "user-avatar", type = ResourceType.Security, sources = ResourceSourceEnum.CONSOLE_SOURCE_VALUE, parent = "file-manager" ) public class UserAvatarController implements InitializingBean { private final ApplicationConfig applicationConfig; private final MinioTemplate minioTemplate; private final ConsoleUserService consoleUserService; private final MemberUserService memberUserService; public UserAvatarController(ApplicationConfig applicationConfig, MinioTemplate minioTemplate, ConsoleUserService consoleUserService, MemberUserService memberUserService) { this.applicationConfig = applicationConfig; this.minioTemplate = minioTemplate; this.consoleUserService = consoleUserService; this.memberUserService = memberUserService; } /** * 上传头像 * * @param file 头像 * * @return reset 结果集 * * @throws Exception 上传错误时抛出 */ @PostMapping("upload") @PreAuthorize("hasAuthority('perms[user_avatar:upload]') and isFullyAuthenticated()") @Plugin(name = "上传头像", parent = "user-avatar", sources = ResourceSourceEnum.SYSTEM_SOURCE_VALUE, audit = true) @Idempotent(key = "idempotent:authentication:user:avatar:upload:[#securityContext.authentication.details.id]") public RestResult<Map<String, Object>> upload(@CurrentSecurityContext SecurityContext securityContext, @RequestParam("file") MultipartFile file) throws Exception { SecurityUserDetails userDetails = Casts.cast(securityContext.getAuthentication().getDetails()); UserAvatarHistoryEntity history = getUserAvatarHistory(userDetails); if (!history.getValues().contains(file.getOriginalFilename())) { history.getValues().add(file.getOriginalFilename()); } if (history.getValues().size() > applicationConfig.getUserAvatar().getHistoryCount()) { history.getValues().remove(0); } history.setCurrentAvatarFilename(file.getOriginalFilename()); minioTemplate.writeJsonValue(FileObject.of(history.getBucketName(), history.getHistoryFilename()), history); minioTemplate.upload( FileObject.of(history.getBucketName(), file.getOriginalFilename()), file.getInputStream(), file.getSize(), file.getContentType() ); String currentName = getCurrentAvatarFilename(userDetails.getId()); minioTemplate.upload( FileObject.of(history.getBucketName(), currentName), file.getInputStream(), file.getSize(), file.getContentType() ); return RestResult.of("上传新头像完成"); } /** * 获取历史头像 * * @param securityContext 安全上下文 * * @return 用户头像历史记录实体 */ @GetMapping("history") @PreAuthorize("isFullyAuthenticated()") public RestResult<UserAvatarHistoryEntity> history(@CurrentSecurityContext SecurityContext securityContext) { SecurityUserDetails userDetails = Casts.cast(securityContext.getAuthentication().getDetails()); return RestResult.ofSuccess(getUserAvatarHistory(userDetails)); } /** * 获取用户历史头像信息 * * @param userDetails 用户明细 * * @return 用户头像历史记录实体 */ private UserAvatarHistoryEntity getUserAvatarHistory(SecurityUserDetails userDetails) { String bucketName = userDetails.getType() + Casts.DEFAULT_DOT_SYMBOL + applicationConfig.getUserAvatar().getBucketName(); String token = applicationConfig.getUserAvatar().getHistoryFileToken(); String filename = MessageFormat.format(token, userDetails.getId()); FileObject fileObject = FileObject.of(bucketName, filename); UserAvatarHistoryEntity result = minioTemplate.readJsonValue(fileObject, UserAvatarHistoryEntity.class); if (Objects.isNull(result)) { result = new UserAvatarHistoryEntity(); result.setHistoryFilename(filename); result.setBucketName(bucketName); } return result; } /** * 获取用户头像 * * @param type 用户类型 * @param filename 文件名 * * @return 头像 byte 数组 * * @throws Exception 获取错误时抛出 */ @GetMapping("get/{type}/{filename}") public ResponseEntity<byte[]> get(@PathVariable("type") String type, @PathVariable("filename") String filename) throws Exception { String bucketName = type + Casts.DEFAULT_DOT_SYMBOL + applicationConfig.getUserAvatar().getBucketName(); InputStream is; try { is = minioTemplate.getObject(FileObject.of(bucketName, filename)); } catch (Exception e) { String token = StringUtils.substringBefore(applicationConfig.getUserAvatar().getCurrentUseFileToken(), Casts.PATH_VARIABLE_SYMBOL_START); Integer id = NumberUtils.toInt(StringUtils.replace(filename, token, StringUtils.EMPTY)); SystemUserEntity user; if (ResourceSourceEnum.CONSOLE_SOURCE_VALUE.equals(type)) { user = consoleUserService.get(id); } else if (ResourceSourceEnum.USER_CENTER_SOURCE_VALUE.equals(type)) { user = memberUserService.get(id); } else { throw new SystemException("找不到类型为 [" + type + "] 的头像获取内容"); } is = applicationConfig.getUserAvatar().getDefaultAvatarPath(user.getGender(), id); } return new ResponseEntity<>(IOUtils.toByteArray(is), new HttpHeaders(), HttpStatus.OK); } /** * 选择历史头像 * * @param securityContext 安全上下文 * @param filename 历史头像文件名称 * * @return rest 结果集 * * @throws Exception 拷贝文件错误时抛出 */ @PostMapping("select") @PreAuthorize("isFullyAuthenticated()") public RestResult<?> select(@CurrentSecurityContext SecurityContext securityContext, @RequestParam("filename") String filename) throws Exception { SecurityUserDetails userDetails = Casts.cast(securityContext.getAuthentication().getDetails()); UserAvatarHistoryEntity history = getUserAvatarHistory(userDetails); if (!history.getValues().contains(filename)) { throw new SystemException("图片不存在,可能已经被删除。"); } String currentName = getCurrentAvatarFilename(userDetails.getId()); minioTemplate.copyObject( FileObject.of(history.getBucketName(), filename), FileObject.of(history.getBucketName(), currentName) ); history.setCurrentAvatarFilename(filename); minioTemplate.writeJsonValue(FileObject.of(history.getBucketName(), history.getHistoryFilename()), history); return RestResult.of("更换头像成功"); } /** * 获取当前头像文件名称 * * @param suffix 后缀 * * @return 当前头像文件名称 */ private String getCurrentAvatarFilename(Object suffix) { String token = applicationConfig.getUserAvatar().getCurrentUseFileToken(); return MessageFormat.format(token, suffix); } /** * 删除历史头像 * * @param securityContext 安全上下文 * @param filename 要删除的文件名称 * * @return rest 结果集 * * @throws Exception 删除错误时候抛出 */ @PostMapping("delete") @PreAuthorize("isFullyAuthenticated()") @Idempotent(key = "idempotent:authentication:user:avatar:delete:[#securityContext.authentication.details.id]") public RestResult<?> delete(@CurrentSecurityContext SecurityContext securityContext, @RequestParam("filename") String filename) throws Exception { SecurityUserDetails userDetails = Casts.cast(securityContext.getAuthentication().getDetails()); UserAvatarHistoryEntity history = getUserAvatarHistory(userDetails); if (!history.getValues().contains(filename)) { throw new SystemException("图片不存在,可能已经被删除。"); } history.getValues().remove(filename); if (StringUtils.equals(filename, history.getCurrentAvatarFilename())) { history.setCurrentAvatarFilename(""); } minioTemplate.writeJsonValue(FileObject.of(history.getBucketName(), history.getHistoryFilename()), history); minioTemplate.deleteObject(FileObject.of(history.getBucketName(), filename)); return RestResult.of("删除历史头像成功"); } @Override public void afterPropertiesSet() throws Exception { for (String s : applicationConfig.getUserAvatar().getUserSources()) { String name = ResourceSourceEnum.getMinioBucket(s); String bucketName = applicationConfig.getUserAvatar().getBucketName() + Casts.DEFAULT_DOT_SYMBOL + name; minioTemplate.makeBucketIfNotExists(Bucket.of(bucketName)); } } }
37.063545
149
0.684985
faeb0f0196626a9aa9b87d3fafe3b1c36426ca93
4,055
package edu.pdx.cs410J.greencod; import edu.pdx.cs410J.AppointmentBookParser; import edu.pdx.cs410J.ParserException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.Date; /** * This class represents a <code>TextParser</code> */ public class TextParser implements AppointmentBookParser<AppointmentBook> { private final BufferedReader r; /** * Creates a new <code>TextParser</code> * @param r * The Reader for TextParser */ public TextParser(Reader r) { this.r = new BufferedReader(r); } /** * Parses a file and builds an <code>AppointmentBook</code> * with the information * @return * null if nothing, built <code>AppointmentBook</code> if success * @throws ParserException * With explanation */ public AppointmentBook parse() throws ParserException { try { if(!r.ready()) { throw new ParserException("No Owner Provided"); } String owner = r.readLine(); AppointmentBook newAppointmentBook = new AppointmentBook(owner); String line; String description = null; String beginDate; String beginTime; String endDate; String endTime; String beginPeriod; String endPeriod; if(owner != null){ System.out.println("Checking contents of file...."); while((line = r.readLine()) != null) { description = line; beginDate = r.readLine(); if(beginDate == null){ throw new ParserException("Missing Begin Date"); } Project4.validateDate(beginDate); beginTime = r.readLine(); if(beginTime == null){ throw new ParserException("Missing Begin Time"); } Project4.validateTime(beginTime); beginPeriod = r.readLine(); if(beginPeriod == null){ throw new ParserException("Missing Begin Period"); } Project4.validatePeriod(beginPeriod); endDate = r.readLine(); if(endDate == null){ throw new ParserException("Missing End Date"); } endDate = Project4.validateDate(endDate); endTime = r.readLine(); if(endTime == null){ throw new ParserException("Missing End Time"); } Project4.validateTime(endTime); endPeriod = r.readLine(); if(endPeriod == null){ throw new ParserException("Missing End Period"); } Project4.validatePeriod(endPeriod); StringBuilder dateString = Project4.sToSb(beginDate, beginTime, beginPeriod); Date bd = Project4.sDateFormatter(dateString); dateString = Project4.sToSb(endDate, endTime, endPeriod); Date ed = Project4.sDateFormatter(dateString); String[] deetz = new String[]{beginDate, beginTime, beginPeriod, endDate, endTime, endPeriod}; Appointment newAppointment = new Appointment(owner, description, bd, ed, deetz); newAppointmentBook.addAppointment(newAppointment); } if(description == null){ throw new ParserException("Missing Description"); } } System.out.println("file contents good"); return newAppointmentBook; } catch (ParserException | IOException e) { System.err.println("Mistake in parser: " + e); System.exit(1); } return null; } }
38.619048
114
0.524784
6dc6f998944751a97e4dc54478371c5255357a89
920
package com.sugar.sugarlibrary.image; import android.content.Context; import android.util.AttributeSet; import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView; import com.sugar.sugarlibrary.image.listener.OnProgressListener; /** * Created by android_ls on 2017/5/17. */ public class LargePhotoView extends SubsamplingScaleImageView { private OnProgressListener mOnProgressListener; public LargePhotoView(Context context, AttributeSet attr) { super(context, attr); } public LargePhotoView(Context context) { super(context); } public void setOnProgressListener(OnProgressListener listener) { this.mOnProgressListener = listener; } /** * 加载进度 * @param progress 0~100 */ public void onProgress(int progress) { if(mOnProgressListener != null) { mOnProgressListener.onProgress(progress); } } }
23.589744
69
0.707609
92286f5dc141cdb63bd81d53eb13dd44e2176836
3,948
package evaluation.trains; import java.util.HashMap; import java.util.Map; public class Trains { static Map<String, Integer> distance = new HashMap<>(); static int totalNumberOfTrips, shortestRoute, numberDifferentRoutes; // Define de distance values /*static { distance.put("AB", 5); distance.put("BC", 4); distance.put("CD", 8); distance.put("DC", 8); distance.put("DE", 6); distance.put("AD", 5); distance.put("CE", 2); distance.put("EB", 3); distance.put("AE", 7); }*/ /** * Method that loads the map * @param values */ public static void registerGraph(String...values) { for (String value : values) { value = value.trim().replaceAll(" ",""); distance.put(value.substring(0, 2), Integer.parseInt(value.substring(2))); } } /** * Method that calculates the distance for a route * @param cities * @return calculated distance as string */ public static String distanceRoute(String...cities) { String lastCity = null; int totalDistance = 0; String route; for (String city : cities) { if (lastCity != null) { route = lastCity.concat(city); try { totalDistance += distance.get(route); } catch(NullPointerException npe) { return "NO SUCH ROUTE"; } } lastCity = city; } return String.valueOf(totalDistance); } /* * Iterates over all alternatives of routes */ private static void verifyNumberOfTrip(String origin, String destination, int maxNumberOfTrips) { distance.forEach((k,v) -> { if (k.startsWith(origin)) { if (k.endsWith(destination)) { // Modify the total number of trips Trains.totalNumberOfTrips++; } if (maxNumberOfTrips > 1){ verifyNumberOfTrip(k.substring(1), destination, maxNumberOfTrips-1); } } }); } /** * Method that defines the number of available trips to a destination * @param origin * @param destination * @param maxNumberOfTrips * @return */ public static int numberOfTrips(String origin, String destination, int maxNumberOfTrips) { totalNumberOfTrips = 0; verifyNumberOfTrip(origin, destination, maxNumberOfTrips); return totalNumberOfTrips; } /* * Iterates over the most reduced alternatives of routes */ private static void verifyShortestRoute(String origin, String destination, int totalNumberOfDistanceTravel) { distance.forEach((k,v) -> { if (k.startsWith(origin)) { if (k.endsWith(destination)) { // Obtain the shortest Route if (Trains.shortestRoute == 0 || totalNumberOfDistanceTravel+v < Trains.shortestRoute) Trains.shortestRoute = totalNumberOfDistanceTravel+v; } else { verifyShortestRoute(k.substring(1), destination, totalNumberOfDistanceTravel+v); } } }); } /** * Method that defines the shortest route available * @param origin * @param destination * @return */ public static int shortestRoute(String origin, String destination) { shortestRoute = 0; verifyShortestRoute(origin, destination, 0); return shortestRoute; } /* * Iterates over all alternatives of routes */ private static void verifyDifferentRoutes(String origin, String destination, int maxNumberOfDistance) { distance.forEach((k,v) -> { if (k.startsWith(origin)) { // Verify that the max distance doesn't pass the available distance if (k.endsWith(destination) && maxNumberOfDistance > v) { // Number of total different routes Trains.numberDifferentRoutes++; } if (maxNumberOfDistance > v){ verifyDifferentRoutes(k.substring(1), destination, maxNumberOfDistance-v); } } }); } /** * Method that defines the number of different routes * @param origin * @param destination * @param maxDistance * @return */ public static int numberDifferentRoutes(String origin, String destination, int maxDistance) { numberDifferentRoutes = 0; verifyDifferentRoutes(origin, destination, maxDistance); return numberDifferentRoutes; } }
26.145695
110
0.687943
78348c96c72c0acb490f27b89526dbf2d7d21881
2,376
package com.akx2.skifreeze; import com.akx2.x2.IGameObject; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; public class PowderManager { public final int MAX_POWDER = 100; public final float SPAWN_RATE = 0.05f; public final int PLUME_COUNT = 25; Powder[] powders; int powdersIndex; int idx; float spawnTimer; public PowderManager () { powders = new Powder[MAX_POWDER]; for (idx=0; idx<MAX_POWDER; idx++) { powders[idx] = new Powder(); } idx = 0; spawnTimer = 0; powdersIndex = 0; } int getNextPowder () { if (powdersIndex == MAX_POWDER-1) { powdersIndex = 0; return powdersIndex; } else { powdersIndex++; return powdersIndex; } } public void setMovement(int x, int y) { for (idx=0; idx<MAX_POWDER; idx++) { if (powders[idx].isActive) { powders[idx].setMovement(x, y); } } } public void generatePlume (Vector2 playerPosition, int plumeStrength, int plumeAmount) { for (idx=0; idx<plumeAmount; idx++) { powders[getNextPowder()].activatePlume(playerPosition.x, playerPosition.y, true, plumeStrength); powders[getNextPowder()].activatePlume(playerPosition.x, playerPosition.y, false, plumeStrength); } } public void update(Vector2 playerPosition, boolean allowSpawn) { for (idx=0; idx<MAX_POWDER; idx++) { powders[idx].update(); } if (allowSpawn) { if (spawnTimer >= SPAWN_RATE) { spawnTimer = 0; powders[getNextPowder()].activateTrail(playerPosition.x, playerPosition.y, true); powders[getNextPowder()].activateTrail(playerPosition.x, playerPosition.y, false); } else { spawnTimer += Gdx.graphics.getDeltaTime(); } } } public void render(SpriteBatch batch) { for (idx=0; idx<MAX_POWDER; idx++) { powders[idx].render(batch); } } public void dispose() { for (idx=0; idx<MAX_POWDER; idx++) { powders[idx].dispose(); } } }
25.276596
109
0.555556
018fab569b989960944157d215d7bda5a78a8eba
841
package a3.network.api.messages; import java.util.UUID; import ray.networking.IGameConnection.ProtocolType; public interface Message { public UUID getUUID(); public void setUUID(UUID uuid); public MessageType getMessageType(); public void setMessageType(MessageType messageType); public String getFromIP(); public void setFromIP(String fromIP); public String getToIP(); public void setToIP(String toIP); public Integer getFromPort(); public void setFromPort(Integer fromPort); public Integer getToPort(); public void setToPort(Integer toPort); public ProtocolType getProtocol(); public void setProtocol(ProtocolType protocol); public String getFromName(); public void setFromName(String fromName); public String getToName(); public void setToName(String toName); public String toMessageString(); }
21.564103
53
0.774078
46defe0cb685debc53d7c834d3fe30f63a4b120f
862
package com.xuzimian.java.learning.components.beanutils.hutool; import cn.hutool.core.bean.BeanUtil; import com.xuzimian.java.learning.components.beanutils.base.BaseBeanUtlis; import com.xuzimian.java.learning.components.beanutils.base.BeanModelSource; import com.xuzimian.java.learning.components.beanutils.base.BeanModelTarget; import org.junit.jupiter.api.Test; public class HutoolBeanUtilDemo extends BaseBeanUtlis { @Test public void testCopy() { BeanModelTarget beanModelTarget = new BeanModelTarget(); BeanUtil.copyProperties(BeanModelSource.getExample(), beanModelTarget); System.out.print(beanModelTarget); } /** * 测试转换效率 */ @Test public void testCopyEfficiency() { runCopyEfficiency(BeanModelSource.getExample(), s -> BeanUtil.copyProperties(s, new BeanModelTarget() )); } }
33.153846
113
0.7471
0d38c2c76db9d077556b885ff237d7e294cfbe29
7,660
package neqsim.processSimulation.processEquipment.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import neqsim.processSimulation.processEquipment.ProcessEquipmentBaseClass; import neqsim.processSimulation.processEquipment.ProcessEquipmentInterface; import neqsim.processSimulation.processEquipment.stream.Stream; /** * <p> * SetPoint class. * </p> * * @author Even Solbraa * @version $Id: $Id */ public class SetPoint extends ProcessEquipmentBaseClass { private static final long serialVersionUID = 1000; ProcessEquipmentInterface sourceEquipment = null, targetEquipment = null; String sourceVarialble = "", targetVariable = "", targetPhase = "", targetComponent = ""; double targetValue = 0.0; String targetUnit = ""; double inputValue = 0.0, oldInputValue = 0.0; static Logger logger = LogManager.getLogger(SetPoint.class); /** * <p> * Constructor for SetPoint. * </p> */ public SetPoint() {} /** * <p> * Constructor for SetPoint. * </p> * * @param name a {@link java.lang.String} object */ public SetPoint(String name) { super(name); } /** * <p> * Constructor for SetPoint. * </p> * * @param name a {@link java.lang.String} object * @param targetEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param targetVariable a {@link java.lang.String} object * @param sourceEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object */ public SetPoint(String name, ProcessEquipmentInterface targetEquipment, String targetVariable, ProcessEquipmentInterface sourceEquipment) { this.targetEquipment = targetEquipment; this.targetVariable = targetVariable; this.sourceEquipment = sourceEquipment; run(); } /** * <p> * setSourceVariable. * </p> * * @param adjustedEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param adjstedVariable a {@link java.lang.String} object */ public void setSourceVariable(ProcessEquipmentInterface adjustedEquipment, String adjstedVariable) { this.sourceEquipment = adjustedEquipment; this.sourceVarialble = adjstedVariable; } /** * <p> * setSourceVariable. * </p> * * @param adjustedEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object */ public void setSourceVariable(ProcessEquipmentInterface adjustedEquipment) { this.sourceEquipment = adjustedEquipment; } /** * <p> * Setter for the field <code>targetVariable</code>. * </p> * * @param targetEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param targetVariable a {@link java.lang.String} object * @param targetValue a double * @param targetUnit a {@link java.lang.String} object */ public void setTargetVariable(ProcessEquipmentInterface targetEquipment, String targetVariable, double targetValue, String targetUnit) { this.targetEquipment = targetEquipment; this.targetVariable = targetVariable; this.targetValue = targetValue; this.targetUnit = targetUnit; } /** * <p> * Setter for the field <code>targetVariable</code>. * </p> * * @param targetEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param targetVariable a {@link java.lang.String} object */ public void setTargetVariable(ProcessEquipmentInterface targetEquipment, String targetVariable) { this.targetEquipment = targetEquipment; this.targetVariable = targetVariable; } /** * <p> * Setter for the field <code>targetVariable</code>. * </p> * * @param targetEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param targetVariable a {@link java.lang.String} object * @param targetValue a double * @param targetUnit a {@link java.lang.String} object * @param targetPhase a {@link java.lang.String} object */ public void setTargetVariable(ProcessEquipmentInterface targetEquipment, String targetVariable, double targetValue, String targetUnit, String targetPhase) { this.targetEquipment = targetEquipment; this.targetVariable = targetVariable; this.targetValue = targetValue; this.targetUnit = targetUnit; this.targetPhase = targetPhase; } /** * <p> * Setter for the field <code>targetVariable</code>. * </p> * * @param targetEquipment a * {@link neqsim.processSimulation.processEquipment.ProcessEquipmentInterface} object * @param targetVariable a {@link java.lang.String} object * @param targetValue a double * @param targetUnit a {@link java.lang.String} object * @param targetPhase a {@link java.lang.String} object * @param targetComponent a {@link java.lang.String} object */ public void setTargetVariable(ProcessEquipmentInterface targetEquipment, String targetVariable, double targetValue, String targetUnit, String targetPhase, String targetComponent) { this.targetEquipment = targetEquipment; this.targetVariable = targetVariable; this.targetValue = targetValue; this.targetUnit = targetUnit; this.targetPhase = targetPhase; this.targetComponent = targetComponent; } /** * <p> * runTransient. * </p> */ public void runTransient() { run(); } /** {@inheritDoc} */ @Override public void run() { if (targetVariable.equals("pressure")) { targetEquipment.setPressure(sourceEquipment.getPressure()); } else { inputValue = ((Stream) sourceEquipment).getThermoSystem().getNumberOfMoles(); double targetValueCurrent = ((Stream) targetEquipment).getThermoSystem().getVolume(targetUnit); double deviation = targetValue - targetValueCurrent; logger.info("adjuster deviation " + deviation + " inputValue " + inputValue); oldInputValue = inputValue; } } /** {@inheritDoc} */ @Override public void displayResult() {} /** * <p> * main. * </p> * * @param args an array of {@link java.lang.String} objects */ public static void main(String[] args) { // test code for adjuster... neqsim.thermo.system.SystemInterface testSystem = new neqsim.thermo.system.SystemSrkEos((273.15 + 25.0), 20.00); testSystem.addComponent("methane", 1000.00); testSystem.createDatabase(true); testSystem.setMixingRule(2); Stream stream_1 = new Stream("Stream1", testSystem); SetPoint adjuster1 = new SetPoint(); adjuster1.setSourceVariable(stream_1, "molarFlow"); adjuster1.setTargetVariable(stream_1, "gasVolumeFlow", 10.0, "", "MSm3/day"); neqsim.processSimulation.processSystem.ProcessSystem operations = new neqsim.processSimulation.processSystem.ProcessSystem(); operations.add(stream_1); operations.add(adjuster1); operations.run(); } }
33.160173
99
0.651697
5cb1f28d4c087edf4b1fbe24b1c7f7faaee84bfe
6,305
package lumien.randomthings.tileentity; import java.util.List; import com.google.common.base.Predicate; import lumien.randomthings.block.ModBlocks; import lumien.randomthings.lib.IEntityFilterItem; import lumien.randomthings.util.InventoryUtil; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.IMob; import net.minecraft.entity.passive.IAnimals; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.math.AxisAlignedBB; public class TileEntityEntityDetector extends TileEntityBase implements ITickable { boolean powered; int rangeX = 5; int rangeY = 5; int rangeZ = 5; boolean invert; boolean strongOutput; static final int MAX_RANGE = 10; FILTER filter = FILTER.ALL; InventoryBasic filterInventory; public TileEntityEntityDetector() { filterInventory = new InventoryBasic("tile.entityDetector", false, 1); } public enum FILTER { ALL("all", Entity.class), LIVING("living", EntityLivingBase.class), ANIMAL("animal", IAnimals.class), MONSTER("monster", IMob.class), PLAYER("player", EntityPlayer.class), ITEMS("item", EntityItem.class), CUSTOM("custom", null); String languageKey; Class filterClass; private FILTER(String languageKey, Class filterClass) { this.languageKey = "gui.entityDetector.filter." + languageKey; this.filterClass = filterClass; } public String getLanguageKey() { return languageKey; } } public boolean strongOutput() { return strongOutput; } public IInventory getInventory() { return filterInventory; } @Override public void update() { if (!this.world.isRemote) { boolean newPowered = checkSupposedPowereredState(); if (newPowered != powered) { powered = newPowered; this.syncTE(); if (!strongOutput) { this.world.notifyNeighborsOfStateChange(pos, ModBlocks.entityDetector, false); } else { this.world.notifyNeighborsOfStateChange(pos, ModBlocks.entityDetector, false); for (EnumFacing facing : EnumFacing.VALUES) { this.world.notifyNeighborsOfStateChange(this.pos.offset(facing), ModBlocks.entityDetector, false); } } } } } public void cycleFilter() { int index = filter.ordinal(); index++; if (index < FILTER.values().length) { filter = FILTER.values()[index]; } else { filter = FILTER.values()[0]; } syncTE(); } private boolean checkSupposedPowereredState() { List<Entity> entityList = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(this.pos, this.pos.add(1, 1, 1)).grow(rangeX, rangeY, rangeZ), new FilterPredicate(filter.filterClass, filterInventory.getStackInSlot(0))); return !invert == (entityList != null && entityList.size() > 0); } @Override public void writeDataToNBT(NBTTagCompound compound, boolean sync) { compound.setBoolean("powered", powered); compound.setInteger("rangeX", rangeX); compound.setInteger("rangeY", rangeY); compound.setInteger("rangeZ", rangeZ); compound.setInteger("filter", filter.ordinal()); compound.setBoolean("invert", invert); compound.setBoolean("strongOutput", strongOutput); NBTTagCompound inventoryCompound = new NBTTagCompound(); InventoryUtil.writeInventoryToCompound(inventoryCompound, filterInventory); compound.setTag("inventory", inventoryCompound); } @Override public void readDataFromNBT(NBTTagCompound compound, boolean sync) { powered = compound.getBoolean("powered"); rangeX = compound.getInteger("rangeX"); rangeY = compound.getInteger("rangeY"); rangeZ = compound.getInteger("rangeZ"); filter = FILTER.values()[compound.getInteger("filter")]; invert = compound.getBoolean("invert"); strongOutput = compound.getBoolean("strongOutput"); NBTTagCompound inventoryCompound = compound.getCompoundTag("inventory"); if (inventoryCompound != null) { InventoryUtil.readInventoryFromCompound(inventoryCompound, filterInventory); } } public boolean isPowered() { return powered; } public int getRangeX() { return rangeX; } public void setRangeX(int rangeX) { this.rangeX = rangeX; if (this.rangeX < 0) { this.rangeX = 0; } else if (this.rangeX > MAX_RANGE) { this.rangeX = MAX_RANGE; } this.syncTE(); } public int getRangeY() { return rangeY; } public void setRangeY(int rangeY) { this.rangeY = rangeY; if (this.rangeY < 0) { this.rangeY = 0; } else if (this.rangeY > MAX_RANGE) { this.rangeY = MAX_RANGE; } this.syncTE(); } public int getRangeZ() { return rangeZ; } public void setRangeZ(int rangeZ) { this.rangeZ = rangeZ; if (this.rangeZ < 0) { this.rangeZ = 0; } else if (this.rangeZ > MAX_RANGE) { this.rangeZ = MAX_RANGE; } this.syncTE(); } public void toggleInvert() { invert = !invert; this.syncTE(); } public boolean invert() { return invert; } public FILTER getFilter() { return filter; } private class FilterPredicate implements Predicate<Entity> { Class filterClass; ItemStack filterItem; IEntityFilterItem filterInstance; public FilterPredicate(Class filterClass, ItemStack filterItem) { this.filterClass = filterClass; this.filterItem = filterItem; if (!filterItem.isEmpty() && filterItem.getItem() instanceof IEntityFilterItem) { this.filterInstance = (IEntityFilterItem) filterItem.getItem(); } } @Override public boolean apply(Entity input) { if (filterClass == null && filterInstance == null) { return false; } return filterClass == null ? filterInstance.apply(filterItem, input) : filterClass.isAssignableFrom(input.getClass()); } } public void toggleStrongOutput() { this.strongOutput = !this.strongOutput; this.syncTE(); this.world.notifyNeighborsOfStateChange(pos, ModBlocks.entityDetector, false); for (EnumFacing facing : EnumFacing.VALUES) { this.world.notifyNeighborsOfStateChange(this.pos.offset(facing), ModBlocks.entityDetector, false); } } }
21.228956
230
0.719905
51c210304f46739cab114f620f31359f5c700814
918
package com.roy.algorithm.inflearn.retry2.dynamic; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; // 최대 부분 증가수열(LIS) // // N개의 자연수로 이루어진 수열이 주어졌을 때, 그 중에서 가장 길게 증가하는(작은 수에서 큰 수로) 원소들의 집합을 찾는 프로그램을 작성하라. // 예를 들어, 원소가 2, 7, 5, 8, 6, 4, 7, 12, 3 이면 가장 길게 증가하도록 원소들을 차례대로 뽑아내면 // 2, 5, 6, 7, 12를 뽑아내어 길이가 5인 최대 부분 증가수열을 만들 수 있다. // - 입력설명 // 첫째 줄은 입력되는 데이터의 수 N(3≤N≤1,000, 자연수)를 의미하고, 둘째 줄은 N개의 입력데이터들이 주어진다. // - 출력설명 // 첫 번째 줄에 부분증가수열의 최대 길이를 출력한다. // - 입력예제 1 // 8 // 5 3 7 8 6 2 9 4 // - 출력예제 1 // 4 // - 해설 // dynamics는 inputs에 있는 수까지의 최대 증가를 기록한다. @SuppressWarnings("NewClassNamingConvention") public class MaxIncreaseNumbers { @Test @DisplayName("최대 부분 증가수열") public void main() { int[] inputs1 = {5, 3, 7, 8, 6, 2, 9, 4}; int expectedAnswer1 = 4; // int answer1 = solution1(inputs1); // assertEquals(expectedAnswer1, answer1); } }
26.228571
82
0.626362
fc69a6c28a9a67c4f9aaea2f52ece700a7e77492
504
class NumArray { int[] dp; public NumArray(int[] nums) { int len = nums.length; dp = new int[len + 1]; dp[0] = 0; for(int i = 1; i <= len; i++) { dp[i] = dp[i - 1] + nums[i - 1]; } } public int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } } /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */ © 2018 GitHub, Inc.
21
64
0.492063
1c7641dd4f50ed8d23545229dff253a27af599bb
1,120
package udemy39; import java.util.Scanner; public class Udemy39 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String dia; System.out.println("Digite o numero para equivaler ao dia da semana"); int x; x = sc.nextInt(); switch (x){ case 1 : dia = "domingo"; break; case 2 : dia = "segunda"; break; case 3 : dia = "terça"; break; case 4 : dia = "quarta"; break; case 5 : dia = "quinta"; break; case 6 : dia = "sexta"; break; case 7 : dia = "sábado"; break; default : dia = "valor invalido"; break; } System.out.println("O Numero equivale a : " + dia ); } }
21.960784
78
0.349107
af8eb058e5a005f779dda92450e3e1ec6859eb1b
239
package com.zb.shardingjdbc.service; import com.zb.shardingjdbc.domain.User; /** * <p> * 服务类 * </p> * * @author zhangbo * @since 2020-02-08 */ public interface IUserService { User get(Long id); void save(User user); }
11.95
39
0.631799
b39d5efd08725d8e4fcab0c0505ab1d03cc6c3e0
346
package com.hanzhan.tech.workbench.candidate.service; import com.hanzhan.tech.workbench.candidate.entity.HzCandidate; import com.baomidou.mybatisplus.extension.service.IService; /** * @Description: 候选人表 * @Author: jeecg-boot * @Date: 2021-09-18 * @Version: V1.0 */ public interface IHzCandidateService extends IService<HzCandidate> { }
23.066667
68
0.765896
3e5d65cb5674e5e1409b86ceaccf2f7ef7806f35
3,792
package controllers; import com.avaje.ebean.Ebean; import helpers.GoogleRecaptcha; import models.Email; import models.ErrorLog; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import play.Logger; import play.Play; import play.data.DynamicForm; import play.data.Form; import play.libs.ws.WSClient; import play.mvc.Controller; import play.mvc.Result; import views.html.newMain; import javax.inject.Inject; /** * Created by gordan.masic on 05/10/15. */ public class Emails extends Controller { private static Form<Email> mailForm1 = Form.form(Email.class); @Inject WSClient ws; public Result sendMail() { DynamicForm mailForm = Form.form().bindFromRequest(); String userName = mailForm.get("name"); String mail = mailForm.get("mail"); String subject = mailForm.get("subject"); String message = mailForm.get("message"); String recaptcha = mailForm.get("g-recaptcha-response"); Boolean verify = GoogleRecaptcha.verifyGoogleRecaptcha(ws, recaptcha); if (verify) { SimpleEmail email = new SimpleEmail(); email.setHostName(Play.application().configuration().getString("smtp.host")); email.setSmtpPort(587); try { email.setFrom(Play.application().configuration().getString("mailFrom")); email.setAuthentication(Play.application().configuration().getString("mailFromPass"), Play.application().configuration().getString("mail.smtp.pass")); email.setStartTLSEnabled(true); email.setDebug(true); email.addTo(Play.application().configuration().getString("mail.smtp.user")); email.setSubject(subject); email.setMsg(userName + "\n" + mail + "\n\n"+subject +"\n" + message); email.send(); } catch (EmailException e) { Ebean.save(new ErrorLog(e.getMessage())); e.printStackTrace(); } return redirect(routes.Application.index()); } else { flash("error", "Not validated"); return redirect(routes.Application.index()); } } @Inject WSClient wsU; public Result sendUserMail() { DynamicForm mailForm = Form.form().bindFromRequest(); String userName = mailForm.get("name"); String mail = mailForm.get("mail"); String subject = mailForm.get("subject"); String message = mailForm.get("message"); String recaptcha = mailForm.get("g-recaptcha-response"); Boolean verify = GoogleRecaptcha.verifyGoogleRecaptcha(wsU, recaptcha); if (verify) { SimpleEmail email = new SimpleEmail(); email.setHostName(Play.application().configuration().getString("smtp.host")); email.setSmtpPort(587); try { email.setFrom(Play.application().configuration().getString("mailFrom")); email.setAuthentication(Play.application().configuration().getString("mailFromPass"), Play.application().configuration().getString("mail.smtp.pass")); email.setStartTLSEnabled(true); email.setDebug(true); email.addTo(Play.application().configuration().getString("mail.smtp.user")); email.setSubject(subject); email.setMsg(userName + "\n" + mail + "\n\n"+subject +"\n" + message); email.send(); } catch (EmailException e) { Ebean.save(new ErrorLog(e.getMessage())); e.printStackTrace(); } return redirect("/"); } else { flash("error", "Not validated"); return redirect("/"); } } }
38.693878
166
0.609968
d036333001f0afb3a587f7660659aeb7d7d48e58
211
package com.bob.sina_weibo.util; public interface Constant { public static final String APPKEY= "19870586"; public static final String REDIRECTURL= "https://api.weibo.com/oauth2/default.html"; }
26.375
85
0.729858
0975ef26ac619876fc2f35e66074300d406c458d
7,089
package com.example.teamtracker.repositories; import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import com.example.teamtracker.network.APIClient; import com.example.teamtracker.network.request.LoginRequestModel; import com.example.teamtracker.network.request.RegisterRequestModel; import com.example.teamtracker.network.response.GoogleLoginResponseModel; import com.example.teamtracker.network.response.RegisterResponseModel; import com.example.teamtracker.network.response.UserDetailsResponseModel; import com.example.teamtracker.network.response.UserResponseModel; import com.example.teamtracker.network.service.AuthService; import com.example.teamtracker.network.response.GoogleOAuthLoginResponseModel; import com.example.teamtracker.util.SharedRefs; import retrofit2.Call; import retrofit2.Callback; public class AuthRepository { private AuthService authService; SharedRefs sharedRefs; public AuthRepository(Context context) { authService = APIClient.getInstance().create(AuthService.class); sharedRefs = new SharedRefs(context); } public LiveData<Boolean> login(String username, String password) { MutableLiveData<Boolean> isLoginSuccessful = new MutableLiveData<>(); authService.login(new LoginRequestModel(username, password)).enqueue(new Callback<retrofit2.Response<Void>>() { @Override public void onResponse(Call<retrofit2.Response<Void>> call, retrofit2.Response<retrofit2.Response<Void>> response) { if (response.code() == 200) { String accessToken = response.headers().get(SharedRefs.AUTHORIZATION); authService.getUserDetails(accessToken).enqueue(new Callback<UserDetailsResponseModel>() { @Override public void onResponse(Call<UserDetailsResponseModel> call, retrofit2.Response<UserDetailsResponseModel> response) { if (response.code() == 200) { UserDetailsResponseModel userDetailsResponseModel = response.body(); UserResponseModel user = userDetailsResponseModel.getUser(); sharedRefs.putString(SharedRefs.ACCESS_TOKEN, accessToken); sharedRefs.putString(SharedRefs.USER_NAME, user.getName()); sharedRefs.putString(SharedRefs.USER_EMAIL, user.getEmail()); sharedRefs.putString(SharedRefs.USER_ID, String.valueOf(user.getId())); isLoginSuccessful.setValue(true); } else { isLoginSuccessful.setValue(false); } } @Override public void onFailure(Call<UserDetailsResponseModel> call, Throwable t) { isLoginSuccessful.setValue(false); } }); } else { isLoginSuccessful.setValue(false); } } @Override public void onFailure(Call<retrofit2.Response<Void>> call, Throwable t) { t.printStackTrace(); isLoginSuccessful.setValue(false); } }); return isLoginSuccessful; } public LiveData<Boolean> googleOAuthLogin(GoogleLoginResponseModel googleLoginResponseModel) { MutableLiveData<Boolean> isLoginSuccessful = new MutableLiveData<>(); authService.googleOAuthLogin(googleLoginResponseModel.getIdToken()).enqueue(new Callback<GoogleOAuthLoginResponseModel>() { @Override public void onResponse(Call<GoogleOAuthLoginResponseModel> call, retrofit2.Response<GoogleOAuthLoginResponseModel> response) { GoogleOAuthLoginResponseModel googleOAuthLoginResponseModel = response.body(); String status = googleOAuthLoginResponseModel.getStatus(); if (status.equals("OK")) { String accessToken = googleOAuthLoginResponseModel.getAccessToken(); authService.getUserDetails(accessToken).enqueue(new Callback<UserDetailsResponseModel>() { @Override public void onResponse(Call<UserDetailsResponseModel> call, retrofit2.Response<UserDetailsResponseModel> response) { if (response.code() == 200) { UserDetailsResponseModel userDetailsResponseModel = response.body(); UserResponseModel user = userDetailsResponseModel.getUser(); sharedRefs.putString(SharedRefs.ACCESS_TOKEN, accessToken); sharedRefs.putString(SharedRefs.USER_NAME, user.getName()); sharedRefs.putString(SharedRefs.USER_EMAIL, user.getEmail()); sharedRefs.putString(SharedRefs.USER_ID, String.valueOf(user.getId())); isLoginSuccessful.setValue(true); } else { isLoginSuccessful.setValue(false); } } @Override public void onFailure(Call<UserDetailsResponseModel> call, Throwable t) { isLoginSuccessful.setValue(false); } }); } else { isLoginSuccessful.setValue(false); } } @Override public void onFailure(Call<GoogleOAuthLoginResponseModel> call, Throwable t) { isLoginSuccessful.setValue(false); } }); return isLoginSuccessful; } public LiveData<Boolean> register(String name, String email, String password) { MutableLiveData<Boolean> isRegistrationSuccessful = new MutableLiveData<>(); authService.register(new RegisterRequestModel(name, email, password)).enqueue(new Callback<RegisterResponseModel>() { @Override public void onResponse(Call<RegisterResponseModel> call, retrofit2.Response<RegisterResponseModel> response) { RegisterResponseModel registerResponseModel = response.body(); String status = registerResponseModel.getStatus(); if (status.equals("OK")) { isRegistrationSuccessful.setValue(true); } else { isRegistrationSuccessful.setValue(false); } } @Override public void onFailure(Call<RegisterResponseModel> call, Throwable t) { isRegistrationSuccessful.setValue(false); } }); return isRegistrationSuccessful; } }
50.276596
140
0.599661
04ed7a03236e1e815bd573a19997992c4162fb89
2,015
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.applicationinsights.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.applicationinsights.models.ApplicationInsightsComponent; import java.util.HashMap; import java.util.Map; /** Samples for Components UpdateTags. */ public final class ComponentsUpdateTagsSamples { /* * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2018-05-01-preview/examples/ComponentsUpdateTagsOnly.json */ /** * Sample code: ComponentUpdateTagsOnly. * * @param manager Entry point to ApplicationInsightsManager. */ public static void componentUpdateTagsOnly( com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) { ApplicationInsightsComponent resource = manager .components() .getByResourceGroupWithResponse("my-resource-group", "my-component", Context.NONE) .getValue(); resource .update() .withTags( mapOf( "ApplicationGatewayType", "Internal-Only", "BillingEntity", "Self", "Color", "AzureBlue", "CustomField_01", "Custom text in some random field named randomly", "NodeType", "Edge")) .apply(); } @SuppressWarnings("unchecked") private static <T> Map<String, T> mapOf(Object... inputs) { Map<String, T> map = new HashMap<>(); for (int i = 0; i < inputs.length; i += 2) { String key = (String) inputs[i]; T value = (T) inputs[i + 1]; map.put(key, value); } return map; } }
35.350877
162
0.593548
65b20b5f2edf58024dbf4574d772861ad978228e
2,580
package com.example.multiple_spinner; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @BindView(R.id.textView) TextView mText; @BindView(R.id.sp1) Spinner mSp1; @BindView(R.id.sp2) Spinner mSp2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); initSpinner(); } private void initSpinner() { mSp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selected = parent.getItemAtPosition(position).toString(); Log.d(TAG, "SP1 SELECTED ITEM : " + selected); if (selected == null) { return ; } int sp2Id = getResources().getIdentifier("sp2_" + selected + "_data", "array", getPackageName()); if (sp2Id == 0) { Log.e(TAG, "ERROR: sp2Id == null"); return; } mSp2.setAdapter(instanceAdapter(sp2Id)); mSp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mText.setText(parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private ArrayAdapter<String> instanceAdapter(int spId) { ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, getResources().getStringArray(spId)); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } }
31.851852
113
0.607364
295fa8225f5bb3d25842b0dc3aa77af7ff9f0cc7
4,239
package org.gw4e.eclipse.conversion; /*- * #%L * gw4e * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2017 gw4e-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 java.util.List; public abstract class JUnitTestMethodExtension extends MethodExtension { /** * @param methodName * @param startElement * @param targetVertex */ public JUnitTestMethodExtension(String classname,List<String> additionalContexts,String methodName,String startElement) { super(classname,additionalContexts,methodName,startElement); } /* (non-Javadoc) * @see org.gw4e.eclipse.conversion.MethodExtension#getImportedClasses() */ public String[] getImportedClasses() { String[] deflt = new String[] { org.junit.Test.class.getName(), org.graphwalker.core.machine.Context.class.getName(), org.graphwalker.java.test.TestBuilder.class.getName(), org.graphwalker.java.test.Result.class.getName(), java.io.IOException.class.getName(), }; String[] imports = getImportsForMethod(); String[] ret = new String[deflt.length+imports.length]; System.arraycopy(deflt,0, ret,0, deflt.length); System.arraycopy(imports, 0, ret, deflt.length, imports.length); return ret; } /* (non-Javadoc) * @see org.gw4e.eclipse.conversion.MethodExtension#getImports() */ protected abstract String[] getImportsForMethod(); /* (non-Javadoc) * @see org.gw4e.eclipse.conversion.MethodExtension#getStaticImportedClasses() */ public String [] getStaticImportedClasses () { return new String [] { org.junit.Assert.class.getName(), }; } /** * @return */ protected abstract String getMainSetPathGeneratorCall (); protected String getAdditionaAddContextCall (String classname,String pathgenerator) { return "builder.addContext(new "+ classname + "().setPathGenerator(" + pathgenerator + "), " + classname + ".MODEL_PATH" + ");"; } /** * @return */ protected abstract String getPathgenerator (); /* (non-Javadoc) * @see org.gw4e.eclipse.preferences.MethodExtension#getSource() */ @Override public String getSource(String [] additionalContext, String value) { String newline = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer (); sb.append("@Test ").append(newline); sb.append("public void "+ this.getName() + "() throws IOException {").append(newline); sb.append(" Context context = new " + getClassname() + "();").append(newline); sb.append(" TestBuilder builder = new TestBuilder().addContext(context,MODEL_PATH,"+ getMainSetPathGeneratorCall () + ");").append(newline); if (startElement!=null && startElement.trim().length() >0 ) { sb.append("context.setNextElement(context.getModel().findElements(\"" + startElement + "\").get(0));").append(newline); } for (int i = 0; i < additionalContext.length; i++) { sb.append(getAdditionaAddContextCall (getSimplifiedClassName(additionalContext[i]),getPathgenerator ())).append(newline); } sb.append(" Result result = builder.execute();").append(newline); sb.append(" Assert.assertFalse(result.hasErrors());").append(newline); sb.append("}").append(newline); return sb.toString(); } }
34.463415
145
0.711017
5aae21b239d2d92a09f9f1c179150fdaadbccb65
4,673
/** * */ package com.photo.pgm.core.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; import org.json.JSONObject; import com.photo.bas.core.model.common.Department; import com.photo.bas.core.model.entity.AbsCodeNameEntity; import com.photo.bas.core.utils.FormatUtils; /** * @author FengYu * */ @Entity @Table(schema = "project") @Audited public class Asset extends AbsCodeNameEntity { private static final long serialVersionUID = -2900988957035948110L; private Integer seq = new Integer(0); // 序号 @ManyToOne(fetch = FetchType.LAZY) @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private PetrolStation petrolStation; // 工程管理-油站信息 @ManyToOne @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private Contract contract; // 合同信息 @ManyToOne @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private AssetsCategory assetsCategory; // 资产类别 @ManyToOne @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private Department department; // 资产属于部门 private String brand; // 品牌 private String specification; // 规格 private Integer quantity = new Integer(0); // 数量 @Temporal(TemporalType.TIMESTAMP) @Column(columnDefinition = "timestamp with time zone") private Date qualityPeriod; @ManyToOne(fetch = FetchType.LAZY) @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) private Cooperation vendor; private String sapcode1; // SAP资产类别号 private String sapcode2; // SAP台卡号 @Override public JSONObject toJSONObject() { JSONObject jo = super.toJSONObject(); jo.put("seq", FormatUtils.intValue(seq)); jo.put("contract",contract == null ? "" : FormatUtils.stringValue(contract.getCode())); jo.put("assetsCategory", FormatUtils.stringValue(assetsCategory.getName())); jo.put("brand", FormatUtils.stringValue(brand)); jo.put("specification", FormatUtils.stringValue(specification)); jo.put("quantity", FormatUtils.intValue(quantity)); jo.put("qualityPeriod", FormatUtils.dateValue(qualityPeriod)); jo.put("vendor", FormatUtils.stringValue(vendor == null ? "" : vendor.getName())); jo.put("sapcode1", FormatUtils.stringValue(sapcode1)); jo.put("sapcode2", FormatUtils.stringValue(sapcode2)); jo.put("department", FormatUtils.displayString(department)); return jo; } public Integer getSeq() { return seq; } public void setSeq(Integer seq) { this.seq = seq; } public PetrolStation getPetrolStation() { return petrolStation; } public void setPetrolStation(PetrolStation petrolStation) { this.petrolStation = petrolStation; } public Contract getContract() { return contract; } public void setContract(Contract contract) { this.contract = contract; } public AssetsCategory getAssetsCategory() { return assetsCategory; } public void setAssetsCategory(AssetsCategory assetsCategory) { this.assetsCategory = assetsCategory; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getSpecification() { return specification; } public void setSpecification(String specification) { this.specification = specification; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Date getQualityPeriod() { return qualityPeriod; } public void setQualityPeriod(Date qualityPeriod) { this.qualityPeriod = qualityPeriod; } public Cooperation getVendor() { return vendor; } public void setVendor(Cooperation vendor) { this.vendor = vendor; } public String getSapcode1() { return sapcode1; } public void setSapcode1(String sapcode1) { this.sapcode1 = sapcode1; } public String getSapcode2() { return sapcode2; } public void setSapcode2(String sapcode2) { this.sapcode2 = sapcode2; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } @Override public String getSavePermission() { return null; } @Override public String getDeletePermission() { return null; } }
24.212435
93
0.715386
cbb01ea3627d1b9139e543010849295e854e41a1
1,980
package org.pty4j.web.websocket; import lombok.extern.slf4j.Slf4j; import org.pty4j.web.websocket.mock.MockHandler; import org.pty4j.web.websocket.terminal.TerminalHandler; import org.pty4j.web.websocket.xterm.XtermHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; /** * 作者: lzw<br/> * 创建时间:2017-12-05 21:37 <br/> */ @Configuration @EnableWebSocket @Slf4j public class WebSocketConfig implements WebSocketConfigurer { private final TerminalHandler terminalHandler; private final XtermHandler xtermHandler; private final MockHandler mockHandler; private final WebSocketHandshakeInterceptor webSocketHandshakeInterceptor; @Autowired public WebSocketConfig( TerminalHandler terminalHandler, XtermHandler xtermHandler, MockHandler mockHandler, WebSocketHandshakeInterceptor webSocketHandshakeInterceptor) { this.terminalHandler = terminalHandler; this.xtermHandler = xtermHandler; this.mockHandler = mockHandler; this.webSocketHandshakeInterceptor = webSocketHandshakeInterceptor; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { String[] allowsOrigins = {"*"}; //WebSocket通道 withSockJS()表示开启 SockJs, SockJS 所处理的 URL 是 “http://“ 或 “https://“ 模式,而不是 “ws://“ or “wss://“ registry.addHandler(terminalHandler, "/terminal") .addHandler(xtermHandler, "/socket/xterm") .addHandler(mockHandler, "/socket/mock") .addInterceptors(webSocketHandshakeInterceptor) .setAllowedOrigins(allowsOrigins); // .withSockJS(); } }
39.6
114
0.737879
66ff37e5af2d93ddb806151e3bb93a1c4c87d9b0
11,565
package pl.edu.agh.iosr.surveylance.service.impl; import pl.edu.agh.iosr.surveylance.dao.AnswerDAO; import pl.edu.agh.iosr.surveylance.dao.ComponentDAO; import pl.edu.agh.iosr.surveylance.dao.QuestionDAO; import pl.edu.agh.iosr.surveylance.entities.Component; import pl.edu.agh.iosr.surveylance.entities.Question; import pl.edu.agh.iosr.surveylance.service.ModificationService; import pl.edu.agh.iosr.surveylance.service.QuestionManager; import pl.edu.agh.iosr.surveylance.service.ComponentManager; import pl.edu.agh.iosr.surveylance.service.exceptions.ComponentDoesNotExistException; import java.util.ArrayList; import java.util.List; import java.util.Iterator; /** * Manages components inside survey. * * @author michal * @author kuba */ public class ComponentManagerImpl implements ComponentManager { private ModificationService modificationService; private ComponentDAO componentDAO; private QuestionDAO questionDAO; private AnswerDAO answerDAO; /** * {@inheritDoc} */ @Override public void setComponentDAO(ComponentDAO componentDAO) { this.componentDAO = componentDAO; } /** * {@inheritDoc} */ @Override public void setQuestionDAO(QuestionDAO questionDAO) { this.questionDAO = questionDAO; } /** * {@inheritDoc} */ @Override public void setAnswerDAO(AnswerDAO answerDAO) { this.answerDAO = answerDAO; } /** * {@inheritDoc} */ public void setModificationService( ModificationService modificationService) { this.modificationService = modificationService; } /** * This method set position of component (component will be at the end). * * @param parent parent order component's * * @return maximum postion number */ private int getMaxPosition(Component parent) { return getComponents(parent).size(); } /** * Adjusts position of component inside parent component. All components * that have position equal or greater than <code>position</code> are * moved one place further. * * @param parent parent component's id * @param position expected position of component inside parent * component * * @return adjusted position of the component expected position */ private int adjustPosition(Component parent, int position) { int maxPosition = 0; for (Component child : getComponents(parent)) { if (child.getPosition() != null && child.getPosition() >= position) { child.setPosition(child.getPosition() + 1); child.setModifications(child.getModifications() + 1); componentDAO.update(child); } if (child.getPosition() != null && child.getPosition() > maxPosition) maxPosition = child.getPosition(); } if (maxPosition + 1 < position) position = maxPosition + 1; return position; } /** * {@inheritDoc} */ @Override public Component createComponent(Component parent, int position) { position = adjustPosition(parent, position); Component component = new Component(); component.setPosition(position); component.setParentComponent(parent); componentDAO.create(component); modificationService.markModified(parent); return component; } /** * {@inheritDoc} */ @Override public Component createComponent(Component parent) { return createComponent(parent, getMaxPosition(parent)); } /** * {@inheritDoc} */ @Override public Component createComponent(long parentId) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); if (parent == null) { throw new ComponentDoesNotExistException("Component with id " + parentId + " does not exist in database"); } return createComponent(parent); } /** * {@inheritDoc} */ @Override public Component createComponent(long parentId, int position) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); if (parent == null) { throw new ComponentDoesNotExistException("Component with id " + parentId + " does not exist in database"); } return createComponent(parent, position); } /** * {@inheritDoc} */ @Override public void addComponent(Component parent, Component component, int position) { // mark modified old and new parent if (component.getParentComponent() != null) modificationService.markModified(component.getParentComponent()); modificationService.markModified(parent); position = adjustPosition(parent, position); component.setPosition(position); component.setParentComponent(parent); componentDAO.update(component); } /** * {@inheritDoc} */ @Override public void addComponent(Component parent, Component component) { addComponent(parent, component, getMaxPosition(parent)); } /** * {@inheritDoc} */ @Override public void addComponent(long parentId, long componentId) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); Component component = componentDAO.findById(componentId, false); if (parent != null && component != null) addComponent(parent, component); else { long id; if (parent == null) id = parentId; else id = componentId; throw new ComponentDoesNotExistException("Component with id " + id + " does not exist in database"); } } /** * {@inheritDoc} */ @Override public void addComponent(long parentId, long componentId, int position) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); Component component = componentDAO.findById(componentId, false); if (parent != null && component != null) addComponent(parent, component, position); else { long id; if (parent == null) id = parentId; else id = componentId; throw new ComponentDoesNotExistException("Component with id " + id + " does not exist in database"); } } /** * {@inheritDoc} */ @Override public List<Component> getComponents(Component parent) { if (parent == null) return new ArrayList<Component>(); return componentDAO.findByParent(parent); } /** * {@inheritDoc} */ @Override public List<Component> getComponents(long parentId) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); if (parent == null) { throw new ComponentDoesNotExistException("Component with id " + parentId + " does not exist in database"); } return getComponents(parent); } /** * {@inheritDoc} */ @Override public Component getComponent(Component parent, int position) { Iterator<Component> iterator = getComponents(parent).iterator(); while (iterator.hasNext()) { Component comp = iterator.next(); if (comp.getPosition() != null && comp.getPosition().intValue() == position) return comp; } return null; } /** * {@inheritDoc} */ @Override public Component getComponent(long parentId, int position) throws ComponentDoesNotExistException { Component parent = componentDAO.findById(parentId, false); if (parent == null) { throw new ComponentDoesNotExistException("Component with id " + parentId + " does not exist in database"); } return getComponent(parent, position); } /** * {@inheritDoc} */ @Override public void deleteComponent(Component component) { // delete child components (cascade delete) for (Component child : getComponents(component)) deleteComponent(child); Question question = questionDAO.findByParent(component); // if component is asociated with question - also delete it if (question != null) { question.setParentComponent(null); // to prevent recursive // component delete QuestionManager questionManager = new QuestionManagerImpl(); questionManager.setQuestionDAO(questionDAO); questionManager.setAnswerDAO(answerDAO); questionManager.deleteQuestion(question); } for (Component comp : getComponents(component.getParentComponent())) if (comp.getPosition() != null && comp.getPosition() > component.getPosition()) { comp.setPosition(comp.getPosition() - 1); componentDAO.update(comp); } if (component.getParentComponent() != null) modificationService.markModified(component.getParentComponent()); component.setParentComponent(null); componentDAO.delete(component); } /** * {@inheritDoc} */ @Override public void deleteComponent(long componentId) throws ComponentDoesNotExistException { Component component = componentDAO.findById(componentId, false); if (component != null) deleteComponent(component); else { throw new ComponentDoesNotExistException("Component with id " + componentId + " does not exist in database"); } } /** * {@inheritDoc} */ @Override public void deleteComponent(long parentId, int position) throws ComponentDoesNotExistException { Component component = getComponent(parentId, position); if (component != null) deleteComponent(component); else { throw new ComponentDoesNotExistException("Component with id " + parentId + " does not exist in database"); } } /** * {@inheritDoc} */ @Override public int moveComponent(Component component, int newPosition) { int position = component.getPosition(); if (position == newPosition) return position; if (component.getParentComponent() != null) { long parentId = component.getParentComponent().getId(); int maxPosition = 0; for (Component child : getComponents(parentId)) { if (child.getPosition() != null) if (child.getPosition() > position && child.getPosition() <= newPosition) { child.setPosition(child.getPosition() - 1); child.setModifications(child.getModifications() + 1); componentDAO.update(child); } else if (child.getPosition() < position && child.getPosition() >= newPosition) { child.setPosition(child.getPosition() + 1); child.setModifications(child.getModifications() + 1); componentDAO.update(child); } if (child.getPosition() != null && child.getPosition() > maxPosition) maxPosition = child.getPosition(); } if (maxPosition < newPosition) newPosition = maxPosition; component.setPosition(newPosition); componentDAO.update(component); modificationService.markModified(component); return newPosition; } return -1; } /** * {@inheritDoc} */ @Override public int moveComponent(long componentId, int newPosition) throws ComponentDoesNotExistException { Component component = componentDAO.findById(componentId, false); if (component == null) { throw new ComponentDoesNotExistException("Component with id " + componentId + " does not exist in database"); } return moveComponent(component, newPosition); } /** * {@inheritDoc} */ @Override public Component getRoot(Component component) throws ComponentDoesNotExistException{ return componentDAO.findRootComponent(component); } /** * {@inheritDoc} */ @Override public Component getRoot(long componentId) throws ComponentDoesNotExistException{ return getRoot(componentDAO.findById(componentId, false)); } }
25.7
86
0.685171
65f10de32eea4d94918c86b5d01809a0253d2fe6
852
package com.MyCode.array.ArrayRotation; public class FindElementAfterRotation { public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int[][] ranges = { { 0, 2 }, { 0, 3 } }; int index = 1; System.out.println(findRotation(arr,ranges,rotations,index)); } private static int findRotation(int[] arr, int[][] ranges, int rotations, int index) { for (int i = 0;i<ranges.length;i++) { int left = ranges[i][0]; int right=ranges[i][1]; if(left<=index && right>= index){ if(index==left) index = right; else index--; } } return index; } }
23.666667
90
0.49061
31f07414f3d9d0990b7303653a2d81d58a5587e4
13,398
package com.wukong.servlet.user; import com.mysql.cj.util.StringUtils; import com.wukong.pojo.Role; import com.wukong.pojo.User; import com.wukong.service.role.RoleService; import com.wukong.service.role.RoleServiceImpl; import com.wukong.service.user.UserService; import com.wukong.service.user.UserServiceImpl; import com.wukong.tools.Constants; import com.wukong.tools.PageSupport; import com.alibaba.fastjson.JSONArray; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserServlet extends HttpServlet { /** * Constructor of the object. */ public UserServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); System.out.println("method----> " + method); if(method != null && method.equals("add")){ //增加操作 this.add(request, response); }else if(method != null && method.equals("query")){ this.query(request, response); }else if(method != null && method.equals("getrolelist")){ this.getRoleList(request, response); }else if(method != null && method.equals("ucexist")){ this.userCodeExist(request, response); }else if(method != null && method.equals("deluser")){ this.delUser(request, response); }else if(method != null && method.equals("view")){ this.getUserById(request, response,"userview.jsp"); }else if(method != null && method.equals("modify")){ this.getUserById(request, response,"usermodify.jsp"); }else if(method != null && method.equals("modifyexe")){ this.modify(request, response); }else if(method != null && method.equals("pwdmodify")){ this.getPwdByUserId(request, response); }else if(method != null && method.equals("savepwd")){ this.updatePwd(request, response); } } private void updatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object o = request.getSession().getAttribute(Constants.USER_SESSION); String newpassword = request.getParameter("newpassword"); boolean flag = false; if(o != null && !StringUtils.isNullOrEmpty(newpassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User)o).getId(),newpassword); if(flag){ request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录!"); request.getSession().removeAttribute(Constants.USER_SESSION);//session注销 }else{ request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!"); } }else{ request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败!"); } request.getRequestDispatcher("pwdmodify.jsp").forward(request, response); } private void getPwdByUserId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object o = request.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = request.getParameter("oldpassword"); Map<String, String> resultMap = new HashMap<String, String>(); if(null == o ){//session过期 resultMap.put("result", "sessionerror"); }else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空 resultMap.put("result", "error"); }else{ String sessionPwd = ((User)o).getUserPassword(); if(oldpassword.equals(sessionPwd)){ resultMap.put("result", "true"); }else{//旧密码输入不正确 resultMap.put("result", "false"); } } response.setContentType("application/json"); PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush(); outPrintWriter.close(); } private void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("uid"); String userName = request.getParameter("userName"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String userRole = request.getParameter("userRole"); User user = new User(); user.setId(Integer.valueOf(id)); user.setUserName(userName); user.setGender(Integer.valueOf(gender)); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } user.setPhone(phone); user.setAddress(address); user.setUserRole(Integer.valueOf(userRole)); user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId()); user.setModifyDate(new Date()); UserService userService = new UserServiceImpl(); if(userService.modify(user)){ response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query"); }else{ request.getRequestDispatcher("usermodify.jsp").forward(request, response); } } private void getUserById(HttpServletRequest request, HttpServletResponse response,String url) throws ServletException, IOException { String id = request.getParameter("uid"); if(!StringUtils.isNullOrEmpty(id)){ //调用后台方法得到user对象 UserService userService = new UserServiceImpl(); User user = userService.getUserById(id); request.setAttribute("user", user); request.getRequestDispatcher(url).forward(request, response); } } private void delUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("uid"); Integer delId = 0; try{ delId = Integer.parseInt(id); }catch (Exception e) { // TODO: handle exception delId = 0; } HashMap<String, String> resultMap = new HashMap<String, String>(); if(delId <= 0){ resultMap.put("delResult", "notexist"); }else{ UserService userService = new UserServiceImpl(); if(userService.deleteUserById(delId)){ resultMap.put("delResult", "true"); }else{ resultMap.put("delResult", "false"); } } //把resultMap转换成json对象输出 response.setContentType("application/json"); PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush(); outPrintWriter.close(); } private void userCodeExist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //判断用户账号是否可用 String userCode = request.getParameter("userCode"); HashMap<String, String> resultMap = new HashMap<String, String>(); if(StringUtils.isNullOrEmpty(userCode)){ //userCode == null || userCode.equals("") resultMap.put("userCode", "exist"); }else{ UserService userService = new UserServiceImpl(); User user = userService.selectUserCodeExist(userCode); if(null != user){ resultMap.put("userCode","exist"); }else{ resultMap.put("userCode", "notexist"); } } //把resultMap转为json字符串以json的形式输出 //配置上下文的输出类型 response.setContentType("application/json"); //从response对象中获取往外输出的writer对象 PrintWriter outPrintWriter = response.getWriter(); //把resultMap转为json字符串 输出 outPrintWriter.write(JSONArray.toJSONString(resultMap)); outPrintWriter.flush();//刷新 outPrintWriter.close();//关闭流 } private void getRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Role> roleList = null; RoleService roleService = new RoleServiceImpl(); roleList = roleService.getRoleList(); //把roleList转换成json对象输出 response.setContentType("application/json"); PrintWriter outPrintWriter = response.getWriter(); outPrintWriter.write(JSONArray.toJSONString(roleList)); outPrintWriter.flush(); outPrintWriter.close(); } private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //查询用户列表 String queryUserName = request.getParameter("queryname"); String temp = request.getParameter("queryUserRole"); String pageIndex = request.getParameter("pageIndex"); int queryUserRole = 0; UserService userService = new UserServiceImpl(); List<User> userList = null; //设置页面容量 int pageSize = Constants.pageSize; //当前页码 int currentPageNo = 1; /** * http://localhost:8090/SMBMS/userlist.do * ----queryUserName --NULL * http://localhost:8090/SMBMS/userlist.do?queryname= * --queryUserName ---"" */ System.out.println("queryUserName servlet--------"+queryUserName); System.out.println("queryUserRole servlet--------"+queryUserRole); System.out.println("query pageIndex--------- > " + pageIndex); if(queryUserName == null){ queryUserName = ""; } if(temp != null && !temp.equals("")){ queryUserRole = Integer.parseInt(temp); } if(pageIndex != null){ try{ currentPageNo = Integer.valueOf(pageIndex); }catch(NumberFormatException e){ response.sendRedirect("error.jsp"); } } //总数量(表) int totalCount = userService.getUserCount(queryUserName,queryUserRole); //总页数 PageSupport pages=new PageSupport(); pages.setCurrentPageNo(currentPageNo); pages.setPageSize(pageSize); pages.setTotalCount(totalCount); int totalPageCount = pages.getTotalPageCount(); //控制首页和尾页 if(currentPageNo < 1){ currentPageNo = 1; }else if(currentPageNo > totalPageCount){ currentPageNo = totalPageCount; } userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo, pageSize); request.setAttribute("userList", userList); List<Role> roleList = null; RoleService roleService = new RoleServiceImpl(); roleList = roleService.getRoleList(); request.setAttribute("roleList", roleList); request.setAttribute("queryUserName", queryUserName); request.setAttribute("queryUserRole", queryUserRole); request.setAttribute("totalPageCount", totalPageCount); request.setAttribute("totalCount", totalCount); request.setAttribute("currentPageNo", currentPageNo); request.getRequestDispatcher("userlist.jsp").forward(request, response); } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("add()================"); String userCode = request.getParameter("userCode"); String userName = request.getParameter("userName"); String userPassword = request.getParameter("userPassword"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String userRole = request.getParameter("userRole"); User user = new User(); user.setUserCode(userCode); user.setUserName(userName); user.setUserPassword(userPassword); user.setAddress(address); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } user.setGender(Integer.valueOf(gender)); user.setPhone(phone); user.setUserRole(Integer.valueOf(userRole)); user.setCreationDate(new Date()); user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId()); UserService userService = new UserServiceImpl(); if(userService.add(user)){ response.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query"); }else{ request.getRequestDispatcher("useradd.jsp").forward(request, response); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
34.530928
96
0.703015
06385952d56af8667fabef3cb3633e58ff484601
1,368
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecordEBranchProductionIssueRecord; import javax.validation.Valid; /** * CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecord */ public class CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecord { private CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecordEBranchProductionIssueRecord eBranchProductionIssueRecord = null; /** * Get eBranchProductionIssueRecord * @return eBranchProductionIssueRecord **/ public CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecordEBranchProductionIssueRecord getEBranchProductionIssueRecord() { return eBranchProductionIssueRecord; } public void setEBranchProductionIssueRecord(CREBranchChannelOperatingSessionRequestInputModelEBranchChannelOperatingSessionInstanceRecordEBranchProductionIssueRecord eBranchProductionIssueRecord) { this.eBranchProductionIssueRecord = eBranchProductionIssueRecord; } }
40.235294
199
0.886696
6d1ca66d1910d6b05f6b7f200c79125c97ad9416
25,693
package com.dungeoncrawler.view; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Timer; import com.dungeoncrawler.model.Dungeon; import com.dungeoncrawler.model.Entity; import com.dungeoncrawler.model.entities.*; import java.awt.Shape; import java.util.ArrayList; import java.util.Arrays; public class GameScreen { //PLAYER public EntitySprite player; //ENTITIES public EntitySprite[] entitySprites; Entity[] entities; //DMG visualization BitmapFont font; DamageFontContainer[] dmgContainer; //MAP private Map m; TiledMapRenderer tmr; TiledMap tm; public ArrayList<AnimatedObject> objects; public ArrayList<AnimatedObject> mapItems; public ArrayList<AnimatedObject> doors; // MiniMap ShapeRenderer shapeRenderer; Sprite miniMapContainer; int mapX = 10; int mapY = 310; int gap = 2; int rectWidth = 15; int rectHeight = 10; float alpha = 0.5f; Timer animations; Timer animatePlayer; Timer roomChangeTimer; Timer doorUnlockTimer; int roomChangeAnimationState; boolean roomLoading; boolean unlockDoor; Texture roomChangeTexture; Sprite roomChangeSprite; TextureRegion[][] roomChangeTextureRegion; int roomChangeRow; Player p; HudContainer hc; // Sound public Music music; //Inventory TEST // CONTROLS ArrayList<Button> controls; int mouseX; int mouseY; float animationSpeed = 0.1f; public GameScreen(Dungeon d, float volume) { //CONTROLS entities = d.getCurrentEntities(); //PLAYER Texture[] playerTexture = new Texture[4]; String gender = d.getPlayer().getGender(); playerTexture[0] = new Texture(Gdx.files.internal("sprites/player/player_"+d.getPlayer().getSkin()+"_"+gender+".png")); playerTexture[1] = new Texture(Gdx.files.internal("sprites/player/player_"+d.getPlayer().getSkin()+"_"+gender+".png")); playerTexture[2] = new Texture(Gdx.files.internal("sprites/player/player_"+d.getPlayer().getSkin()+"_"+gender+".png")); playerTexture[3] = new Texture(Gdx.files.internal("sprites/player/player_"+d.getPlayer().getSkin()+"_"+gender+".png")); //DMG visualization font = new BitmapFont(); font.setColor(1, 0, 0, 1); dmgContainer = new DamageFontContainer[10]; player = new EntitySprite(playerTexture, 64, 64); player.update(200, 200); //ENTITIES entitySprites = new EntitySprite[15]; //MAP float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); m = new Map(); Texture[] tempTextures = new Texture[d.getLevel().length]; for(int i = 0; i < tempTextures.length; i++){ int j = i+1; tempTextures[i] = new Texture(Gdx.files.internal("tilesets/tileset_floor_" + j + ".png")); } MapGenerator mg = new MapGenerator(tempTextures); m = mg.generateMap(d); mg.ichWillSpielen(m.getMaps()); shapeRenderer = new ShapeRenderer(); miniMapContainer = new Sprite(new Texture(Gdx.files.internal("sprites/miniMapContainer.png"))); miniMapContainer.setPosition(mapX - 10, mapY - 20); tm = new TiledMap(); tmr = new OrthogonalTiledMapRenderer(tm); music = Gdx.audio.newMusic(Gdx.files.internal("music/gamemusic.mp3")); music.setVolume(volume); music.play(); animations = new Timer(); animations.scheduleTask(new Timer.Task() { @Override public void run() { if(objects != null){ for(AnimatedObject object : objects){ object.updateAnimation(); } } } },0, 0.1f); animatePlayer = new Timer(); animatePlayer.scheduleTask(new Timer.Task() { @Override public void run() { player.updateAnimation(p); for(int i = 0; i < entitySprites.length; i++){ if(entitySprites[i] != null){ entitySprites[i].updateAnimation(entities[i]); } } } }, 0, animationSpeed); //Inventory TEST hc = new HudContainer(); roomChangeTimer = new Timer(); roomLoading = false; roomChangeSprite = new Sprite(); roomChangeRow = 0; roomChangeSprite.setPosition(0f, 0f); roomChangeTimer.scheduleTask(new Timer.Task() { @Override public void run() { if(roomChangeRow >= 9){ roomLoading = false; roomChangeRow = 0; roomChangeTimer.stop(); } else{ roomChangeRow++; } } },0, 0.03f); // CONTROLS controls = new ArrayList(); int hudX = -160; int hudY = 25; controls.add(new Button("sprites/controls/arrowLeft.png", hudX + 0, hudY + 50, 0)); controls.add(new Button("sprites/controls/arrowUp.png", hudX + 50, hudY + 100, 1)); controls.add(new Button("sprites/controls/arrowRight.png", hudX + 100, hudY + 50, 2)); controls.add(new Button("sprites/controls/arrowDown.png", hudX + 50, hudY + 0, 3)); controls.add(new Button("sprites/controls/arrowLeft.png", 550-170, 75, 4)); controls.add(new Button("sprites/controls/arrowUp.png", 600-170, 125, 5)); controls.add(new Button("sprites/controls/arrowRight.png", 650-170, 75, 6)); controls.add(new Button("sprites/controls/arrowDown.png", 600-170, 25, 7)); controls.add(new Button("sprites/controls/pickUp.png", 160-110, 30, 8)); controls.add(new Button("sprites/controls/equip1.png", 160-110, 120, 9)); controls.add(new Button("sprites/controls/drop.png", 160+110, 30, 10)); controls.add(new Button("sprites/controls/equip2.png", 160+110, 120, 11)); controls.add(new Button("sprites/controls/use.png", 600-170, 200, 12)); // INVENTORY controls.add(new Button("sprites/controls/inventorySlot.png", -118, 334, 20)); //0 controls.add(new Button("sprites/controls/inventorySlot.png", -69, 334, 21)); //1 controls.add(new Button("sprites/controls/inventorySlot.png", -144, 282, 22)); //2 controls.add(new Button("sprites/controls/inventorySlot.png", -92, 282, 23)); //3 controls.add(new Button("sprites/controls/inventorySlot.png", -42, 282, 24)); //4 controls.add(new Button("sprites/controls/inventorySlot.png", -144, 231, 25)); //5 controls.add(new Button("sprites/controls/inventorySlot.png", -92, 231, 26)); //6 controls.add(new Button("sprites/controls/inventorySlot.png", -42, 231, 27)); //7 } public void render (SpriteBatch batch, Player p, Entity[] e, int tileX, int tileY, int level, int roomPosX, int roomPosY, OrthographicCamera camera, int[][] miniMap, boolean touch) { shapeRenderer.setProjectionMatrix(camera.combined); entities = e; this.p = p; //playerMoving = (p.getMovementX() != 0 || p.getMovementY() != 0); //setzt player Sprite auf richtige Position player.update((int) p.getxPos(), (int) p.getyPos()); if(p.getMovementX() > 1){ player.setDirection(1); player.updateFlip(); } else if(p.getMovementX() < -1){ player.setDirection(0); player.updateFlip(); } tm = getM().getMaps()[level][roomPosX][roomPosY].getMap(); objects = getM().getMaps()[level][roomPosX][roomPosY].getObjects(); mapItems = getM().getMaps()[level][roomPosX][roomPosY].getMapItems(); doors = getM().getMaps()[level][roomPosX][roomPosY].getDoors(); if(tm != null){ tmr = new OrthogonalTiledMapRenderer(tm); } //MAP tmr.setView(camera); tmr.render(); updateEntitySprites(e); ArrayList<EntitySprite> temp = new ArrayList<>(); for(EntitySprite entity : entitySprites){ if(entity != null){ temp.add(entity); } } EntitySprite[] renderArray = new EntitySprite[temp.size() + 1]; for(int i = 0; i < renderArray.length; i++){ if(i == renderArray.length - 1){ renderArray[i] = player; } else{ renderArray[i] = temp.get(i); } } Arrays.sort(renderArray); //BATCH batch.begin(); for(AnimatedObject object : objects){ object.getSprite().draw(batch); } for(AnimatedObject mapItem : mapItems){ mapItem.getSprite().draw(batch); } for(AnimatedObject door : doors){ door.getSprite().draw(batch); } for(EntitySprite eSprite : renderArray){ eSprite.getSprites()[0].draw(batch); } if(roomLoading == true){ roomChangeSprite.setRegion(roomChangeTextureRegion[0][roomChangeRow]); roomChangeSprite.draw(batch); } for(int x = 0; x < dmgContainer.length; x++){ if(dmgContainer[x] != null){ String text = ""+dmgContainer[x].getValue(); font.draw(batch, text, dmgContainer[x].getCurrentX(), dmgContainer[x].getCurrentY()); } } if(touch) for(Button button : controls){ button.getSprite().draw(batch); } miniMapContainer.draw(batch); batch.end(); Gdx.gl.glEnable(GL20.GL_BLEND); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); for(int i = 0; i < miniMap.length; i++){ for(int j = 0; j < miniMap.length; j++){ // current Room if(i == roomPosX && j == roomPosY){ shapeRenderer.setColor(0, 0.75f, 0, alpha); } // not found else if(miniMap[i][j] == 0){ shapeRenderer.setColor(0, 0, 0, alpha); } // found else if(miniMap[i][j] == 1){ shapeRenderer.setColor(0.2f, 0.2f, 0.2f, alpha); } // visited else if(miniMap[i][j] == 2){ shapeRenderer.setColor(0.5f, 0.5f, 0.5f, alpha); } if(miniMap[i][j] != 0) { shapeRenderer.rect(i * gap + i * rectWidth + mapX, j * gap + j * rectHeight + mapY, rectWidth, rectHeight); shapeRenderer.setColor(Color.RED); } } } shapeRenderer.end(); Gdx.gl.glDisable(GL20.GL_BLEND); // BUTTON HITBOXES /* ShapeRenderer lol = new ShapeRenderer(); lol.setProjectionMatrix(camera.combined); lol.begin(ShapeRenderer.ShapeType.Filled); for(Button button : controls){ lol.rect(button.getxPos(), button.getyPos(), button.getWidth(), button.getHeight()); } lol.circle(mouseX,mouseY,15); lol.end(); */ } public void generateEntitySprites(Entity[] e){ entitySprites = new EntitySprite[15]; for(int i = 0; i < e.length; i++){ generateNewEntitySprite(e[i], i); } } public void generateNewEntitySprite(Entity e, int i){ if(e != null){ Texture[] tx = new Texture[1]; //nimmt entity ID -> 0 = Archer || 1 = Swordsman || 2 = Arrow || 3 = Wizard double g = Math.random(); String gender; if(g >= 0.5){ gender = "m"; } else{ gender = "w"; } switch(e.getId()){ case 0: tx[0] = new Texture("sprites/archer/archer_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 1: tx[0] = new Texture("sprites/swordsman/swordsman_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 2: tx[0] = new Texture("sprites/projectile/arrow.png"); entitySprites[i] = new EntitySprite(tx, 24, 5); break; case 3: tx[0] = new Texture("sprites/wizard/wizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 4: tx[0] = new Texture("sprites/spell/spell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 5: tx[0] = new Texture("sprites/projectile/laser.png"); entitySprites[i] = new EntitySprite(tx, 36, 15); break; case 6: tx[0] = new Texture("sprites/wizard/firewizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 7: tx[0] = new Texture("sprites/spell/firespell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 8: tx[0] = new Texture("sprites/wizard/earthwizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 9: tx[0] = new Texture("sprites/spell/earthspell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 10: tx[0] = new Texture("sprites/swordsman/fireswordsman_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 11: tx[0] = new Texture("sprites/archer/icearcher_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 12: tx[0] = new Texture("sprites/projectile/icearrow.png"); entitySprites[i] = new EntitySprite(tx, 24, 5); break; case 13: tx[0] = new Texture("sprites/archer/firearcher_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 14: tx[0] = new Texture("sprites/projectile/firearrow.png"); entitySprites[i] = new EntitySprite(tx, 24, 5); break; case 15: tx[0] = new Texture("sprites/swordsman/iceswordsman_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 16: tx[0] = new Texture("sprites/wizard/icewizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 17: tx[0] = new Texture("sprites/spell/icespell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 18: tx[0] = new Texture("sprites/wizard/waterwizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 19: tx[0] = new Texture("sprites/spell/waterspell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 20: tx[0] = new Texture("sprites/wizard/healwizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 21: tx[0] = new Texture("sprites/spell/healspell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 22: tx[0] = new Texture("sprites/wizard/naturewizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 23: tx[0] = new Texture("sprites/spell/naturespell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 24: tx[0] = new Texture("sprites/wizard/darkwizard_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 25: tx[0] = new Texture("sprites/spell/darkspell.png"); entitySprites[i] = new EntitySprite(tx, 16, 16); break; case 26: tx[0] = new Texture("sprites/swordsman/darkswordsman_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 27: tx[0] = new Texture("sprites/archer/darkarcher_"+gender+".png"); entitySprites[i] = new EntitySprite(tx, 64, 64); break; case 28: tx[0] = new Texture("sprites/projectile/darkarrow.png"); entitySprites[i] = new EntitySprite(tx, 24, 5); break; } entitySprites[i].update((int) e.getxPos() + 32, (int) e.getyPos() + 32); if(e.getType() == 2){ entitySprites[i].getSprites()[0].setRotation((float) Math.toDegrees(e.getAngle())); } if(e.isToDelete()){ entitySprites[i].setDie(2); } entitySprites[i].updateAnimation(e); } } public void updateEntitySprites(Entity[] e){ for(int i = 0; i < e.length; i++){ if(e[i] != null){ entitySprites[i].update((int) e[i].getxPos(), (int) e[i].getyPos()); } } } public void deleteEntitySprite(int i){ entitySprites[i].getSprites()[0].getTexture().dispose(); entitySprites[i] = null; } public void updateDamageContainer(){ for(int x = 0; x < dmgContainer.length; x++){ if(dmgContainer[x] != null){ if(dmgContainer[x].getCurrentLifetime() >= dmgContainer[x].getLifetime()){ dmgContainer[x] = null; } else{ dmgContainer[x].setCurrentLifetime(dmgContainer[x].getCurrentLifetime() + 1); dmgContainer[x].setCurrentY(dmgContainer[x].getCurrentY() + 1); } } } } public void cleanUp(){ music.dispose(); animations.clear(); animatePlayer.clear(); } public void startLoadingScreen(){ roomChangeSprite = new Sprite(new Texture("sprites/roomChange.png")); roomChangeSprite.setPosition(0,0); roomChangeTextureRegion = roomChangeSprite.split(528,432); roomLoading = true; roomChangeTimer.start(); } public void startUnlockScreen(){ roomChangeSprite = new Sprite(new Texture("sprites/unlock.png")); roomChangeSprite.setPosition(400,400); roomChangeTextureRegion = roomChangeSprite.split(48,64); roomLoading = true; roomChangeTimer.start(); } //GETTER public EntitySprite getPlayer(){ return player; } public boolean getIsLoading(){ return roomLoading; } /** * @return the m */ public Map getM() { return m; } public void stop(){ animations.stop(); animatePlayer.stop(); } public void resume(){ animations.start(); animatePlayer.start(); } public void end(){ animations.stop(); animatePlayer.stop(); cleanUp(); } public void createDmgFont(int value, int startX, int startY){ for(int i = 0; i < dmgContainer.length; i++){ if(dmgContainer[i]== null){ dmgContainer[i] = new DamageFontContainer(value, startX, startY); i = dmgContainer.length + 1; } } } public ArrayList<Integer> click(int x, int y){ x = (int)(((float)x) / (float)Gdx.graphics.getWidth() * 700f) -170; y = 380- (int)(((float)y) / (float)Gdx.graphics.getHeight() * 380f)+ 25; mouseX = x; mouseY = y; ArrayList<Integer> clicks = new ArrayList(); Circle mouse = new Circle(x,y,20); for(Button button : controls){ if(Intersector.overlaps(mouse, button.getSprite().getBoundingRectangle())){ clicks.add(button.getId()); } } return clicks; } }
40.082683
183
0.458841