blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
132 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
0910dd9cdc4b4e22cd703385edd5e1985c53229a
70533af14c57c24c89969e60b0c506aec564cae9
/src/cloud_plugin/testcase/algorithm/videoplanassess/pa_modeling/Volumen_Estimate_AlgorithmCreateTask.java
0fe0bf4c8b08ba8996f18e899d662c0488cd210b
[]
no_license
yangquan1982/AutomationTestFramework1
e393d6ac69b8412a91290e88b2a46d39856ecfcc
bc8faa61dd62a221af2a481e5b0f5d3b7a8200b5
refs/heads/master
2020-03-09T13:07:01.660799
2019-06-13T04:33:48
2019-06-13T04:33:48
128,802,310
2
0
null
null
null
null
UTF-8
Java
false
false
5,791
java
package cloud_plugin.testcase.algorithm.videoplanassess.pa_modeling; import java.util.Arrays; import java.util.Collection; import org.fest.swing.annotation.GUITest; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.openqa.selenium.WebDriver; import cloud_plugin.task.network_performance_analysis_center.network_planning.lte_seq_vmos.SeqVMOSTask; import cloud_public.page.GetDataByTypePage; import cloud_public.page.HomePage; import cloud_public.page.IndexPage; import cloud_public.task.LoginTask; import common.constant.constparameter.ConstUrl; import common.util.CommonWD; import common.util.ParamUtil; @GUITest @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(value = Parameterized.class) public class Volumen_Estimate_AlgorithmCreateTask { private static WebDriver driver = null; private static String defaultWindowID = null; private static String ParaFile = ConstUrl.getProjectHomePath()+"\\Data\\baseline\\02_算法\\参数化\\视频规划与评估\\容量评估前台参数化表.xlsx"; private static String SheetName = "VMOS_算法"; private String secns; private String TestCaseId; private String ProjectName; private String[] TaskType; private String[] CfgData; private String[] ParamData; private String[] SigData; private String[] NonEncryptedVideoSourceData; private String[] EncryptedVideoSourceData; private String[] OTTData; private String[] ElectronicMapData; private String[] LTECharacteristicLibraryData; private String[] PerformanceData; private String VideoTrafficForecastResultFile; private String[] XDR_MRPreprocessData; private String[] CDRData; private String[] UELogsData; private String[] DataPreprocessingSetItems; private String[] DataPreprocessingSetValues; private String[] EvaluationSetItems; private String[] EvaluationSetItemsValues; private String IsIndependentBusyhourKPIs; private String FilteringMode; private String BusyhourKPI; private String[] CustomHours; private String BusyDays; private String LegendSetItem; private String LegendSetSegmentNumber; private String[] LegendSetValue; public Volumen_Estimate_AlgorithmCreateTask(String secns, String testId,String projectName, String[] taskType, String[] cfgData, String[] paramData, String[] sigData, String[] nonEncryptedVideoSourceData, String[] encryptedVideoSourceData, String[] oTTData, String[] electronicMapData, String[] lTECharacteristicLibraryData, String[] performanceData, String videoTrafficForecastResultFile,String[] xDR_MRPreprocessData, String[] cDRData, String[] uELogsData, String[] dataPreprocessingSetItems, String[] dataPreprocessingSetValues, String[] evaluationSetItems, String[] evaluationSetItemsValues, String isIndependentBusyhourKPIs, String filteringMode, String busyhourKPI, String[] customHours, String busyDays, String legendSetItem, String legendSetSegmentNumber, String[] legendSetValue) { this.secns = secns; TestCaseId=testId; ProjectName = projectName; TaskType = taskType; CfgData = cfgData; ParamData = paramData; SigData = sigData; NonEncryptedVideoSourceData = nonEncryptedVideoSourceData; EncryptedVideoSourceData = encryptedVideoSourceData; OTTData = oTTData; ElectronicMapData = electronicMapData; LTECharacteristicLibraryData = lTECharacteristicLibraryData; PerformanceData = performanceData; VideoTrafficForecastResultFile = videoTrafficForecastResultFile; XDR_MRPreprocessData = xDR_MRPreprocessData; CDRData = cDRData; UELogsData = uELogsData; DataPreprocessingSetItems = dataPreprocessingSetItems; DataPreprocessingSetValues = dataPreprocessingSetValues; EvaluationSetItems = evaluationSetItems; EvaluationSetItemsValues = evaluationSetItemsValues; IsIndependentBusyhourKPIs = isIndependentBusyhourKPIs; FilteringMode = filteringMode; BusyhourKPI = busyhourKPI; CustomHours = customHours; BusyDays = busyDays; LegendSetItem = legendSetItem; LegendSetSegmentNumber = legendSetSegmentNumber; LegendSetValue = legendSetValue; } @Parameters() public static Collection<Object[]> data() throws Exception { System.out.print("This is collection"); Collection<Object[]> coll = Arrays.asList(ParamUtil.getObjectArr( ParaFile, SheetName)); return coll; } @BeforeClass public static void setUpBeforeClass() { driver = CommonWD.getWebDriver(); defaultWindowID = driver.getWindowHandle(); LoginTask.login(driver); HomePage.gotoldVersion(driver); IndexPage.OpenNetPerfomanceAnalysisCenter(driver); } @Before public void setUp() { GetDataByTypePage.closeOtherWindows(driver, defaultWindowID); SeqVMOSTask.goBackToNetworkAnalysisCenter(driver); } @After public void tearDown() { // StartBackFillTMSS.backFill(TestCaseId,result); System.out.println("tmss end xx"); } @AfterClass public static void tearDownAfterClass() { driver.quit(); } @Test public void T00_Algorithm_vMOSCreateTask() { SeqVMOSTask.ParamCreateTask(driver, secns, ProjectName, TaskType, CfgData, ParamData, SigData, NonEncryptedVideoSourceData, EncryptedVideoSourceData, OTTData, ElectronicMapData, LTECharacteristicLibraryData, PerformanceData, VideoTrafficForecastResultFile, XDR_MRPreprocessData,CDRData, UELogsData, DataPreprocessingSetItems, DataPreprocessingSetValues, EvaluationSetItems, EvaluationSetItemsValues, IsIndependentBusyhourKPIs, FilteringMode, BusyhourKPI, CustomHours, BusyDays, LegendSetItem, LegendSetSegmentNumber, LegendSetValue); } }
[ "tbg127@gmail.com" ]
tbg127@gmail.com
3b908567ecf666fa87a5182995601c02b7cadfc6
07faadd987a5febb3c6e7180323c2b01e654f3c7
/src/preprocessing/akiba-iwata/src/tc/wata/util/SetOpt.java
23ba175509a8aaa05d8e80a7dece38c022d8d567
[ "MIT", "BSD-3-Clause" ]
permissive
TheoryInPractice/practical-oct
eda454d57e27274c857b874b5526ecf03bfef29e
e57119b26ca7e17d91f12a07cca55bf26e0b5aeb
refs/heads/master
2023-07-23T00:31:11.496517
2020-04-13T19:33:11
2020-04-13T19:33:11
130,571,253
5
0
BSD-3-Clause
2023-07-10T14:15:13
2018-04-22T13:44:23
Python
UTF-8
Java
false
false
6,728
java
package tc.wata.util; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; /** * -ABBR VAL / -ABBRVAL / --NAME VAL / --NAME=VAL という形式の文字列をパースしてOptionアノテーションの指定されたpublicフィールドに値をセットする.<br> * 使える値の種類はint,long,double,boolean,String.<br> * NAMEは曖昧性が無い限り短縮可能. * booleanの場合はデフォルト値を反転させる.<br> * -- から先は全てオプションではない実引数として扱う. */ public class SetOpt { private SetOpt() { } /** * オプションの指定 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Option { /** * 短縮形の名前.指定しない場合短縮形なし. */ char abbr() default 0; /** * オプション名.指定しない場合,変数名がそのまま使われる. */ String name() default ""; /** * 説明文 */ String usage() default ""; /** * 必須かどうか */ boolean required() default false; } /** * 文字列を元に指定された型のオブジェクトを生成. */ public static Object createObject(Class<?> type, String val) { Object obj; if (type == int.class) obj = Integer.parseInt(val); else if (type == long.class) obj = Long.parseLong(val); else if (type == double.class) obj = Double.parseDouble(val); else if (type == boolean.class) obj = Boolean.parseBoolean(val); else if (type == String.class) obj = val; else throw new IllegalArgumentException("Unspported type: " + type); return obj; } private static String getName(Field f) { Option opt = f.getAnnotation(Option.class); if (opt.name() != null && opt.name().length() > 0) return opt.name(); return f.getName(); } private static Field getField(Object obj, String name) { Field res = null; ArrayList<String> list = new ArrayList<>(); if ("help".startsWith(name)) list.add("help"); for (Field f : obj.getClass().getFields()) if (f.isAnnotationPresent(Option.class)) { String id = getName(f); if (id.equals(name)) { return f; } else if (id.startsWith(name)) { list.add(id); res = f; } } if (res == null) { if (list.size() > 0) return null; System.err.printf("No such option: '--%s'%n", name); System.exit(1); } else if (list.size() > 1) { StringBuilder str = new StringBuilder(); for (String s : list) { if (str.length() > 0) str.append(", "); str.append(s); } System.err.printf("Ambiguous option: '--%s' (%s)%n", name, str); System.exit(1); } return res; } private static Field getAbbrField(Object obj, char abbr) { for (Field f : obj.getClass().getDeclaredFields()) if (f.isAnnotationPresent(Option.class)) { Option opt = f.getAnnotation(Option.class); if (opt.abbr() == abbr) { return f; } } System.err.printf("No such option: '-%c'%n" + abbr); System.exit(1); return null; } /** * 引数を元に,オブジェクトのフィールドに値を設定する. * @return オプション以外の引数リストを返す */ public static String[] setOpt(Object obj, String...args) { Set<Field> used = new HashSet<>(); ArrayList<String> ret = new ArrayList<>(); try { for (int i = 0; i < args.length; i++) { String s = args[i]; if (s.equals("--")) { for (int j = i + 1; j < args.length; j++) { ret.add(args[j]); } break; } else if (!s.startsWith("-")) { ret.add(s); } else if (s.startsWith("--")) { String name, val = null; if (s.indexOf('=') >= 0) { name = s.substring(2, s.indexOf('=')); val = s.substring(s.indexOf('=') + 1); } else { name = s.substring(2); } Field f = getField(obj, name); if (f == null) { showUsage(obj); System.exit(1); } else if (f.getType().equals(boolean.class)) { if (val != null) { System.err.printf("The option '--%s' cannot not take arguments%n", name); System.exit(1); } f.set(obj, !(boolean)f.get(obj)); } else { if (val == null) { if (i + 1 >= args.length) { System.err.printf("The option '--%s' requires an argument%n", name); System.exit(1); } val = args[++i]; } try { f.set(obj, createObject(f.getType(), val)); } catch (Exception e) { System.err.printf("Illegal argument for the option '--%s': %s%n", name, val); System.exit(1); } } used.add(f); } else if (s.length() >= 2) { char abbr = s.charAt(1); String val = s.substring(2); Field f = getAbbrField(obj, abbr); if (f == null) { showUsage(obj); System.exit(1); } else if (f.getType().equals(boolean.class)) { if (!val.isEmpty()) { System.err.printf("The option '-%c' cannot not take arguments%n", abbr); System.exit(1); } f.set(obj, !(boolean)f.get(obj)); } else { if (val.isEmpty()) { if (i + 1 >= args.length) { System.err.printf("The option '-%c' requires an argument%n", abbr); System.exit(1); } val = args[++i]; } try { f.set(obj, createObject(f.getType(), val)); } catch (Exception e) { System.err.printf("Illegal argument for the option '-%c': %s%n", abbr, val); System.exit(1); } } used.add(f); } else { System.err.printf("No such option: '-'%n"); System.exit(1); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } for (Field f : obj.getClass().getFields()) if (f.isAnnotationPresent(Option.class)) { Option opt = f.getAnnotation(Option.class); if (opt.required() && !used.contains(f)) { System.err.printf("The required option '--%s' is not specified.%n", getName(f)); System.exit(1); } } return ret.toArray(new String[0]); } /** * Optionアノテーションが付与されたフィールドの一覧を表示する. */ public static void showUsage(Object obj) { try { System.err.println("Options:"); for (Field f : obj.getClass().getFields()) if (f.isAnnotationPresent(Option.class)) { Option opt = f.getAnnotation(Option.class); System.err.print(" "); if (opt.abbr() != 0) System.err.printf("-%c, ", opt.abbr()); else System.err.print(" "); System.err.printf("--%s <%s>(%s)", getName(f), f.getType().getSimpleName(), opt.required() ? "required" : f.get(obj)); System.err.println("\t" + opt.usage()); } System.err.println(" --help\tShow this usage"); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
[ "ewhorton@ncsu.edu" ]
ewhorton@ncsu.edu
f272588d064476cfbde19d1361b35b8e83b1ada7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_329fe79e4ed81113f348c8dc1cf1b2b1198a9dd9/PatchListCacheImpl/11_329fe79e4ed81113f348c8dc1cf1b2b1198a9dd9_PatchListCacheImpl_s.java
d8c363dbf1f115a77254b8831560945b94f91b2b
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
23,940
java
// Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Some portions (e.g. outputDiff) below are: // // Copyright (C) 2009, Christian Halstrick <christian.halstrick@sap.com> // Copyright (C) 2009, Johannes E. Schindelin // Copyright (C) 2009, Johannes Schindelin <johannes.schindelin@gmx.de> // and other copyright owners as documented in the project's IP log. // // This program and the accompanying materials are made available // under the terms of the Eclipse Distribution License v1.0 which // accompanies this distribution, is reproduced below, and is // available at http://www.eclipse.org/org/documents/edl-v10.php // // All rights reserved. // // Redistribution and use in source and binary forms, with or // without modification, are permitted provided that the following // conditions are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // - Neither the name of the Eclipse Foundation, Inc. nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // package com.google.gerrit.server.patch; import com.google.gerrit.reviewdb.Change; import com.google.gerrit.reviewdb.Patch; import com.google.gerrit.reviewdb.PatchSet; import com.google.gerrit.reviewdb.Project; import com.google.gerrit.reviewdb.AccountDiffPreference.Whitespace; import com.google.gerrit.server.cache.Cache; import com.google.gerrit.server.cache.CacheModule; import com.google.gerrit.server.cache.EntryCreator; import com.google.gerrit.server.cache.EvictionPolicy; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.diff.EditList; import org.eclipse.jgit.diff.MyersDiff; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.diff.RawTextIgnoreAllWhitespace; import org.eclipse.jgit.diff.RawTextIgnoreTrailingWhitespace; import org.eclipse.jgit.diff.RawTextIgnoreWhitespaceChange; import org.eclipse.jgit.diff.RenameDetector; import org.eclipse.jgit.diff.ReplaceEdit; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.FileHeader.PatchType; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.util.io.DisabledOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; /** Provides a cached list of {@link PatchListEntry}. */ @Singleton public class PatchListCacheImpl implements PatchListCache { private static final String CACHE_NAME = "diff"; private static final Pattern BLANK_LINE_RE = Pattern.compile("^[ \\t]*(|[{}]|/\\*\\*?|\\*)[ \\t]*$"); private static final Pattern CONTROL_BLOCK_START_RE = Pattern.compile("[{:][ \\t]*$"); public static Module module() { return new CacheModule() { @Override protected void configure() { final TypeLiteral<Cache<PatchListKey, PatchList>> type = new TypeLiteral<Cache<PatchListKey, PatchList>>() {}; disk(type, CACHE_NAME) // .memoryLimit(128) // very large items, cache only a few .evictionPolicy(EvictionPolicy.LRU) // prefer most recent .populateWith(Loader.class) // ; bind(PatchListCacheImpl.class); bind(PatchListCache.class).to(PatchListCacheImpl.class); } }; } private final Cache<PatchListKey, PatchList> cache; @Inject PatchListCacheImpl( @Named(CACHE_NAME) final Cache<PatchListKey, PatchList> thecache) { cache = thecache; } public PatchList get(final PatchListKey key) { return cache.get(key); } public PatchList get(final Change change, final PatchSet patchSet) { return get(change, patchSet, Whitespace.IGNORE_NONE); } public PatchList get(final Change change, final PatchSet patchSet, final Whitespace whitespace) { final Project.NameKey projectKey = change.getProject(); final ObjectId a = null; final ObjectId b = ObjectId.fromString(patchSet.getRevision().get()); return get(new PatchListKey(projectKey, a, b, whitespace)); } static class Loader extends EntryCreator<PatchListKey, PatchList> { private final GitRepositoryManager repoManager; private final boolean computeIntraline; @Inject Loader(GitRepositoryManager mgr, @GerritServerConfig Config config) { repoManager = mgr; computeIntraline = config.getBoolean("cache", "diff", "intraline", true); } @Override public PatchList createEntry(final PatchListKey key) throws Exception { final Repository repo = repoManager.openRepository(key.projectKey.get()); try { return readPatchList(key, repo); } finally { repo.close(); } } private PatchList readPatchList(final PatchListKey key, final Repository repo) throws IOException { // TODO(jeffschu) correctly handle merge commits RawText.Factory rawTextFactory; switch (key.getWhitespace()) { case IGNORE_ALL_SPACE: rawTextFactory = RawTextIgnoreAllWhitespace.FACTORY; break; case IGNORE_SPACE_AT_EOL: rawTextFactory = RawTextIgnoreTrailingWhitespace.FACTORY; break; case IGNORE_SPACE_CHANGE: rawTextFactory = RawTextIgnoreWhitespaceChange.FACTORY; break; case IGNORE_NONE: default: rawTextFactory = RawText.FACTORY; break; } final ObjectReader reader = repo.newObjectReader(); try { final RevWalk rw = new RevWalk(reader); final RevCommit b = rw.parseCommit(key.getNewId()); final RevObject a = aFor(key, repo, rw, b); if (a == null) { // This is a merge commit, compared to its ancestor. // final PatchListEntry[] entries = new PatchListEntry[1]; entries[0] = newCommitMessage(rawTextFactory, repo, reader, null, b); return new PatchList(a, b, computeIntraline, true, entries); } final boolean againstParent = b.getParentCount() > 0 && b.getParent(0) == a; RevCommit aCommit; RevTree aTree; if (a instanceof RevCommit) { aCommit = (RevCommit) a; aTree = aCommit.getTree(); } else if (a instanceof RevTree) { aCommit = null; aTree = (RevTree) a; } else { throw new IOException("Unexpected type: " + a.getClass()); } RevTree bTree = b.getTree(); final TreeWalk walk = new TreeWalk(reader); walk.reset(); walk.setRecursive(true); walk.addTree(aTree); walk.addTree(bTree); walk.setFilter(TreeFilter.ANY_DIFF); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repo); df.setRawTextFactory(rawTextFactory); RenameDetector rd = new RenameDetector(repo); rd.addAll(DiffEntry.scan(walk)); List<DiffEntry> diffEntries = rd.compute(); final int cnt = diffEntries.size(); final PatchListEntry[] entries = new PatchListEntry[1 + cnt]; entries[0] = newCommitMessage(rawTextFactory, repo, reader, // againstParent ? null : aCommit, b); for (int i = 0; i < cnt; i++) { FileHeader fh = df.createFileHeader(diffEntries.get(i)); entries[1 + i] = newEntry(reader, aTree, bTree, fh); } return new PatchList(a, b, computeIntraline, againstParent, entries); } finally { reader.release(); } } private PatchListEntry newCommitMessage( final RawText.Factory rawTextFactory, final Repository db, final ObjectReader reader, final RevCommit aCommit, final RevCommit bCommit) throws IOException { StringBuilder hdr = new StringBuilder(); hdr.append("diff --git"); if (aCommit != null) { hdr.append(" a/" + Patch.COMMIT_MSG); } else { hdr.append(" " + FileHeader.DEV_NULL); } hdr.append(" b/" + Patch.COMMIT_MSG); hdr.append("\n"); if (aCommit != null) { hdr.append("--- a/" + Patch.COMMIT_MSG + "\n"); } else { hdr.append("--- " + FileHeader.DEV_NULL + "\n"); } hdr.append("+++ b/" + Patch.COMMIT_MSG + "\n"); Text aText = aCommit != null ? Text.forCommit(db, reader, aCommit) : Text.EMPTY; Text bText = Text.forCommit(db, reader, bCommit); byte[] rawHdr = hdr.toString().getBytes("UTF-8"); RawText aRawText = rawTextFactory.create(aText.getContent()); RawText bRawText = rawTextFactory.create(bText.getContent()); EditList edits = new MyersDiff(aRawText, bRawText).getEdits(); FileHeader fh = new FileHeader(rawHdr, edits, PatchType.UNIFIED); return newEntry(reader, aText, bText, edits, null, null, fh); } private PatchListEntry newEntry(ObjectReader reader, RevTree aTree, RevTree bTree, FileHeader fileHeader) throws IOException { final FileMode oldMode = fileHeader.getOldMode(); final FileMode newMode = fileHeader.getNewMode(); if (oldMode == FileMode.GITLINK || newMode == FileMode.GITLINK) { return new PatchListEntry(fileHeader, Collections.<Edit> emptyList()); } if (aTree == null // want combined diff || fileHeader.getPatchType() != PatchType.UNIFIED || fileHeader.getHunks().isEmpty()) { return new PatchListEntry(fileHeader, Collections.<Edit> emptyList()); } List<Edit> edits = fileHeader.toEditList(); if (edits.isEmpty()) { return new PatchListEntry(fileHeader, Collections.<Edit> emptyList()); } if (!computeIntraline) { return new PatchListEntry(fileHeader, edits); } switch (fileHeader.getChangeType()) { case ADD: case DELETE: return new PatchListEntry(fileHeader, edits); } return newEntry(reader, null, null, edits, aTree, bTree, fileHeader); } private PatchListEntry newEntry(ObjectReader reader, Text aContent, Text bContent, List<Edit> edits, RevTree aTree, RevTree bTree, FileHeader fileHeader) throws IOException { for (int i = 0; i < edits.size(); i++) { Edit e = edits.get(i); if (e.getType() == Edit.Type.REPLACE) { if (aContent == null) { edits = new ArrayList<Edit>(edits); aContent = read(reader, fileHeader.getOldPath(), aTree); bContent = read(reader, fileHeader.getNewPath(), bTree); combineLineEdits(edits, aContent, bContent); i = -1; // restart the entire scan after combining lines. continue; } CharText a = new CharText(aContent, e.getBeginA(), e.getEndA()); CharText b = new CharText(bContent, e.getBeginB(), e.getEndB()); List<Edit> wordEdits = new MyersDiff(a, b).getEdits(); // Combine edits that are really close together. If they are // just a few characters apart we tend to get better results // by joining them together and taking the whole span. // for (int j = 0; j < wordEdits.size() - 1;) { Edit c = wordEdits.get(j); Edit n = wordEdits.get(j + 1); if (n.getBeginA() - c.getEndA() <= 5 || n.getBeginB() - c.getEndB() <= 5) { int ab = c.getBeginA(); int ae = n.getEndA(); int bb = c.getBeginB(); int be = n.getEndB(); if (canCoalesce(a, c.getEndA(), n.getBeginA()) && canCoalesce(b, c.getEndB(), n.getBeginB())) { wordEdits.set(j, new Edit(ab, ae, bb, be)); wordEdits.remove(j + 1); continue; } } j++; } // Apply some simple rules to fix up some of the edits. Our // logic above, along with our per-character difference tends // to produce some crazy stuff. // for (int j = 0; j < wordEdits.size(); j++) { Edit c = wordEdits.get(j); int ab = c.getBeginA(); int ae = c.getEndA(); int bb = c.getBeginB(); int be = c.getEndB(); // Sometimes the diff generator produces an INSERT or DELETE // right up against a REPLACE, but we only find this after // we've also played some shifting games on the prior edit. // If that happened to us, coalesce them together so we can // correct this mess for the user. If we don't we wind up // with silly stuff like "es" -> "es = Addresses". // if (1 < j) { Edit p = wordEdits.get(j - 1); if (p.getEndA() == ab || p.getEndB() == bb) { if (p.getEndA() == ab && p.getBeginA() < p.getEndA()) { ab = p.getBeginA(); } if (p.getEndB() == bb && p.getBeginB() < p.getEndB()) { bb = p.getBeginB(); } wordEdits.remove(--j); } } // We sometimes collapsed an edit together in a strange way, // such that the edges of each text is identical. Fix by // by dropping out that incorrectly replaced region. // while (ab < ae && bb < be && a.equals(ab, b, bb)) { ab++; bb++; } while (ab < ae && bb < be && a.equals(ae - 1, b, be - 1)) { ae--; be--; } // The leading part of an edit and its trailing part in the same // text might be identical. Slide down that edit and use the tail // rather than the leading bit. If however the edit is only on a // whitespace block try to shift it to the left margin, assuming // that it is an indentation change. // boolean aShift = true; if (ab < ae && isOnlyWhitespace(a, ab, ae)) { int lf = findLF(wordEdits, j, a, ab); if (lf < ab && a.charAt(lf) == '\n') { int nb = lf + 1; int p = 0; while (p < ae - ab) { if (a.equals(ab + p, a, ab + p)) p++; else break; } if (p == ae - ab) { ab = nb; ae = nb + p; aShift = false; } } } if (aShift) { while (0 < ab && ab < ae && a.charAt(ab - 1) != '\n' && a.equals(ab - 1, a, ae - 1)) { ab--; ae--; } if (!a.isLineStart(ab) || !a.contains(ab, ae, '\n')) { while (ab < ae && ae < a.size() && a.equals(ab, a, ae)) { ab++; ae++; if (a.charAt(ae - 1) == '\n') { break; } } } } boolean bShift = true; if (bb < be && isOnlyWhitespace(b, bb, be)) { int lf = findLF(wordEdits, j, b, bb); if (lf < bb && b.charAt(lf) == '\n') { int nb = lf + 1; int p = 0; while (p < be - bb) { if (b.equals(bb + p, b, bb + p)) p++; else break; } if (p == be - bb) { bb = nb; be = nb + p; bShift = false; } } } if (bShift) { while (0 < bb && bb < be && b.charAt(bb - 1) != '\n' && b.equals(bb - 1, b, be - 1)) { bb--; be--; } if (!b.isLineStart(bb) || !b.contains(bb, be, '\n')) { while (bb < be && be < b.size() && b.equals(bb, b, be)) { bb++; be++; if (b.charAt(be - 1) == '\n') { break; } } } } // If most of a line was modified except the LF was common, make // the LF part of the modification region. This is easier to read. // if (ab < ae // && (ab == 0 || a.charAt(ab - 1) == '\n') // && ae < a.size() && a.charAt(ae) == '\n') { ae++; } if (bb < be // && (bb == 0 || b.charAt(bb - 1) == '\n') // && be < b.size() && b.charAt(be) == '\n') { be++; } wordEdits.set(j, new Edit(ab, ae, bb, be)); } edits.set(i, new ReplaceEdit(e, wordEdits)); } } return new PatchListEntry(fileHeader, edits); } private static void combineLineEdits(List<Edit> edits, Text a, Text b) { for (int j = 0; j < edits.size() - 1;) { Edit c = edits.get(j); Edit n = edits.get(j + 1); // Combine edits that are really close together. Right now our rule // is, coalesce two line edits which are only one line apart if that // common context line is either a "pointless line", or is identical // on both sides and starts a new block of code. These are mostly // block reindents to add or remove control flow operators. // final int ad = n.getBeginA() - c.getEndA(); final int bd = n.getBeginB() - c.getEndB(); if ((1 <= ad && isBlankLineGap(a, c.getEndA(), n.getBeginA())) || (1 <= bd && isBlankLineGap(b, c.getEndB(), n.getBeginB())) || (ad == 1 && bd == 1 && isControlBlockStart(a, c.getEndA()))) { int ab = c.getBeginA(); int ae = n.getEndA(); int bb = c.getBeginB(); int be = n.getEndB(); edits.set(j, new Edit(ab, ae, bb, be)); edits.remove(j + 1); continue; } j++; } } private static boolean isBlankLineGap(Text a, int b, int e) { for (; b < e; b++) { if (!BLANK_LINE_RE.matcher(a.getLine(b)).matches()) { return false; } } return true; } private static boolean isControlBlockStart(Text a, int idx) { final String l = a.getLine(idx); return CONTROL_BLOCK_START_RE.matcher(l).find(); } private static boolean canCoalesce(CharText a, int b, int e) { while (b < e) { if (a.charAt(b++) == '\n') { return false; } } return true; } private static int findLF(List<Edit> edits, int j, CharText t, int b) { int lf = b; int limit = 0 < j ? edits.get(j - 1).getEndB() : 0; while (limit < lf && t.charAt(lf) != '\n') { lf--; } return lf; } private static boolean isOnlyWhitespace(CharText t, final int b, final int e) { for (int c = b; c < e; c++) { if (!Character.isWhitespace(t.charAt(c))) { return false; } } return b < e; } private static Text read(ObjectReader reader, String path, RevTree tree) throws IOException { TreeWalk tw = TreeWalk.forPath(reader, path, tree); if (tw == null || tw.getFileMode(0).getObjectType() != Constants.OBJ_BLOB) { return Text.EMPTY; } ObjectLoader ldr; try { ldr = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB); } catch (MissingObjectException notFound) { return Text.EMPTY; } return new Text(ldr.getCachedBytes()); } private static RevObject aFor(final PatchListKey key, final Repository repo, final RevWalk rw, final RevCommit b) throws IOException { if (key.getOldId() != null) { return rw.parseAny(key.getOldId()); } switch (b.getParentCount()) { case 0: return rw.parseAny(emptyTree(repo)); case 1:{ RevCommit r = b.getParent(0); rw.parseBody(r); return r; } default: // merge commit, return null to force combined diff behavior return null; } } private static ObjectId emptyTree(final Repository repo) throws IOException { ObjectInserter oi = repo.newObjectInserter(); try { ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {}); oi.flush(); return id; } finally { oi.release(); } } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
f0ea35f810ebf6f2a3b513b4f4dd80d0d46e62dc
328c0ad6b2ca55b06ccc5e71667dd75f071e63e4
/healthworld/src/com/tianxia/app/healthworld/digest/ChapterDetailsView.java
d9fb33a4b8d74f765fa2b8faec04d166c2850105
[]
no_license
lf78204490/world
e24a058936424fdbc1b39c03dac8ee5b48f669ba
e55af242efa60b987e669623d149e54a71285a87
refs/heads/master
2021-01-16T00:11:56.295653
2012-07-25T12:39:56
2012-07-25T12:39:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,600
java
/* * Copyright (C) 2012 Jayfeng. */ package com.tianxia.app.healthworld.digest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; import java.util.List; public class ChapterDetailsView extends View{ private String mInitText; private String mContent; private List<String> mLines; private int mPage = 1; private int mPageLines; private int mPageMax; private int mMarginTopAndBottom = 50; private int mMarginLeftAndRight = 25; private Paint mPaint; private float mFontHeight; private boolean mNeedRefresh = true; public ChapterDetailsView(Context context,AttributeSet attrs) { super(context, attrs); mLines = new ArrayList<String>(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(25); FontMetrics fm = mPaint.getFontMetrics(); mFontHeight = fm.descent - fm.top; } public void setInitText(String initText) { mInitText = initText; invalidate(); } public void setContent(String content) { mContent = content; invalidate(); } @Override public void onDraw(Canvas canvas) { if (mContent != null && !"".equals(mContent)) { if (mNeedRefresh) { splitContentToPageLines(); mNeedRefresh = false; } float drawTop = mMarginTopAndBottom; int startLine = (mPage - 1)*mPageLines; for (int i = startLine; i < startLine + mPageLines && i < mLines.size(); i++) { canvas.drawText(mLines.get(i), mMarginLeftAndRight, drawTop, mPaint); drawTop += mFontHeight + 2.5; } } else if (mInitText != null && !"".equals(mInitText)) { int initTextWidth = (int) mPaint.measureText(mInitText); int initTextX = (getWidth() - initTextWidth)/2; int initTextY = (getHeight() - (int)mFontHeight)/2; canvas.drawText(mInitText, initTextX, initTextY, mPaint); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (event.getX() > getWidth()/2) { if (mPage < mPageMax) { mPage++; invalidate(); } else { } } else if (event.getX() < getWidth()/2) { if (mPage > 1) { mPage--; invalidate(); } else { } } break; default: break; } return super.onTouchEvent(event); } public void splitContentToPageLines() { mPageLines = (int)((float)(getHeight() - mMarginTopAndBottom*2)/mFontHeight); int start = 0, end; mLines.clear(); int textWidth = getWidth() - mMarginLeftAndRight*2; for (int i = 0; i < mContent.length(); i++) { end = i; String line = mContent.substring(start, end + 1); if (mPaint.measureText(line) >= textWidth) { line = mContent.substring(start, end); mLines.add(line); start = i; } else if (i == mContent.length() - 1 ){ mLines.add(line); start = i; } else if (mContent.charAt(i) == '\r' && mContent.charAt(i+1) == '\n') { // if goto this if branch, there is must be : i < mContent.length() - 1 if (start >= end) { continue; } line = mContent.substring(start, end); mLines.add(line); start = i + 2; if (start > mContent.length() - 1) { start = mContent.length() - 1; } } else if (mContent.charAt(i) == '\n') { if (start >= end) { continue; } line = mContent.substring(start, end); mLines.add(line); start = i + 1; } } if (mLines.size()%mPageLines == 0) { mPageMax = mLines.size()/mPageLines; } else { mPageMax = mLines.size()/mPageLines + 1; } } }
[ "673592063@qq.com" ]
673592063@qq.com
8bb5bcea2b29e941621f5c972e43d9eb4e465c4a
7ccfd45b7aa66125d2e4d03d2d8183a8545de8be
/src/com/snmi/behavioralPatterns/command/Switch.java
9c86bc50516f9f5f38212245faca8d080f4ebf0a
[]
no_license
stefanmandradzhiyski/design-patterns
38e5c8b241011f2d57107d02776ce13de0d4501f
268f4bb2f663856b47744c266ac7940ce1d85a64
refs/heads/master
2021-07-12T20:27:01.537621
2020-09-26T07:25:41
2020-09-26T07:25:41
206,670,414
0
0
null
null
null
null
UTF-8
Java
false
false
327
java
package com.snmi.behavioralPatterns.command; /** * Switch as Invoker * @author Stefan Mandradzhiyski * @version 1.0 */ public class Switch { /** * Store and execute the command * @param command take the command */ public void storeAndExecute(Command command) { command.execute(); } }
[ "stefanmandradzhiyski@gmail.com" ]
stefanmandradzhiyski@gmail.com
33537074a37bdcaeebb759aca6940d328ae818d4
3e25a6ab00fc9002c5b8e93b9bd200232566aa1c
/src/main/java/org/iesalandalus/programacion/tutorias/mvc/modelo/dominio/Alumno.java
e53496f0e3f886c2873fe2e53c99e7c5e370986a
[]
no_license
MarMP/Tutorias-4
2bd39c2cc03bed75eb067a5ce3a0d4305e121df7
aefc6206674af51c91410f198203fa030918e7d8
refs/heads/master
2022-06-05T21:06:48.181295
2020-05-03T23:12:35
2020-05-03T23:12:35
258,241,007
0
0
null
null
null
null
UTF-8
Java
false
false
3,838
java
package org.iesalandalus.programacion.tutorias.mvc.modelo.dominio; import java.io.Serializable; import java.util.Objects; public class Alumno implements Serializable { private static final String ER_NOMBRE = "^([A-Za-zÁÉÍÓÚñáéíóúÑ]{0}?[A-Za-zÁÉÍÓÚñáéíóúÑ\\']+[\\s])+([A-Za-zÁÉÍÓÚñáéíóúÑ]{0}?[A-Za-zÁÉÍÓÚñáéíóúÑ\\'])+[\\s]?([A-Za-zÁÉÍÓÚñáéíóúÑ]{0}?[A-Za-zÁÉÍÓÚñáéíóúÑ\\'])?$"; private static final String PREFIJO_EXPEDIENTE = "SP_"; private static final String ER_CORREO = "\\w+(?:\\.\\w+)*@\\w+\\.\\w{2,5}"; private static int ultimoIdentificador = 0; private String nombre; private String correo; private String expediente; public Alumno(String nombre, String correo) { setNombre(nombre); setCorreo(correo); incrementaUltimoIdentificador(); setExpediente(); } public Alumno(Alumno alumno) { if (alumno == null) { throw new NullPointerException("ERROR: No es posible copiar un alumno nulo."); } setNombre(alumno.getNombre()); setCorreo(alumno.getCorreo()); this.expediente = alumno.getExpediente(); } public static Alumno getAlumnoFicticio(String correo) { return new Alumno("Mar Membrive", correo); } public String getNombre() { return nombre; } private void setNombre(String nombre) { if (nombre == null) { throw new NullPointerException("ERROR: El nombre no puede ser nulo."); } if (nombre.trim().equals("")) { throw new IllegalArgumentException("ERROR: El nombre no tiene un formato válido."); } this.nombre = formateaNombre(nombre); if (!this.nombre.matches(ER_NOMBRE)) { throw new IllegalArgumentException("ERROR: El nombre no tiene un formato válido."); } } private String formateaNombre(String nombre) { String cadenaMinus = nombre; cadenaMinus = cadenaMinus.toLowerCase(); cadenaMinus = cadenaMinus.trim(); cadenaMinus = cadenaMinus.replaceAll(" +", " "); char[] cadCaracter = cadenaMinus.toCharArray(); cadCaracter[0] = Character.toUpperCase(cadCaracter[0]); for (int i = 0; i < cadenaMinus.length() - 1; i++) if (cadCaracter[i] == ' ' || cadCaracter[i] == '.') { cadCaracter[i + 1] = Character.toUpperCase(cadCaracter[i + 1]); } return new String(cadCaracter); } public String getCorreo() { return correo; } private void setCorreo(String correo) { if (correo == null) { throw new NullPointerException("ERROR: El correo no puede ser nulo."); } if (correo.trim().equals("")) { throw new IllegalArgumentException("ERROR: El formato del correo no es válido."); } if (!correo.matches(ER_CORREO)) { throw new IllegalArgumentException("ERROR: El formato del correo no es válido."); } this.correo = correo; } public String getExpediente() { return expediente; } private void setExpediente() { expediente = PREFIJO_EXPEDIENTE + getIniciales() + "_" + ultimoIdentificador; } private static void incrementaUltimoIdentificador() { ultimoIdentificador++; } public static void identificadorFichero (int ultimoIdentificadorFichero) { ultimoIdentificador = ultimoIdentificadorFichero; } private String getIniciales() { String[] nombres = nombre.split(" "); String iniciales = ""; for (String nombre : nombres) { if (!nombre.equals("")) { iniciales = iniciales + nombre.charAt(0); } } return iniciales.toUpperCase(); } @Override public int hashCode() { return Objects.hash(correo); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Alumno)) { return false; } Alumno other = (Alumno) obj; return Objects.equals(correo, other.correo); } @Override public String toString() { return "nombre=" + nombre + " (" + getIniciales() + ")," + " correo=" + correo + ", expediente=" + expediente; } }
[ "marmembriveplaza@gmail.com" ]
marmembriveplaza@gmail.com
294b0dfb5056c9845f1fc321ea2f533ec0a7af91
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/neo4j/2018/4/FusionIndexBase.java
4a869484bbc2380f564e4f0e49ab1926b9503bc3
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
6,462
java
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.index.schema.fusion; import java.lang.reflect.Array; import java.util.Arrays; import org.neo4j.collection.primitive.PrimitiveIntCollections; import org.neo4j.function.ThrowingConsumer; import org.neo4j.function.ThrowingFunction; import org.neo4j.helpers.Exceptions; import org.neo4j.kernel.api.index.IndexProvider; /** * Acting as a simplifier for the multiplexing that is going in inside a fusion index. A fusion index consists of multiple parts, * each handling one or more value groups. Each instance, be it a reader, populator or accessor should extend this class * to get that multiplexing at a low cost. All parts will live in an array with specific slot constants to each specific part. * * @param <T> type of instances */ public abstract class FusionIndexBase<T> { static final int INSTANCE_COUNT = 5; static final int STRING = 0; static final int NUMBER = 1; static final int SPATIAL = 2; static final int TEMPORAL = 3; static final int LUCENE = 4; final T[] instances; final FusionIndexProvider.Selector selector; FusionIndexBase( T[] instances, FusionIndexProvider.Selector selector ) { assert instances.length == INSTANCE_COUNT; this.instances = instances; this.selector = selector; } <R,E extends Exception> R[] instancesAs( Class<R> cls, ThrowingFunction<T,R,E> converter ) throws E { return instancesAs( instances, cls, converter ); } static <T,R,E extends Exception> R[] instancesAs( T[] instances, Class<R> cls, ThrowingFunction<T,R,E> converter ) throws E { R[] result = (R[]) Array.newInstance( cls, instances.length ); for ( int i = 0; i < instances.length; i++ ) { result[i] = converter.apply( instances[i] ); } return result; } /** * NOTE: duplicate of {@link #forAll(ThrowingConsumer, Iterable)} to avoid having to wrap subjects of one form into another. * There are some real use cases for passing in an array instead of {@link Iterable} out there... * * Method for calling a lambda function on many objects when it is expected that the function might * throw an exception. First exception will be thrown and subsequent will be suppressed. * * For example, in FusionIndexAccessor: * <pre> * public void drop() throws IOException * { * forAll( IndexAccessor::drop, firstAccessor, secondAccessor, thirdAccessor ); * } * </pre> * * @param consumer lambda function to call on each object passed * @param subjects varargs array of objects to call the function on * @param <E> the type of exception anticipated, inferred from the lambda * @throws E if consumption fails with this exception */ @SafeVarargs public static <T, E extends Exception> void forAll( ThrowingConsumer<T,E> consumer, T... subjects ) throws E { // Duplicate this method for array to avoid creating a purely internal list to shove that in to the other method. E exception = null; for ( T subject : subjects ) { try { consumer.accept( subject ); } catch ( Exception e ) { exception = Exceptions.chain( exception, (E) e ); } } if ( exception != null ) { throw exception; } } /** * See {@link #forAll(ThrowingConsumer, Object[])} * NOTE: duplicate of {@link #forAll(ThrowingConsumer, Object[])} to avoid having to wrap subjects of one form into another. * There are some real use cases for passing in an Iterable instead of array out there... * * Method for calling a lambda function on many objects when it is expected that the function might * throw an exception. First exception will be thrown and subsequent will be suppressed. * * For example, in FusionIndexAccessor: * <pre> * public void drop() throws IOException * { * forAll( IndexAccessor::drop, firstAccessor, secondAccessor, thirdAccessor ); * } * </pre> * * @param consumer lambda function to call on each object passed * @param subjects varargs array of objects to call the function on * @param <E> the type of exception anticipated, inferred from the lambda * @throws E if consumption fails with this exception */ public static <T, E extends Exception> void forAll( ThrowingConsumer<T,E> consumer, Iterable<T> subjects ) throws E { E exception = null; for ( T subject : subjects ) { try { consumer.accept( subject ); } catch ( Exception e ) { exception = Exceptions.chain( exception, (E) e ); } } if ( exception != null ) { throw exception; } } static void validateSelectorInstances( Object[] instances, int... aliveIndex ) { for ( int i = 0; i < instances.length; i++ ) { boolean expected = PrimitiveIntCollections.contains( aliveIndex, i ); boolean actual = instances[i] != IndexProvider.EMPTY; if ( expected != actual ) { throw new IllegalArgumentException( String.format( "Only indexes expected to be separated from IndexProvider.EMPTY are %s but was %s", Arrays.toString( aliveIndex ), Arrays.toString( instances ) ) ); } } } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
54966c2ffe94fec0dcb79e0e14b7874a67e1b662
34faed4bb85b3fabf684f3faac01524546f3c3ee
/src/Assemb/LOperand/Reg.java
498c536765cfb0d6c96ead24642f83c70647a5cc
[]
no_license
ZYHowell/Warspite
38123a5577cfbf6f7084766b3de83152f3b8bc83
d6953e55a56ad7198846c6119690f4ed203b3092
refs/heads/master
2023-04-04T21:02:43.291267
2021-04-21T09:56:16
2021-04-21T09:56:16
233,590,305
2
0
null
null
null
null
UTF-8
Java
false
false
608
java
package Assemb.LOperand; import Assemb.RISCInst.Mv; import java.util.HashSet; public abstract class Reg extends LOperand { public int degree = 0; public double weight = 0; public Reg alias = null; public PhyReg color; public Imm stackOffset = null; public HashSet<Reg> adjList = new HashSet<>(); public HashSet<Mv> moveList = new HashSet<>(); public Reg() { super(); if (this instanceof PhyReg) color = (PhyReg)this; else color = null; } public void init() { moveList.clear(); weight = 0; } }
[ "zhuangyh@sjtu.edu.cn" ]
zhuangyh@sjtu.edu.cn
74b77403846a02356b51ee668462d9d3a2f3bce7
1cf0344795731c3ea4a06c3f9776367ee6e3d91f
/src/other/aoc/AOC2017Day5.java
eaafcfc52ddf37b74499096490405805d3177379
[]
no_license
Alex7Li/ProgrammingContests
cf900303ef6ea34d686ea005ba810aabcc6bcc3d
cf6aa6758beb4cc5ca458fcda4ba8dd258e639c1
refs/heads/master
2023-03-11T04:14:49.577346
2023-02-24T20:48:29
2023-02-24T20:48:29
100,300,632
3
0
null
null
null
null
UTF-8
Java
false
false
544
java
package other.aoc; import java.util.Scanner; public class AOC2017Day5 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int lines = 1033; int count = 0; int[] a = new int[1033]; for (int i = 0; i < lines; i++) { a[i] = s.nextInt(); } int curIndex = 0; while (curIndex < a.length) { if (a[curIndex] >= 3) { a[curIndex]--; curIndex += a[curIndex] + 1; } else { a[curIndex]++; curIndex += a[curIndex] - 1; } count++; } System.out.println(count); s.close(); } }
[ "7alex7li@gmail.com" ]
7alex7li@gmail.com
6e168d9f909defab3c6012ecb1b8b9a6a23440ef
9dbd7a0e4e28ef918f95004d9dfc82ef83c03178
/Setting/app/src/main/java/com/example/nishigupta/setting/MainActivity.java
08b87a4723fe7f1f5ca5db2c7e5a6428d0d2492b
[]
no_license
goyalavishi/Android-Dev-Practice
17d19e28c9d1ad6c36be431a720ad5242f5d75b6
c45fbf50c944af0a955e4b30e61583976c3615bf
refs/heads/master
2022-11-24T06:56:10.448729
2020-07-30T20:27:32
2020-07-30T20:27:32
283,852,472
1
0
null
null
null
null
UTF-8
Java
false
false
2,228
java
package com.example.nishigupta.setting; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { char gen = 'f'; ImageView avatar; //RelativeLayout rel; ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_page); ArrayAdapter adp; list = (ListView) findViewById(R.id.listView); String s[] = {"My Preferences", "Leased Books", "Rented Books", "Settings", "Logout"}; adp = new ArrayAdapter(this, android.R.layout.simple_list_item_1, s); //rel=(RelativeLayout)findViewById(R.id.relative); avatar = (ImageView) findViewById(R.id.imageView); if (gen == 'f') { // rel.setBackgroundColor(Color.parseColor("#5093ff")); avatar.setImageDrawable(getResources().getDrawable(R.drawable.girl)); } else { avatar.setImageDrawable(getResources().getDrawable(R.drawable.boy)); //rel.setBackgroundColor(Color.parseColor("#5093ff")); } list.setAdapter(adp); list.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(this,[position-1],Toast.LENGTH_SHORT).show(); if(position==0) { Intent inent = new Intent(this, Preference.class); startActivity(inent); } else if(position==1) { Intent inent = new Intent(this, LeasedBook.class); startActivity(inent); } else if(position==2) { Intent inent = new Intent(this, RentedBook.class); startActivity(inent); } else if(position ==3) { Intent inent = new Intent(this, Settings.class); startActivity(inent); } } }
[ "goyalavishi@gmail.com" ]
goyalavishi@gmail.com
ca707534ade91b2c2836edaa9527e40d079bb1cd
aca457909ef8c4eb989ba23919de508c490b074a
/DialerJADXDecompile/defpackage/ai.java
9752a5d1c52282fd8f9cbf801495d8f474dd035e
[]
no_license
KHikami/ProjectFiCallingDeciphered
bfccc1e1ba5680d32a4337746de4b525f1911969
cc92bf6d4cad16559a2ecbc592503d37a182dee3
refs/heads/master
2021-01-12T17:50:59.643861
2016-12-08T01:20:34
2016-12-08T01:23:04
71,650,754
1
0
null
null
null
null
UTF-8
Java
false
false
373
java
package defpackage; import java.lang.ref.WeakReference; /* compiled from: PG */ /* renamed from: ai */ public final class ai { final WeakReference a; public int b; public ai(int i, ah ahVar) { this.a = new WeakReference(ahVar); this.b = i; } final boolean a(ah ahVar) { return ahVar != null && this.a.get() == ahVar; } }
[ "chu.rachelh@gmail.com" ]
chu.rachelh@gmail.com
344ad40493eb2cd5ddbbd59d303c104cba3f2837
55bcf06cd72ffa0bd4170663d80627b525f82d0d
/Prova1Questao5/src/Empresa.java
b02c07d9a7435521fba20a5caf300b6e2d9271a4
[]
no_license
fellipebs/Java_Faculdade_POO
7cba614648975edff828739036c02646fcfab92c
1865df72744109b2a8819da90d530274d18113a7
refs/heads/master
2023-03-29T21:54:22.809439
2021-04-06T22:04:21
2021-04-06T22:04:21
355,339,790
0
0
null
null
null
null
IBM852
Java
false
false
733
java
import java.util.List; public class Empresa { public String nome; public String endereco; public String cnpj; public double saldo = 0; public List<Departamento> d; public Empresa(String nome, String endereco, String cnpj, double saldo) { this.nome = nome; this.endereco = endereco; this.cnpj = cnpj; this.saldo = saldo; } public void exibirAtributos() { System.out.println("Nome:" + this.nome); System.out.println("Enderešo:" + this.endereco); System.out.println("Cnpj:" + this.cnpj); System.out.println("Saldo:" + this.saldo); } public void exibirDepartamentos() { for(int i = 0; i < d.size(); i++) { if(d.get(i) != null) { System.out.println("Nome:" + d.get(i).nome); } } } }
[ "fellipe.saraiva@netscanner.com.br" ]
fellipe.saraiva@netscanner.com.br
3ed70f075ce0a4558db37df83f99af45baa9605c
4b4dd42f7b1d2d65ca19f7d9701b8cd32e93e9c2
/branches/java-fp/xas/src/fc/xml/xas/FragmentIterator.java
31f7c4a7723cc5050f10f862fe9196a87e97f37c
[ "MIT" ]
permissive
lagerspetz/fc-syxaw
5919f55799442f9d36f7ba3889be46bf748198b1
45e350e589fd5a8761a993f3110193586e037525
refs/heads/master
2020-05-18T16:55:04.562543
2010-04-10T09:58:28
2010-04-10T09:58:28
32,139,827
0
0
null
null
null
null
UTF-8
Java
false
false
1,804
java
/* * Copyright 2005--2008 Helsinki Institute for Information Technology * * This file is a part of Fuego middleware. Fuego middleware is free * software; you can redistribute it and/or modify it under the terms * of the MIT license, included as the file MIT-LICENSE in the Fuego * middleware source distribution. If you did not receive the MIT * license with the distribution, write to the Fuego Core project at * fuego-core-users@googlegroups.com. */ package fc.xml.xas; import java.util.Iterator; import java.util.NoSuchElementException; public class FragmentIterator implements Iterator { private FragmentItem fragment; private int index; private int length; FragmentIterator (FragmentItem fragment, int index) { this(fragment, index, Integer.MAX_VALUE); } FragmentIterator (FragmentItem fragment, int index, int length) { Verifier.checkInterval(0, index, fragment.length()); Verifier.checkNotNegative(length); this.fragment = fragment; this.index = index; this.length = length; } public boolean hasNext () { return length > 0 && index < fragment.length(); } public Object next () { if (hasNext()) { Item item = fragment.get(index); // FIXME: Need to determine skipping at next run // to consider potential convert int n = 1; if (FragmentItem.isFragment(item)) { n = ((FragmentItem) item).getSize(); } index += n; length -= n; return item; } else { throw new NoSuchElementException("Fragment exhausted, index=" + index + ", length=" + length); } } public void remove () { throw new UnsupportedOperationException(); } public Pointer pointer () { return new FragmentPointer(fragment, index); } } // arch-tag: ce29e1e3-d27b-4e89-a928-02ff9730bc2c
[ "tancred.lindholm@e02fe240-acfe-11de-93df-fb3520970a50" ]
tancred.lindholm@e02fe240-acfe-11de-93df-fb3520970a50
65d10abf2f0b41a4abf33694ee32ae3ad2e0a125
5cb5d1fc80c1f68ade44f0a26a02d1aeb118c64d
/ink-user/ink-user-core/src/main/java/com/ink/user/core/dao/IReqLogDao.java
e86cf754d6b45da3d7bc3d5901c9da92d9e0e1cd
[]
no_license
gspandy/zx-parent
4350d1ef851d05eabdcf8c6c7049a46593e3c22e
5cdc52e645537887e86e5cbc117139ca1a56f55d
refs/heads/master
2023-08-31T15:29:50.763388
2016-08-11T09:17:29
2016-08-11T09:20:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
401
java
/** * <p> Copyright (c) 2015-2025 银客网.</p> * <p>All Rights Reserved. 保留所有权利. </p> */ package com.ink.user.core.dao; import com.ink.user.core.po.ReqLog; import com.ink.base.EntityDao; /** * @author * @version 1.0 * @since 1.0 */ public interface IReqLogDao extends EntityDao<ReqLog, java.lang.Long>{ ReqLog checkReqLog(String ordId, String txnCode, String mchId); }
[ "zxzhouxiang123@163.com" ]
zxzhouxiang123@163.com
48d8a720d68198fb0e4609d7cb00437acd680400
ae17db47f93731f5febaa19b72c9c861958d4951
/Algorithms/NumberLineJumps.java
cb7144601b7ce2583efc97fd738a44f0204f314e
[]
no_license
YeibinKang/HackerRank
57b5b8f4867b063b8e7ce5223d90e502c567d3b1
cd1ef41ac9282ecddb0e8aeecd3ba328e8378eea
refs/heads/main
2023-08-31T05:11:56.948024
2021-09-21T18:40:57
2021-09-21T18:40:57
406,098,169
0
0
null
null
null
null
UTF-8
Java
false
false
2,083
java
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'kangaroo' function below. * * The function is expected to return a STRING. * The function accepts following parameters: * 1. INTEGER x1 * 2. INTEGER v1 * 3. INTEGER x2 * 4. INTEGER v2 */ public static String kangaroo(int x1, int v1, int x2, int v2) { // Write your code here //speed = distance/time //distance = speed * time //distance = v1 * j // (v1*j)+x1 = (v2*j)+x2 // j = (x2-x1)/(v1-v2) //remainder should be 0 (because j should be integer) if(v2 >= v1 && x2 > x1){ return "NO"; }else{ if((x2-x1)%(v2-v1) == 0){ return "YES"; }else{ return "NO"; } } } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" "); int x1 = Integer.parseInt(firstMultipleInput[0]); int v1 = Integer.parseInt(firstMultipleInput[1]); int x2 = Integer.parseInt(firstMultipleInput[2]); int v2 = Integer.parseInt(firstMultipleInput[3]); String result = Result.kangaroo(x1, v1, x2, v2); bufferedWriter.write(result); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
[ "yeibinkang@gmail.com" ]
yeibinkang@gmail.com
10c850838aeeb6eedbd8d41feca27960ab90b582
ec283dd0148de73153cf163d21a710795f8adf59
/src/_03_date_time/DateClass.java
ce4c2b7526ffda372bffb7cbb4594fb95a95c8fb
[]
no_license
yurtseveronr/hello-java
592c1ba8cd310bf2d3c8b11995bff32f68122478
64a94c840884518fab40f6d28ecd42ddd30c0e0e
refs/heads/master
2023-06-20T08:51:47.657832
2021-07-20T13:29:59
2021-07-20T13:29:59
387,798,557
0
0
null
null
null
null
UTF-8
Java
false
false
1,371
java
package _03_date_time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateClass { public static void main(String[] args) throws ParseException { Date now = new Date(); System.out.println(now.toString()); Date date_userdefined = new Date(24*60*60*1000); // after 1st january 1970 System.out.println(date_userdefined.toString()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date date = new Date(); System.out.println(simpleDateFormat.format(date)); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS"); Date date1 = new Date(); System.out.println(simpleDateFormat1.format(date1)); String dateAsText = "2020-12-12"; SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("dd-MM-yyyy"); Date date2 = simpleDateFormat2.parse(dateAsText);//throws ParseException, go to exception handling System.out.println(date2); boolean after = date.after(date1); boolean before = date.before(date2); boolean equals = date.equals(date2); int compare = date.compareTo(date_userdefined); long duration_time = date.getTime(); date.setTime(11111111); // after 1st january 1970 } }
[ "yurtseveronr@gmail.com" ]
yurtseveronr@gmail.com
7e2efa8f1fd31a925085ec6682c598df6e47f421
1195fc70a96c1fffadbb5e54a6af42e8efd0233a
/src/com/orderFoods/factory/HibernateSessionFactory.java
08ff2d11dfc6ba0025718d763a81253c5571f523
[]
no_license
jyf514/OrderFoods
d208c7437ffa24fcf1c5d4304480faf33c526170
fbcc8350caf8cc9e05f267409f69594633514081
refs/heads/master
2020-04-05T22:45:33.410253
2014-05-24T08:59:42
2014-05-24T09:00:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,231
java
package com.orderFoods.factory; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
[ "526613332@qq.com" ]
526613332@qq.com
0d659d94a6f6b411683a338a8094ebe9e2fceae1
5dade31d71baaf39075be2e91a975a29a1c46586
/app/src/main/java/picketwatch/DrawingView.java
17ef71b342d6daf8e27acb07bd512a77ee81c705
[]
no_license
paulinar/picket-watch
be4b04499b281aaa37e557382bd62628846dbf98
55cc98898c8ec9eb584b869a646093e832075241
refs/heads/master
2016-09-06T21:35:43.670249
2014-10-14T07:12:27
2014-10-14T07:12:27
25,191,544
0
1
null
null
null
null
UTF-8
Java
false
false
4,643
java
package com.example.mari.picketwatch; /* Followed tutorial: http://code.tutsplus.com/tutorials/android-sdk-create-a-drawing-app-touch-interaction--mobile-19202 */ import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; public class DrawingView extends View { //drawing path private Path drawPath; //drawing and canvas are both Paint objects private Paint drawPaint, canvasPaint; //initial color private int paintColor = 0xFF660000; //canvas private Canvas drawCanvas; //canvas bitmap private Bitmap canvasBitmap; private float brushSize, lastBrushSize; private boolean erase=false; /* The user paths drawn with drawPaint will be drawn onto the canvas, which is drawn with canvasPaint. */ // constructor method // we'll add an instance of the custom View to the XML layout file public DrawingView(Context context, AttributeSet attrs){ super(context, attrs); setupDrawing(); } // helper method to get drawing area setup for interaction private void setupDrawing(){ brushSize = getResources().getInteger(R.integer.medium_size); lastBrushSize = brushSize; drawPath = new Path(); drawPaint = new Paint(); // initial color drawPaint.setColor(paintColor); // initial path properties (make drawings look smoother) drawPaint.setAntiAlias(true); drawPaint.setStrokeWidth(brushSize); // used to be hardcoded drawPaint.setStyle(Paint.Style.STROKE); drawPaint.setStrokeJoin(Paint.Join.ROUND); drawPaint.setStrokeCap(Paint.Cap.ROUND); // instantiate canvas Paint object canvasPaint = new Paint(Paint.DITHER_FLAG); } /* Size view */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // instantiate drawing canvas and bitmap using width & height values canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); drawCanvas = new Canvas(canvasBitmap); } /* Draw view */ @Override protected void onDraw(Canvas canvas) { // draw the canvas & drawing path canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint); canvas.drawPath(drawPath, drawPaint); } /* listen for touch events */ @Override public boolean onTouchEvent(MotionEvent event) { float touchX = event.getX(); float touchY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // user touches the view drawPath.moveTo(touchX, touchY); break; case MotionEvent.ACTION_MOVE: drawPath.lineTo(touchX, touchY); break; case MotionEvent.ACTION_UP: // user lifts finger off view drawCanvas.drawPath(drawPath, drawPaint); drawPath.reset(); break; default: return false; } // each time user draws using touch interaction, invalidate the View to cause onDrawmethod to execute // i.e. re-renders entire view invalidate(); return true; } public void setColor(String newColor){ invalidate(); // parse and set color for drawing paintColor = Color.parseColor(newColor); drawPaint.setColor(paintColor); } public void setBrushSize(float newSize){ float pixelAmount = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, newSize, getResources().getDisplayMetrics()); brushSize=pixelAmount; drawPaint.setStrokeWidth(brushSize); // update Paint object to use new size } public void setLastBrushSize(float lastSize){ lastBrushSize=lastSize; } public float getLastBrushSize(){ return lastBrushSize; } // default is user is drawing public void setErase(boolean isErase){ erase=isErase; if (erase) drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); else drawPaint.setXfermode(null); } // clears canvas and updates display public void startNew(){ drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR); invalidate(); } }
[ "m.paulina.ramos@gmail.com" ]
m.paulina.ramos@gmail.com
e243b7fd805073ea6c05a09d320b3f062f0b0240
630f27eddc3926ed426ade2cab05540b23d3dc08
/app/src/main/java/me/bakumon/moneykeeper/ui/addaccount/AddAccountViewModel.java
2d05875dd159f75dc4e5332c1db3a70dc783d5a8
[ "Apache-2.0" ]
permissive
Wangsilu0117/SE-Group3
cc6ddc531f2232806cf3dd4cb1d2db47abd55519
ba6ae39f67c3386f42b1a569d726ab9931682e21
refs/heads/master
2023-02-03T17:34:46.199583
2020-12-24T03:42:47
2020-12-24T03:42:47
296,614,688
1
0
null
null
null
null
UTF-8
Java
false
false
817
java
package me.bakumon.moneykeeper.ui.addaccount; import io.reactivex.Completable; import me.bakumon.moneykeeper.base.BaseViewModel; import me.bakumon.moneykeeper.database.entity.Account; import me.bakumon.moneykeeper.datasource.AppDataSource; public class AddAccountViewModel extends BaseViewModel { public AddAccountViewModel(AppDataSource dataSource) { super(dataSource); } public Completable saveAccount(Account account, String name) { if (account == null) { // 添加 return mDataSource.addAccount(name); } else { // 修改 Account updateAccount = new Account(account.id, name, account.rank); updateAccount.state = account.state; return mDataSource.updateAccount(account, updateAccount); } } }
[ "904473183@qq.com" ]
904473183@qq.com
472cb6612e33da6f3a35839eabbcc51ce7451480
5ac3c341968b8337042e3992f5b75f27132d48de
/LiveWallPaper/src/main/java/com/roger/livewallpaper/programs/HeightmapShaderProgram.java
8ce3543a0f8e2340be4f40e348d15337467e0654
[]
no_license
BigDendi/HelloNDK
70360da9265679d2025c9a5fe139bf24cfdec91b
11c5981f304a4734f9c62bc938c99fedd2eb33a5
refs/heads/master
2021-08-14T08:23:31.651562
2017-11-15T03:29:05
2017-11-15T03:29:10
110,777,949
0
0
null
null
null
null
UTF-8
Java
false
false
3,003
java
/*** * Excerpted from "OpenGL ES for Android", * published by The Pragmatic Bookshelf. * Copyrights apply to this code. It may not be used to create training material, * courses, books, articles, and the like. Contact us if you are in doubt. * We make no guarantees that this code is fit for any purpose. * Visit http://www.pragmaticprogrammer.com/titles/kbogla for more book information. ***/ package com.roger.livewallpaper.programs; import android.content.Context; import com.roger.livewallpaper.R; import static android.opengl.GLES20.glGetAttribLocation; import static android.opengl.GLES20.glGetUniformLocation; import static android.opengl.GLES20.glUniform3fv; import static android.opengl.GLES20.glUniform4fv; import static android.opengl.GLES20.glUniformMatrix4fv; public class HeightmapShaderProgram extends ShaderProgram { private final int uVectorToLightLocation; private final int uMVMatrixLocation; private final int uIT_MVMatrixLocation; private final int uMVPMatrixLocation; private final int uPointLightPositionsLocation; private final int uPointLightColorsLocation; private final int aPositionLocation; private final int aNormalLocation; public HeightmapShaderProgram(Context context) { super(context, R.raw.heightmap_vertex_shader, R.raw.heightmap_fragment_shader); uVectorToLightLocation = glGetUniformLocation(program, U_VECTOR_TO_LIGHT); uMVMatrixLocation = glGetUniformLocation(program, U_MV_MATRIX); uIT_MVMatrixLocation = glGetUniformLocation(program, U_IT_MV_MATRIX); uMVPMatrixLocation = glGetUniformLocation(program, U_MVP_MATRIX); uPointLightPositionsLocation = glGetUniformLocation(program, U_POINT_LIGHT_POSITIONS); uPointLightColorsLocation = glGetUniformLocation(program, U_POINT_LIGHT_COLORS); aPositionLocation = glGetAttribLocation(program, A_POSITION); aNormalLocation = glGetAttribLocation(program, A_NORMAL); } /* public void setUniforms(float[] matrix, Vector vectorToLight) { glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0); glUniform3f(uVectorToLightLocation, vectorToLight.x, vectorToLight.y, vectorToLight.z); } */ public void setUniforms(float[] mvMatrix, float[] it_mvMatrix, float[] mvpMatrix, float[] vectorToDirectionalLight, float[] pointLightPositions, float[] pointLightColors) { glUniformMatrix4fv(uMVMatrixLocation, 1, false, mvMatrix, 0); glUniformMatrix4fv(uIT_MVMatrixLocation, 1, false, it_mvMatrix, 0); glUniformMatrix4fv(uMVPMatrixLocation, 1, false, mvpMatrix, 0); glUniform3fv(uVectorToLightLocation, 1, vectorToDirectionalLight, 0); glUniform4fv(uPointLightPositionsLocation, 3, pointLightPositions, 0); glUniform3fv(uPointLightColorsLocation, 3, pointLightColors, 0); } public int getPositionAttributeLocation() { return aPositionLocation; } public int getNormalAttributeLocation() { return aNormalLocation; } }
[ "xiang2713@yeah.net" ]
xiang2713@yeah.net
21d190d7498c9301c084d1c5117a92192f791ff8
5a261f113661e732e052e202ddf55616d8202912
/app/src/main/java/com/example/PriceAlert2020/ActiveAlertsPage.java
26af06cdce86c19c21f46001b706eebcb4d842bc
[]
no_license
CxHx/DebugApp
98f84fcb66db9825623c410e91ff038c5841e536
d8c2912faa665cd853d6bd4c418cbd339e9bf24f
refs/heads/master
2022-08-24T02:14:22.403930
2020-05-17T08:53:57
2020-05-17T08:53:57
264,437,684
0
0
null
null
null
null
UTF-8
Java
false
false
1,223
java
package com.example.PriceAlert2020; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import androidx.appcompat.app.AppCompatActivity; public class ActiveAlertsPage extends AppCompatActivity { private RelativeLayout appIconLayoutAAP; //appIcon to get back to the main page @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.active_alerts_page); appIconLayoutAAP = findViewById(R.id.appIconLayoutAAP); appIconLayoutAAP.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), MainPage.class); startActivity(intent); } }); } /** * Redirects you back to the main page. * (Since the page before would only be a popup on the main page, either the appIcon or the * backButton can be scrapped) * @param view */ public void backToMainPage(View view) { Intent intent = new Intent(this, MainPage.class); startActivity(intent); } }
[ "41574468+CxHx@users.noreply.github.com" ]
41574468+CxHx@users.noreply.github.com
3aaba598c7abf6fb0e5f1cf88f2d2acb051576e5
f54fad3847c91e417812289c5870da0ddfd17585
/client/console/src/main/java/org/apache/syncope/client/console/rest/UserSelfRestClient.java
6a09b7c805e4ccdebdf7d7ec6a707e852172bc38
[ "Apache-2.0" ]
permissive
cs-keum/syncope
58e22bf2ad0847f30b2e6124329eedac05441d0e
29f2d7b2617a9dd2e5dd2f40f7d25e5cfc49cd95
refs/heads/master
2021-05-31T07:16:29.005937
2015-12-31T10:03:32
2015-12-31T10:03:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,511
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.client.console.rest; import org.apache.syncope.client.console.SyncopeConsoleSession; import org.apache.syncope.common.lib.SyncopeClientException; import org.apache.syncope.common.lib.patch.UserPatch; import org.apache.syncope.common.lib.to.UserTO; import org.apache.syncope.common.rest.api.service.UserSelfService; import org.springframework.stereotype.Component; @Component public class UserSelfRestClient extends BaseRestClient { private static final long serialVersionUID = 2994691796924731295L; public boolean isSelfRegistrationAllowed() { Boolean result = null; try { result = SyncopeConsoleSession.get().getSyncopeTO().isSelfRegAllowed(); } catch (SyncopeClientException e) { LOG.error("While seeking if self registration is allowed", e); } return result == null ? false : result; } public UserTO read() { return SyncopeConsoleSession.get().getSelfTO(); } public void create(final UserTO userTO, final boolean storePassword) { getService(UserSelfService.class).create(userTO, storePassword); } public void update(final UserPatch userPatch) { getService(UserSelfService.class).update(userPatch); } public void delete() { getService(UserSelfService.class).delete(); } public boolean isPasswordResetAllowed() { Boolean result = null; try { result = SyncopeConsoleSession.get().getSyncopeTO().isPwdResetAllowed(); } catch (SyncopeClientException e) { LOG.error("While seeking if password reset is allowed", e); } return result == null ? false : result; } public boolean isPwdResetRequiringSecurityQuestions() { Boolean result = null; try { result = SyncopeConsoleSession.get().getSyncopeTO().isPwdResetRequiringSecurityQuestions(); } catch (SyncopeClientException e) { LOG.error("While seeking if password reset requires security question", e); } return result == null ? false : result; } public void changePassword(final String password) { getService(UserSelfService.class).changePassword(password); } public void requestPasswordReset(final String username, final String securityAnswer) { getService(UserSelfService.class).requestPasswordReset(username, securityAnswer); } public void confirmPasswordReset(final String token, final String password) { getService(UserSelfService.class).confirmPasswordReset(token, password); } }
[ "ilgrosso@apache.org" ]
ilgrosso@apache.org
b2bc62d7420c85a8aa32175833f84fdafa2e82f6
973fccc219e22c87f2fdc60e1fcec814f7f91e89
/framework/common/src/org/ofbiz/common/email/NotificationServices.java
778fd7c9d47d1ae313b306b557d375b33d95d4fa
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown", "LicenseRef-scancode-jdom", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "MPL-1.1", "CPL-1.0", "GFDL-1.1-or-later", "MPL-2.0", "CC-BY-2.5", "SPL-1.0", "LicenseRef-scancode-proprietary-license", "CDDL-1.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
ilscipio/scipio-erp
170462a6bd6ad428aa9810ece576765b263ea592
0258c890ee1824c047b9306717e3b301e63537dd
refs/heads/master
2023-03-09T11:18:18.929234
2023-02-14T04:58:19
2023-02-14T04:59:08
60,078,463
344
224
Apache-2.0
2023-03-04T15:28:32
2016-05-31T10:00:37
Java
UTF-8
Java
false
false
16,140
java
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ package org.ofbiz.common.email; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import org.ofbiz.base.component.ComponentConfig.WebappInfo; import org.ofbiz.base.location.FlexibleLocation; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.template.FreeMarkerWorker; import org.ofbiz.entity.Delegator; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; import org.ofbiz.webapp.OfbizUrlBuilder; import org.ofbiz.webapp.WebAppUtil; import freemarker.template.TemplateException; /** * Provides generic services related to preparing and delivering notifications * via email. * <p> * To use the NotificationService, a message specific service should be * defined for a particular * <a href="http://freemarker.sourceforge.net/docs/dgui_quickstart_template.html"> * Freemarker Template</a> mapping the required fields of the template to the * required attributes of the service. * </p> * <p> * This service definition should extend the <code>sendNotificationInterface</code> * or the <code>prepareNotificationInterface</code> service interface * and simply invoke the associated method defined in this class. * </p> * <pre> * {@code * <service name="sendPoPickupNotification" engine="java" * location="org.ofbiz.content.email.NotificationServices" * invoke="sendNotification"> * <description>Sends notification based on a message template</description> * <implements service="sendNotificationInterface"/> * <attribute name="orderId" type="String" mode="IN" optional="false"/> * </service> * } * </pre> * <p> * An optional parameter available to all message templates is * <code>baseUrl</code> which can either be specified when the service is * invoked or let the <code>NotificationService</code> attempt to resolve it * as best it can, see {@link #setBaseUrl(Delegator, String, Map) setBaseUrl(Map)} * for details on how this is achieved. * </p> * The following example shows what a simple notification message template, * associated with the above service, might contain: * <blockquote> * <pre> * Please use the following link to schedule a delivery date: * ${baseUrl}/ordermgr/control/schedulepo?orderId=${orderId}" * </pre> * </blockquote> * <p> * The template file must be found on the classpath at runtime and * match the "templateName" field passed to the service when it * is invoked. * </p> * <p> * For complex messages with a large number of dynamic fields, it may be wise * to implement a custom service that takes one or two parameters that can * be used to resolve the rest of the required fields and then pass them to * the {@link #prepareNotification(DispatchContext, Map) prepareNotification(DispatchContext, Map)} * or {@link #sendNotification(DispatchContext, Map) sendNotification(DispatchContext, Map)} * methods directly to generate or generate and send the notification respectively. * </p> */ public class NotificationServices { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); public static final String resource = "CommonUiLabels"; /** * This will use the {@link #prepareNotification(DispatchContext, Map) prepareNotification(DispatchContext, Map)} * method to generate the body of the notification message to send * and then deliver it via the "sendMail" service. * <p> * If the "body" parameter is already specified, the message body generation * phase will be skipped and the notification will be sent with the * specified body instead. This can be used to combine both service * calls in a decoupled manner if other steps are required between * generating the message body and sending the notification. * * @param ctx The dispatching context of the service * @param context The map containing all the fields associated with * the sevice * @return A Map with the service response messages in it */ public static Map<String, Object> sendNotification(DispatchContext ctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = ctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); Map<String, Object> result = null; try { // see whether the optional 'body' attribute was specified or needs to be processed // nulls are handled the same as not specified String body = (String) context.get("body"); if (body == null) { // prepare the body of the notification email Map<String, Object> bodyResult = prepareNotification(ctx, context); // ensure the body was generated successfully if (bodyResult.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) { body = (String) bodyResult.get("body"); } else { // otherwise just report the error Debug.logError("prepareNotification failed: " + bodyResult.get(ModelService.ERROR_MESSAGE), module); body = null; } } // make sure we have a valid body before sending if (body != null) { // retain only the required attributes for the sendMail service Map<String, Object> emailContext = new LinkedHashMap<>(); emailContext.put("sendTo", context.get("sendTo")); emailContext.put("body", body); emailContext.put("sendCc", context.get("sendCc")); emailContext.put("sendBcc", context.get("sendBcc")); emailContext.put("sendFrom", context.get("sendFrom")); emailContext.put("subject", context.get("subject")); emailContext.put("sendVia", context.get("sendVia")); emailContext.put("sendType", context.get("sendType")); emailContext.put("contentType", context.get("contentType")); // pass on to the sendMail service result = dispatcher.runSync("sendMail", emailContext); } else { Debug.logError("Invalid email body; null is not allowed", module); result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailInvalidBody", locale)); } } catch (GenericServiceException serviceException) { Debug.logError(serviceException, "Error sending email", module); result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailDeliveryError", locale)); } return result; } /** * This will process the associated notification template definition * with all the fields contained in the given context and generate * the message body of the notification. * <p> * The result returned will contain the appropriate response * messages indicating success or failure and the OUT parameter, * "body" containing the generated message. * * @param ctx The dispatching context of the service * @param context The map containing all the fields associated with * the sevice * @return A new Map indicating success or error containing the * body generated from the template and the input parameters. */ public static Map<String, Object> prepareNotification(DispatchContext ctx, Map<String, ? extends Object> context) { Delegator delegator = ctx.getDelegator(); String templateName = (String) context.get("templateName"); Map<String, Object> templateData = UtilGenerics.checkMap(context.get("templateData")); String webSiteId = (String) context.get("webSiteId"); Locale locale = (Locale) context.get("locale"); Map<String, Object> result = null; if (templateData == null) { templateData = new LinkedHashMap<>(); } try { // ensure the baseUrl is defined // SCIPIO: 2019-02-04: Use better method //setBaseUrl(delegator, webSiteId, templateData); checkSetWebSiteFields(delegator, webSiteId, templateData); // initialize the template reader and processor URL templateUrl = FlexibleLocation.resolveLocation(templateName); if (templateUrl == null) { Debug.logError("Problem getting the template URL: " + templateName + " not found", module); return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemFindingTemplate", locale)); } // process the template with the given data and write // the email body to the String buffer Writer writer = new StringWriter(); FreeMarkerWorker.renderTemplate(templateUrl.toExternalForm(), templateData, writer); // extract the newly created body for the notification email String notificationBody = writer.toString(); // generate the successful response result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "CommonNotifyEmailMessageBodyGeneratedSuccessfully", locale)); result.put("body", notificationBody); } catch (IOException ie) { Debug.logError(ie, "Problems reading template", module); result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemReadingTemplate", locale)); } catch (TemplateException te) { Debug.logError(te, "Problems processing template", module); result = ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonNotifyEmailProblemProcessingTemplate", locale)); } return result; } /** * The expectation is that a lot of notification messages will include * a link back to one or more pages in the system, which will require knowledge * of the base URL to extrapolate. This method will ensure that the * <code>baseUrl</code> field is set in the given context. * <p> * If it has been specified a default <code>baseUrl</code> will be * set using a best effort approach. If it is specified in the * url.properties configuration files of the system, that will be * used, otherwise it will attempt resolve the fully qualified * local host name. * <p> * <i>Note:</i> I thought it might be useful to have some dynamic way * of extending the default properties provided by the NotificationService, * such as the <code>baseUrl</code>, perhaps using the standard * <code>ResourceBundle</code> java approach so that both classes * and static files may be invoked. * <p> * SCIPIO: This now also puts the following extra fields in the context: * <ul> * <li>baseWebSiteId (2015-10-16): the webSiteId, with extra prefix to prevent conflicts * <li>baseWebappPath (2018-08-01): the combination of webappPathPrefix+contextRoot for * the given website (this is simply the context root if * webappPathPrefix is not explicitly configured) * </ul> * * @param context The context to check and, if necessary, set the * <code>baseUrl</code>. */ public static void setBaseUrl(Delegator delegator, String webSiteId, Map<String, Object> context) { // If the baseUrl was not specified we can do a best effort instead if (!context.containsKey("baseUrl")) { try { WebappInfo webAppInfo = null; if (webSiteId != null) { webAppInfo = WebAppUtil.getWebappInfoFromWebsiteId(webSiteId); } OfbizUrlBuilder builder = OfbizUrlBuilder.from(webAppInfo, delegator); StringBuilder newURL = new StringBuilder(); builder.buildHostPart(newURL, "", false, false); context.put("baseUrl", newURL.toString()); newURL = new StringBuilder(); builder.buildHostPart(newURL, "", true, false); context.put("baseSecureUrl", newURL.toString()); // SCIPIO: 2018-08-01: store baseWebappPath, which is webappPathPrefix + contextPath newURL = new StringBuilder(); builder.buildPathPartWithContextPath(newURL); context.put("baseWebappPath", newURL.toString()); } catch (Exception e) { // SCIPIO: better log if (webSiteId != null) { // should not happen Debug.logError(e, "Exception while adding baseUrl to context [webSiteId: " + webSiteId + "]", module); } else { // may happen in stock (for now) Debug.logWarning("Exception while adding baseUrl to context [no webSiteId available]: " + e.toString(), module); } } } // SCIPIO: use this method to also store a baseWebSiteId in the context, so template has knowledge if (!context.containsKey("baseWebSiteId")) { context.put("baseWebSiteId", webSiteId); } } /** * SCIPIO: Sets the given webSiteId in context IF there isn't already a key for it. * @return the effective webSiteId */ public static String checkSetWebSiteId(Delegator delegator, String webSiteId, Map<String, Object> context) { String contextWebSiteId = (String) context.get("webSiteId"); if (contextWebSiteId == null && !context.containsKey("webSiteId")) { context.put("webSiteId", webSiteId); return webSiteId; } else { return contextWebSiteId; } } /** * SCIPIO: Sets the given webSiteId, along with baseUrl/baseSecureUrl in context IF there aren't already keys for them. * NOTE: You probably want to call the abstracted method {@link #checkSetWebSiteFields} instead. * @return the effective webSiteId */ public static String checkSetBaseUrlAndWebSiteId(Delegator delegator, String webSiteId, Map<String, Object> context) { setBaseUrl(delegator, webSiteId, context); return checkSetWebSiteId(delegator, webSiteId, context); } /** * SCIPIO: Sets the given webSiteId, along with baseUrl/baseSecureUrl in context IF there aren't already keys for them, * and along with anything related (abstraction). * @return the effective webSiteId */ public static String checkSetWebSiteFields(Delegator delegator, String webSiteId, Map<String, Object> context) { return checkSetBaseUrlAndWebSiteId(delegator, webSiteId, context); } }
[ "pplx@ilscipio.com" ]
pplx@ilscipio.com
e46f81df9bddffa1cf354e067fceab54c4f963c5
828b5327357d0fb4cb8f3b4472f392f3b8b10328
/flink-libraries/flink-gelly/src/test/java/org/apache/flink/graph/spargel/SpargelTranslationTest.java
a19d215c9c1ec60a4890ed29987b2ab9543ef6a7
[ "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "ISC", "MIT-0", "GPL-2.0-only", "BSD-2-Clause-Views", "OFL-1.1", "Apache-2.0", "LicenseRef-scancode-jdom", "GCC-exception-3.1", "MPL-2.0", "CC-PDDC", "AGPL-3.0-only", "MPL-2.0-no-copyleft-exception", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "BSD-2-Clause", "CDDL-1.1", "CDDL-1.0", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-free-unknown", "CC0-1.0", "Classpath-exception-2.0", "CC-BY-2.5" ]
permissive
Romance-Zhang/flink_tpc_ds_game
7e82d801ebd268d2c41c8e207a994700ed7d28c7
8202f33bed962b35c81c641a05de548cfef6025f
refs/heads/master
2022-11-06T13:24:44.451821
2019-09-27T09:22:29
2019-09-27T09:22:29
211,280,838
0
1
Apache-2.0
2022-10-06T07:11:45
2019-09-27T09:11:11
Java
UTF-8
Java
false
false
8,584
java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.graph.spargel; import org.apache.flink.api.common.aggregators.LongSumAggregator; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.io.DiscardingOutputFormat; import org.apache.flink.api.java.operators.DeltaIteration; import org.apache.flink.api.java.operators.DeltaIterationResultSet; import org.apache.flink.api.java.operators.TwoInputUdfOperator; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.graph.Graph; import org.apache.flink.graph.Vertex; import org.apache.flink.types.NullValue; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test the creation of a {@link ScatterGatherIteration} program. */ @SuppressWarnings("serial") public class SpargelTranslationTest { private static final String ITERATION_NAME = "Test Name"; private static final String AGGREGATOR_NAME = "AggregatorName"; private static final String BC_SET_MESSAGES_NAME = "borat messages"; private static final String BC_SET_UPDATES_NAME = "borat updates"; private static final int NUM_ITERATIONS = 13; private static final int ITERATION_parallelism = 77; @Test public void testTranslationPlainEdges() { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Long> bcMessaging = env.fromElements(1L); DataSet<Long> bcUpdate = env.fromElements(1L); DataSet<Vertex<String, Double>> result; // ------------ construct the test program ------------------ DataSet<Tuple2<String, Double>> initialVertices = env.fromElements(new Tuple2<>("abc", 3.44)); DataSet<Tuple2<String, String>> edges = env.fromElements(new Tuple2<>("a", "c")); Graph<String, Double, NullValue> graph = Graph.fromTupleDataSet(initialVertices, edges.map(new MapFunction<Tuple2<String, String>, Tuple3<String, String, NullValue>>() { public Tuple3<String, String, NullValue> map( Tuple2<String, String> edge) { return new Tuple3<>(edge.f0, edge.f1, NullValue.getInstance()); } }), env); ScatterGatherConfiguration parameters = new ScatterGatherConfiguration(); parameters.addBroadcastSetForScatterFunction(BC_SET_MESSAGES_NAME, bcMessaging); parameters.addBroadcastSetForGatherFunction(BC_SET_UPDATES_NAME, bcUpdate); parameters.setName(ITERATION_NAME); parameters.setParallelism(ITERATION_parallelism); parameters.registerAggregator(AGGREGATOR_NAME, new LongSumAggregator()); result = graph.runScatterGatherIteration(new MessageFunctionNoEdgeValue(), new UpdateFunction(), NUM_ITERATIONS, parameters).getVertices(); result.output(new DiscardingOutputFormat<>()); // ------------- validate the java program ---------------- assertTrue(result instanceof DeltaIterationResultSet); DeltaIterationResultSet<?, ?> resultSet = (DeltaIterationResultSet<?, ?>) result; DeltaIteration<?, ?> iteration = resultSet.getIterationHead(); // check the basic iteration properties assertEquals(NUM_ITERATIONS, resultSet.getMaxIterations()); assertArrayEquals(new int[]{0}, resultSet.getKeyPositions()); assertEquals(ITERATION_parallelism, iteration.getParallelism()); assertEquals(ITERATION_NAME, iteration.getName()); assertEquals(AGGREGATOR_NAME, iteration.getAggregators().getAllRegisteredAggregators().iterator().next().getName()); // validate that the semantic properties are set as they should TwoInputUdfOperator<?, ?, ?, ?> solutionSetJoin = (TwoInputUdfOperator<?, ?, ?, ?>) resultSet.getNextWorkset(); assertTrue(solutionSetJoin.getSemanticProperties().getForwardingTargetFields(0, 0).contains(0)); assertTrue(solutionSetJoin.getSemanticProperties().getForwardingTargetFields(1, 0).contains(0)); TwoInputUdfOperator<?, ?, ?, ?> edgesJoin = (TwoInputUdfOperator<?, ?, ?, ?>) solutionSetJoin.getInput1(); // validate that the broadcast sets are forwarded assertEquals(bcUpdate, solutionSetJoin.getBroadcastSets().get(BC_SET_UPDATES_NAME)); assertEquals(bcMessaging, edgesJoin.getBroadcastSets().get(BC_SET_MESSAGES_NAME)); } @Test public void testTranslationPlainEdgesWithForkedBroadcastVariable() { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Long> bcVar = env.fromElements(1L); DataSet<Vertex<String, Double>> result; // ------------ construct the test program ------------------ DataSet<Tuple2<String, Double>> initialVertices = env.fromElements(new Tuple2<>("abc", 3.44)); DataSet<Tuple2<String, String>> edges = env.fromElements(new Tuple2<>("a", "c")); Graph<String, Double, NullValue> graph = Graph.fromTupleDataSet(initialVertices, edges.map(new MapFunction<Tuple2<String, String>, Tuple3<String, String, NullValue>>() { public Tuple3<String, String, NullValue> map( Tuple2<String, String> edge) { return new Tuple3<>(edge.f0, edge.f1, NullValue.getInstance()); } }), env); ScatterGatherConfiguration parameters = new ScatterGatherConfiguration(); parameters.addBroadcastSetForScatterFunction(BC_SET_MESSAGES_NAME, bcVar); parameters.addBroadcastSetForGatherFunction(BC_SET_UPDATES_NAME, bcVar); parameters.setName(ITERATION_NAME); parameters.setParallelism(ITERATION_parallelism); parameters.registerAggregator(AGGREGATOR_NAME, new LongSumAggregator()); result = graph.runScatterGatherIteration(new MessageFunctionNoEdgeValue(), new UpdateFunction(), NUM_ITERATIONS, parameters).getVertices(); result.output(new DiscardingOutputFormat<>()); // ------------- validate the java program ---------------- assertTrue(result instanceof DeltaIterationResultSet); DeltaIterationResultSet<?, ?> resultSet = (DeltaIterationResultSet<?, ?>) result; DeltaIteration<?, ?> iteration = resultSet.getIterationHead(); // check the basic iteration properties assertEquals(NUM_ITERATIONS, resultSet.getMaxIterations()); assertArrayEquals(new int[]{0}, resultSet.getKeyPositions()); assertEquals(ITERATION_parallelism, iteration.getParallelism()); assertEquals(ITERATION_NAME, iteration.getName()); assertEquals(AGGREGATOR_NAME, iteration.getAggregators().getAllRegisteredAggregators().iterator().next().getName()); // validate that the semantic properties are set as they should TwoInputUdfOperator<?, ?, ?, ?> solutionSetJoin = (TwoInputUdfOperator<?, ?, ?, ?>) resultSet.getNextWorkset(); assertTrue(solutionSetJoin.getSemanticProperties().getForwardingTargetFields(0, 0).contains(0)); assertTrue(solutionSetJoin.getSemanticProperties().getForwardingTargetFields(1, 0).contains(0)); TwoInputUdfOperator<?, ?, ?, ?> edgesJoin = (TwoInputUdfOperator<?, ?, ?, ?>) solutionSetJoin.getInput1(); // validate that the broadcast sets are forwarded assertEquals(bcVar, solutionSetJoin.getBroadcastSets().get(BC_SET_UPDATES_NAME)); assertEquals(bcVar, edgesJoin.getBroadcastSets().get(BC_SET_MESSAGES_NAME)); } // -------------------------------------------------------------------------------------------- private static class MessageFunctionNoEdgeValue extends ScatterFunction<String, Double, Long, NullValue> { @Override public void sendMessages(Vertex<String, Double> vertex) { } } private static class UpdateFunction extends GatherFunction<String, Double, Long> { @Override public void updateVertex(Vertex<String, Double> vertex, MessageIterator<Long> inMessages) { } } }
[ "1003761104@qq.com" ]
1003761104@qq.com
8c99a817c145ad986f88b81c6767d4c8cec792e3
626ee91fc0cc62c16d469d684f014ce1d8e07aa5
/src/test/java/com/causeway/api/PlannedJobsDB/Test7.java
9c618601fd1585d383644c99def6921f1f6c33bd
[]
no_license
komalgc/RestAssured
87a849ba0a256d75324de0624f743bff39922eed
add42872159e46b229cbb3221e3d9f765b103d3f
refs/heads/main
2022-12-28T17:50:53.323498
2020-10-15T01:57:11
2020-10-15T01:57:11
304,181,007
0
0
null
null
null
null
UTF-8
Java
false
false
2,109
java
package com.causeway.api.PlannedJobsDB; import com.causeway.vixen.Plannedjobssql.Plannedjobssql; import com.causway.files.Payload; import com.causway.files.Resources; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.restassured.RestAssured; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import static io.restassured.RestAssured.given; import static org.testng.Assert.assertEquals; public class Test7 { Properties prop = new Properties(); @BeforeTest public void getData() throws IOException { FileInputStream fis = new FileInputStream( "C:\\RestAssured\\src\\test\\java\\com\\causway\\files\\env.properties"); prop.load(fis); } //Get the No of planned Jobs @Test public void Test7() throws IOException { RestAssured.baseURI = prop.getProperty("HOST3"); Plannedjobssql response = given() .queryParam("count", 5) .queryParam("fromDate", Payload.FmDate()) .queryParam("toDate", Payload.ToDate()) .queryParam("includefollowons", Payload.incfoll()) .log() .all() .when() .get(Resources.getplannedjobdb()) .as(Plannedjobssql.class); //Object Mapper Class - to serialize java objects into JSON and deserialize JSON string into JAVA objects ObjectMapper objectMapper = new ObjectMapper(); String jsoninput = objectMapper.writeValueAsString(response); JsonNode node = objectMapper.readValue(jsoninput, JsonNode.class); JsonNode jobsPlanned = node.get("masterClients").findPath("jobsPlanned"); System.out.println("The size of jobsPlanned is: " + jobsPlanned.size()); System.out.println(jobsPlanned); assertEquals(jobsPlanned.size(), 5); } }
[ "komal.chowdhary@causeway.com" ]
komal.chowdhary@causeway.com
dc41bb97cccaefe9f59f7f0d544c39a304fe532f
099ffad3c706a0417e85f1bb9224d4789a720b87
/app/src/main/java/com/example/lenovo/rsssensorsdetect/FileManager.java
c084686a74ceb9f65281c46139011a039935f14b
[]
no_license
TerenceCYJ/RssSensorsDetect
05808d73717a6b629b2c6a33317de3af27282368
7233cb03e3bf1f8a0776c0f429db3adf10d51e75
refs/heads/master
2021-01-22T20:03:03.473027
2017-03-18T08:52:19
2017-03-18T08:52:19
85,279,162
0
0
null
null
null
null
UTF-8
Java
false
false
5,699
java
package com.example.lenovo.rsssensorsdetect; import android.os.Environment; import android.view.Gravity; import android.widget.Toast; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by lenovo on 2017/3/17. * 采集好的数据的存储 */ public class FileManager { /** * 这个函数每次存两个文件,"dataRssi_at_1" 和 "dataBssid.txt" * dataRssi_at_1存的是rssi和传感器数据,每个时刻的一组数据包括n个AP的rssi和15个传感器的数值,依次添加进去。 * dataBssid存的是Wifi热点一些信息,顺序和上面的对应 注意:如果已存在该文件,这个函数创建的新的文件会覆盖之前的。( * APP第一次开启获取的BSSID顺序和关闭APP再开启进行采集得到的BSSID顺序是不一样的) * 但是app的逻辑是只有改变位置后,存储在内存的数据才清零,所以同一位置的多次存储并无影响。 */ public void saveData() { saveRssiAndSensors(); // 存数据 saveWifiBssids(); // 存wifi的bssid } private void saveRssiAndSensors() { try { File sdCard = Environment.getExternalStorageDirectory();//获取的路径为手机内存 File directory = new File(sdCard.getAbsolutePath() + "/ChenRss-DataCollect"); directory.mkdirs();//在已经存在的目录中创建创建文件夹 File file = new File(directory, "dataRssi_at_" + GlobalPara.getInstance().position_index + ".txt"); FileOutputStream fOut = new FileOutputStream(file); OutputStream fos = fOut; DataOutputStream dos = new DataOutputStream(fos); for (int i = 0; i < WifiDataManager.getInstance().dataCount; i++) { // 存wifi的Rssi数据 for (int j = 0; j < WifiDataManager.getInstance().dataBssid .size(); j++) { if (WifiDataManager.getInstance().dataRssi.get(j) .containsKey(i)) { dos.write((WifiDataManager.getInstance().dataRssi .get(j).get(i) + "\t").getBytes()); } else { dos.write((0 + "\t").getBytes()); // 没有的话就存0 } } // 存传感器数据,rss后面增加15个int SensorDataManager sdm = SensorDataManager.getInstance(); String outString = sdm.dataMagnetic.get(0).get(i) + "\t" + sdm.dataMagnetic.get(1).get(i) + "\t" + sdm.dataMagnetic.get(2).get(i) + "\t" + sdm.dataOrientation.get(0).get(i) + "\t" + sdm.dataOrientation.get(1).get(i) + "\t" + sdm.dataOrientation.get(2).get(i) + "\t" + sdm.dataAccelerate.get(0).get(i) + "\t" + sdm.dataAccelerate.get(1).get(i) + "\t" + sdm.dataAccelerate.get(2).get(i) + "\t" + sdm.dataGyroscope.get(0).get(i) + "\t" + sdm.dataGyroscope.get(1).get(i) + "\t" + sdm.dataGyroscope.get(2).get(i) + "\t" + sdm.dataGravity.get(0).get(i) + "\t" + sdm.dataGravity.get(1).get(i) + "\t" + sdm.dataGravity.get(2).get(i) + "\n"; System.out.println(outString); dos.write(outString.getBytes()); } dos.close(); Toast toast = Toast.makeText( WifiDataManager.getInstance().activity, "存储至“/ChenRss-DataCollect”", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } catch (FileNotFoundException e) { Toast.makeText(WifiDataManager.getInstance().activity, "存储失败。", Toast.LENGTH_SHORT).show(); return; } catch (IOException e) { Toast.makeText(WifiDataManager.getInstance().activity, "存储失败。", Toast.LENGTH_SHORT).show(); return; } } private void saveWifiBssids() { try { File sdCard = Environment.getExternalStorageDirectory(); File directory = new File(sdCard.getAbsolutePath() + "/ChenRss-DataCollect"); directory.mkdirs(); File file = new File(directory, "dataBssid.txt"); FileOutputStream fOut = new FileOutputStream(file); OutputStream fos = fOut; DataOutputStream dos = new DataOutputStream(fos); String[] tmpOutString = new String[WifiDataManager.getInstance().dataBssid .size()]; for (String bssid : WifiDataManager.getInstance().dataBssid .keySet()) { int j = WifiDataManager.getInstance().dataBssid.get(bssid); String jString = j + 1 + "\tBSSID:\t" + bssid + "\tSSID:\t" + WifiDataManager.getInstance().dataWifiNames.get(j) + "\n"; tmpOutString[j] = jString; } for (int i = 0; i < tmpOutString.length; i++) { dos.write(tmpOutString[i].getBytes()); } dos.close(); } catch (FileNotFoundException e) { return; } catch (IOException e) { return; } } }
[ "838453422@qq.com" ]
838453422@qq.com
b57d759ee62106760edb30a9a9b3cf1d5f5e4e9b
7727df1db2dcd9e4524dd644b0e61e9c5f527f23
/app/src/androidTest/java/com/hanseltritama/multipleactivities/ExampleInstrumentedTest.java
99bcb4cc5a9d721574095accaa50b5a0f75b4a35
[]
no_license
hanselgunawan/MultipleActivities
c62738070b9624d908a416acd71f8c7ac7f3d226
3a07eae8044a6209dd3b54c9da725f87d973dfc7
refs/heads/master
2020-04-14T20:10:21.077931
2019-01-04T09:06:57
2019-01-04T09:06:57
164,084,255
0
0
null
null
null
null
UTF-8
Java
false
false
756
java
package com.hanseltritama.multipleactivities; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.hanseltritama.multipleactivities", appContext.getPackageName()); } }
[ "hanseltritama@lmhanse28337711.home" ]
hanseltritama@lmhanse28337711.home
72c7ef15813fd242eae3c08a33ee25f9ca47d56d
8bbeb7b5721a9dbf40caa47a96e6961ceabb0128
/java/37.Sudoku Solver(解数独).java
a4ba6e507ad4ae780a2547c279c77207543ade4e
[ "MIT" ]
permissive
lishulongVI/leetcode
bb5b75642f69dfaec0c2ee3e06369c715125b1ba
6731e128be0fd3c0bdfe885c1a409ac54b929597
refs/heads/master
2020-03-23T22:17:40.335970
2018-07-23T14:46:06
2018-07-23T14:46:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,858
java
/** <p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A&nbsp;sudoku solution must satisfy <strong>all of&nbsp;the following rules</strong>:</p> <ol> <li>Each of the digits&nbsp;<code>1-9</code> must occur exactly&nbsp;once in each row.</li> <li>Each of the digits&nbsp;<code>1-9</code>&nbsp;must occur&nbsp;exactly once in each column.</li> <li>Each of the the digits&nbsp;<code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li> </ol> <p>Empty cells are indicated by the character <code>&#39;.&#39;</code>.</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" style="height:250px; width:250px" /><br /> <small>A sudoku puzzle...</small></p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px" /><br /> <small>...and its solution numbers marked in red.</small></p> <p><strong>Note:</strong></p> <ul> <li>The given board&nbsp;contain only digits <code>1-9</code> and the character <code>&#39;.&#39;</code>.</li> <li>You may assume that the given Sudoku puzzle will have a single unique solution.</li> <li>The given board size is always <code>9x9</code>.</li> </ul> <p>编写一个程序,通过已填充的空格来解决数独问题。</p> <p>一个数独的解法需<strong>遵循如下规则</strong>:</p> <ol> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一行只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一列只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一个以粗实线分隔的&nbsp;<code>3x3</code>&nbsp;宫内只能出现一次。</li> </ol> <p>空白格用&nbsp;<code>&#39;.&#39;</code>&nbsp;表示。</p> <p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png"></p> <p><small>一个数独。</small></p> <p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png"></p> <p><small>答案被标成红色。</small></p> <p><strong>Note:</strong></p> <ul> <li>给定的数独序列只包含数字&nbsp;<code>1-9</code>&nbsp;和字符&nbsp;<code>&#39;.&#39;</code>&nbsp;。</li> <li>你可以假设给定的数独只有唯一解。</li> <li>给定数独永远是&nbsp;<code>9x9</code>&nbsp;形式的。</li> </ul> <p>编写一个程序,通过已填充的空格来解决数独问题。</p> <p>一个数独的解法需<strong>遵循如下规则</strong>:</p> <ol> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一行只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一列只能出现一次。</li> <li>数字&nbsp;<code>1-9</code>&nbsp;在每一个以粗实线分隔的&nbsp;<code>3x3</code>&nbsp;宫内只能出现一次。</li> </ol> <p>空白格用&nbsp;<code>&#39;.&#39;</code>&nbsp;表示。</p> <p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png"></p> <p><small>一个数独。</small></p> <p><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png"></p> <p><small>答案被标成红色。</small></p> <p><strong>Note:</strong></p> <ul> <li>给定的数独序列只包含数字&nbsp;<code>1-9</code>&nbsp;和字符&nbsp;<code>&#39;.&#39;</code>&nbsp;。</li> <li>你可以假设给定的数独只有唯一解。</li> <li>给定数独永远是&nbsp;<code>9x9</code>&nbsp;形式的。</li> </ul> **/ class Solution { public void solveSudoku(char[][] board) { } }
[ "lishulong@wecash.net" ]
lishulong@wecash.net
5330430b134294f9ad18fda3c9fcc02167c73c6f
c8e5f82ea3f650acec8430b1d9cabd05c73dc34c
/src/de/pk/model/interaktion/effekt/Effekt.java
6cc4516c63e2bb28f3bd6080910dff31923dff38
[]
no_license
SloopsaiC/Prog2PK
dcaa03c7c895154b314ba0aeccf3eb4051fa84db
727264cbf32c5d851ba6b4e31dee1bbcb5f1c522
refs/heads/master
2020-05-14T10:18:09.884401
2019-06-05T21:06:55
2019-06-05T21:06:55
181,757,292
1
0
null
null
null
null
UTF-8
Java
false
false
4,819
java
package de.pk.model.interaktion.effekt; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Ein Effekt kann die Attribute von LebendigenObjekten beeinflussen. Er hat * eine bestimmte Dauer (Anzahl an Runden), die er immer wieder aufs Neue wirkt, * bevor er schliesslich abklingt. Besteht aus "EffektTeilen", welche jeweils * eine Aenderung eines Wertes des Ziels ausdruecken */ public class Effekt { private static Map<EffektBeschreibungsIndex, EffektTeil> generiereEffektBeschreibung(EffektTeil[] effektTeile) { Map<EffektBeschreibungsIndex, EffektTeil> beschreibung = new HashMap<>(); for (EffektTeil teil : effektTeile) { beschreibung.put(teil.getIndex(), teil.clone()); } return beschreibung; } /** * Spezifiziert die Aenderungen die dieser Effekt auf ein lebendiges Objekt hat, * wenn er darauf angewandt wird. Indizies sind in * {@link}EffektBeschreibungsIndex definiert */ private Map<EffektBeschreibungsIndex, EffektTeil> effektBeschreibung = null; // Alle EffektTeile welche ueber ihren // EffektBeschreibungsIndex gesucht // werden koennen um spaeteres // Anwenden zu vereinfachen private EffektTyp typ = null; // Der Typ dieses Effektes /** * Erstellt einen Effekt, der keine Auswirkungen hat. */ public Effekt() { this(null, new EffektTeil[0]); } /** * Erstellt einen neuen Effekt mit den gegebenen Aenderungen. Welcher Index * welche Aenderung beschreibt wird durch {@link}EffektIndex beschrieben. * * @param effektBeschreibung Die Aenderungen die dieser Effekt auf ein * LebendigesObjekt hat, falls er auf dieses * angewendet wird. */ public Effekt(EffektTyp typ, EffektTeil... effektTeile) { this(typ, Effekt.generiereEffektBeschreibung(effektTeile)); } public Effekt(EffektTyp typ, Map<EffektBeschreibungsIndex, EffektTeil> effektBeschreibung) { this.typ = typ; this.effektBeschreibung = Collections.synchronizedMap(new HashMap<>(effektBeschreibung)); } @Override public Effekt clone() { return new Effekt(this.typ, this.effektBeschreibung.values().toArray(new EffektTeil[0])); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Effekt other = (Effekt) obj; return (this.typ == other.typ) && Objects.equals(this.effektBeschreibung, other.effektBeschreibung); } /** * Erstellt einen Effekt der genau den gegenteiligen Effekt zu diesem hat. * * @return Ein Effekt der die Auswirkungen dieses Effektes aufhebt */ public Effekt getNegation() { Map<EffektBeschreibungsIndex, EffektTeil> neueEffektBeschreibung = new HashMap<>(); for (EffektBeschreibungsIndex index : this.effektBeschreibung.keySet()) { neueEffektBeschreibung.put(index, new EffektTeil(index, -this.effektBeschreibung.get(index).getWert())); } return new Effekt(this.typ, neueEffektBeschreibung); } /** * @return the typ */ public EffektTyp getTyp() { return this.typ; } public int getWertAusBeschreibung(EffektBeschreibungsIndex index) { EffektTeil beschreibung = this.effektBeschreibung.get(index); if ((beschreibung == null) || this.istAbgeklungen()) { return 0; } return beschreibung.getWert(); } @Override public int hashCode() { return Objects.hash(this.effektBeschreibung, this.typ); } /** * Gibt an, ob der Effekt bereits abgeklungen ist (Wenn die WirkTicks 0 sind). * * @return true, wenn der Effekt abgeklungen ist und in der naechsten Runde * nicht mehr beruecksichtigt werden muss. */ public boolean istAbgeklungen() { return this.effektBeschreibung.get(EffektBeschreibungsIndex.ANZAHL_WIRK_TICKS).getWert() < 1; } /** * Gibt an, dass dieser Effekt ein tickender Effekt ist, also dass er nach einer * bestimmten Zeit bzw. Anzahl an Runden verstreicht und abklingt. Nur tickende * Effekte werden beim Wirken beruecksichtigt. * * @return immer true, da hier nur kurzlebige Effekte modelliert werden. Fuer * dauerhafte Effekte siehe {@link StatusEffekt}. */ public boolean istTickend() { return Boolean.TRUE; } /** * Soll jedes Mal aufgerufen werden, wenn der Effekt gewirkt wurde. Es wird die * verbleibden Anzahl an WirkTicks (Runden), die der Effekt noch wirkt, um 1 * reduziert. */ public void wurdeGewirkt() { // Die Anzahl der Wirkticks um einen vermindern EffektTeil wirkTicks = this.effektBeschreibung.get(EffektBeschreibungsIndex.ANZAHL_WIRK_TICKS); wirkTicks.setWert(wirkTicks.getWert() - 1); } }
[ "43387968+SloopsaiC@users.noreply.github.com" ]
43387968+SloopsaiC@users.noreply.github.com
9f53ea5e91114aed87579990dfaa7a3c697ef854
cd9b34120ca2ad9375c24cb1542ec5c03e80078f
/crop_image/src/main/java/com/android/camera/gallery/Image.java
3a57212374e9ab6c82e41e6050a736174ed4bafe
[ "Apache-2.0" ]
permissive
robinshang/droidddle
739d34564be1f7d9c477cf6bb26770b4676c31cc
cea4d41c1e8bbde1196e4a681b5407d102e67426
refs/heads/master
2020-12-03T01:42:23.016476
2017-04-28T09:26:25
2017-04-28T09:29:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,992
java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.gallery; import android.content.ContentResolver; import android.content.ContentValues; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ExifInterface; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore.Images; import android.provider.MediaStore.Images.ImageColumns; import android.util.Log; import com.android.camera.BitmapManager; import com.android.camera.Util; import java.io.IOException; /** * The class for normal images in gallery. */ public class Image extends BaseImage implements IImage { private static final String TAG = "BaseImage"; private static final String[] THUMB_PROJECTION = new String[]{BaseColumns._ID,}; private ExifInterface mExif; private int mRotation; public Image(BaseImageList container, ContentResolver cr, long id, int index, Uri uri, String dataPath, String mimeType, long dateTaken, String title, int rotation) { super(container, cr, id, index, uri, dataPath, mimeType, dateTaken, title); mRotation = rotation; } @Override public int getDegreesRotated() { return mRotation; } protected void setDegreesRotated(int degrees) { if (mRotation == degrees) return; mRotation = degrees; ContentValues values = new ContentValues(); values.put(ImageColumns.ORIENTATION, mRotation); mContentResolver.update(mUri, values, null, null); //TODO: Consider invalidate the cursor in container // ((BaseImageList) getContainer()).invalidateCursor(); } public boolean isReadonly() { String mimeType = getMimeType(); return !"image/jpeg".equals(mimeType) && !"image/png".equals(mimeType); } public boolean isDrm() { return false; } /** * Replaces the tag if already there. Otherwise, adds to the exif tags. * * @param tag * @param value */ public void replaceExifTag(String tag, String value) { if (mExif == null) { loadExifData(); } mExif.setAttribute(tag, value); } private void loadExifData() { try { mExif = new ExifInterface(mDataPath); } catch (IOException ex) { Log.e(TAG, "cannot read exif", ex); } } private void saveExifData() throws IOException { if (mExif != null) { mExif.saveAttributes(); } } private void setExifRotation(int degrees) { try { degrees %= 360; if (degrees < 0) degrees += 360; int orientation = ExifInterface.ORIENTATION_NORMAL; switch (degrees) { case 0: orientation = ExifInterface.ORIENTATION_NORMAL; break; case 90: orientation = ExifInterface.ORIENTATION_ROTATE_90; break; case 180: orientation = ExifInterface.ORIENTATION_ROTATE_180; break; case 270: orientation = ExifInterface.ORIENTATION_ROTATE_270; break; } replaceExifTag(ExifInterface.TAG_ORIENTATION, Integer.toString(orientation)); saveExifData(); } catch (Exception ex) { Log.e(TAG, "unable to save exif data with new orientation " + fullSizeImageUri(), ex); } } /** * Save the rotated image by updating the Exif "Orientation" tag. * * @param degrees */ public boolean rotateImageBy(int degrees) { int newDegrees = (getDegreesRotated() + degrees) % 360; setExifRotation(newDegrees); setDegreesRotated(newDegrees); return true; } public Bitmap thumbBitmap(boolean rotateAsNeeded) { Bitmap bitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; bitmap = BitmapManager.instance().getThumbnail(mContentResolver, mId, Images.Thumbnails.MINI_KIND, options, false); if (bitmap != null && rotateAsNeeded) { bitmap = Util.rotate(bitmap, getDegreesRotated()); } return bitmap; } }
[ "yfcheng@mobvoi.com" ]
yfcheng@mobvoi.com
d577fb4ae76b23e961b4275ae57d926225fa43aa
834252bcf0d878a5c6c9c5c387bff4ebfa2f4427
/mycluby-common/src/main/java/br/com/techfullit/mycluby/common/models/Employee.java
eb30695cf4c75375b8f546f8a0d14e973be9ac6a
[]
no_license
pflima92/mycluby
e2259431f020a07f83ab53477096927a91b61750
6d30df03466032329bd77e27b3f51c5975e6b70e
refs/heads/master
2021-01-23T15:27:32.894474
2015-07-14T01:49:12
2015-07-14T01:49:12
39,047,061
1
0
null
null
null
null
UTF-8
Java
false
false
3,256
java
package br.com.techfullit.mycluby.common.models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.NamedQueries; import org.hibernate.annotations.NamedQuery; import org.springframework.beans.BeanUtils; import com.fasterxml.jackson.annotation.JsonIgnore; @NamedQueries({ @NamedQuery(name = "Employee.findAllEmployers", query = "from Employee e") }) @Entity @Table(name = "EMPLOYEE") public class Employee implements Cloneable { @Id @Column(name = "ID_EMPLOYEE") @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "NAME_EMPLOYEE") private String name; @Column(name = "LOGIN") private String login; @Column(name = "PASSWORD") private String password; @JsonIgnore @ManyToOne @JoinColumn(name = "ID_ESTABLISHMENT") private Establishment establishment; @JsonIgnore @OneToMany(mappedBy = "employee", targetEntity = Sale.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL) @Fetch(FetchMode.SUBSELECT) private List<Sale> sales; @Transient private ArrayList<Role> roles; public ArrayList<Role> getRoles() { if (roles == null) roles = new ArrayList<Role>(); return roles; } @Transient public double getTotalAmount() { double totalAmount = 0; for (Sale sale : getSales()) { if (!sale.isReversalIndicative()) { if (sale.isPromotional()) { totalAmount += sale.getProduct().getPromotional(); } else { totalAmount += sale.getProduct().getPrice(); } } } return totalAmount; } public void setRoles(ArrayList<Role> roles) { this.roles = roles; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Establishment getEstablishment() { return establishment; } public void setEstablishment(Establishment establishment) { this.establishment = establishment; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public List<Sale> getSales() { return sales; } public void setSales(List<Sale> sales) { this.sales = sales; } public Employee getClone() { Employee cloned = new Employee(); BeanUtils.copyProperties(this, cloned); return cloned; } }
[ "pflima92@gmail.com" ]
pflima92@gmail.com
448a765f3aee7d67c715b2b28357a6400995957a
210c1112cefb7dac6291450a1d7752bfb5896b2a
/Messaging-Q/chatbotmaap/src/main/java/com/juphoon/chatbotmaap/chatbotSearch/RcsChatbotSearchFragment.java
d4eef3b4d430a2804eef96ffe576efdf23821ddb
[]
no_license
zhaotianyu1/message
cc5fcd0b4016e53f5821f99491d8efe36e46f97e
01540a65d5f95becbf353cd3fb555fd46b4a61da
refs/heads/master
2023-07-01T23:55:07.006623
2021-08-13T01:41:34
2021-08-13T01:41:34
395,486,650
0
0
null
null
null
null
UTF-8
Java
false
false
14,674
java
package com.juphoon.chatbotmaap.chatbotSearch; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.fragment.app.Fragment; import androidx.lifecycle.Lifecycle; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.gson.Gson; import com.juphoon.chatbot.RcsChatbotSearchBean; import com.juphoon.chatbotmaap.R; import com.juphoon.chatbotmaap.RcsChatbotDeepLink; import com.juphoon.chatbotmaap.RcsChatbotUtils; import com.juphoon.chatbotmaap.RcsLocalChatbotActivity; import com.juphoon.chatbotmaap.tcl.SimpleItemDecoration; import com.juphoon.chatbotmaap.view.TextViewSnippet; import com.juphoon.helper.RcsBroadcastHelper; import com.juphoon.helper.RcsChatbotHelper; import com.juphoon.helper.RcsTokenHelper; import com.juphoon.rcs.tool.RcsCallWrapper; import com.juphoon.service.RmsDefine; import com.tcl.uicompat.TCLButton; import com.tcl.uicompat.TCLEditText; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class RcsChatbotSearchFragment extends Fragment { private String TAG = RcsChatbotSearchFragment.class.getSimpleName(); private TCLEditText mSearchView; private SearchInfo mSearchInfo; private RecyclerView mChatBotListView; private RcsChatbotListLoadMoreAdapter mChatBotsListAdapter; private Activity mHost; private ProgressBar mProgressBar; private ImageView mLocationView; private RcsBroadcastHelper.IChatbotListener mChatbotListner; private class SearchInfo { String searchKey; int start; int totalItems; String cookie = ""; int perSearchNumber = 10; } @NonNull @Override public Lifecycle getLifecycle() { return super.getLifecycle(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public static RcsChatbotSearchFragment newInstance() { Bundle args = new Bundle(); RcsChatbotSearchFragment fragment = new RcsChatbotSearchFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.chatbot_search_fragment, container, false); mHost = getActivity(); // initLocationView(view); initSearchView(view); initProgressBar(view); initChatBotsListView(view); initRefreshView(view); refreshLocalChatBotsData(); Log.i("ooo","mChatBotsListAdapter.getItemCount() :"+mChatBotsListAdapter.getItemCount()); if(mChatBotsListAdapter.getItemCount() ==0){ Log.i("ooo","false"); mChatBotListView.setFocusable(false); }else{ Log.i("ooo","true"); mChatBotListView.setFocusable(true); } return view; } private void initRefreshView(View view) { // // SwipeRefreshLayout refreshView = view.findViewById(R.id.swipe_refresh); // refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // // } // }); } private TCLButton buttadd2; private void initLocationView(View view) { mLocationView = view.findViewById(R.id.location_view); mLocationView.setPressed(true); mLocationView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } private void initProgressBar(View view) { mProgressBar = view.findViewById(R.id.loading_progressBar); } private void showProgressBar() { if (mProgressBar != null) { mProgressBar.setVisibility(View.VISIBLE); } } private void cancelProgressBar() { if (mProgressBar != null) { mProgressBar.setVisibility(View.GONE); } } private void initSearchView(View view) { AppCompatActivity activity = (AppCompatActivity) getActivity(); final LinearLayout tags_log = activity.findViewById(R.id.tags_log); mSearchView = view.findViewById(R.id.search_view); mSearchView.setFocusable(true); mSearchView.setFocusableInTouchMode(true); mSearchView.requestFocus(); mSearchView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { switch (actionId) { case EditorInfo.IME_ACTION_SEARCH: mSearchInfo = new SearchInfo(); mSearchInfo.start = 0; mSearchInfo.searchKey = mSearchView.getText().toString(); mSearchInfo.totalItems = 0; mSearchInfo.cookie = UUID.randomUUID().toString(); mSearchView.clearFocus(); searchNet(mSearchInfo); showProgressBar(); break; default: break; } return false; } }); //搜索界面的动态查询 mSearchView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { mSearchInfo = new SearchInfo(); mSearchInfo.start = 0; mSearchInfo.searchKey = mSearchView.getText().toString(); mSearchInfo.totalItems = 0; mSearchInfo.cookie = UUID.randomUUID().toString(); if(charSequence.length()>0){ tags_log.setVisibility(View.GONE); }else{ tags_log.setVisibility(View.VISIBLE); } // mSearchView.clearFocus(); searchNet(mSearchInfo); showProgressBar(); } @Override public void afterTextChanged(Editable s) { } }); // mSearchView.setIconified(false); // mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // // } // }); // mSearchView.setOnCloseListener(new SearchView.OnCloseListener() { // @Override // public boolean onClose() { // // // return true; // } // }); // mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // @Override // public boolean onQueryTextSubmit(String query) { // if (TextUtils.isEmpty(query)) { // Toast.makeText(mHost, R.string.chatbot_enter_search_key, Toast.LENGTH_SHORT).show(); // return true; // } // mSearchInfo = new SearchInfo(); // mSearchInfo.start = 0; // mSearchInfo.searchKey = query; // mSearchInfo.totalItems = 0; // mSearchInfo.cookie = UUID.randomUUID().toString(); // mSearchView.clearFocus(); // searchNet(mSearchInfo); // showProgressBar(); // return false; // } // // @Override // public boolean onQueryTextChange(String newText) { // if(TextUtils.isEmpty(newText)){ // refreshLocalChatBotsData(); // } // return true; // } // }); mChatbotListner = new RcsBroadcastHelper.IChatbotListener() { @Override public void onChatbotRecommandList(String s, boolean b, String s1) { } @Override public void onChatbotList(String cookie, boolean result, String json) { cancelProgressBar(); if (mSearchInfo == null || !TextUtils.equals(cookie, mSearchInfo.cookie)) { return; } if (result) { //处理推荐列表 List<RcsChatbotHelper.RcsChatbot> recommendBots = RcsChatbotHelper.parseChatbotRecommendListJson(json); if (recommendBots == null || recommendBots.size() == 0) { } else { } //处理搜索结果 RcsChatbotSearchBean rcsChatbotSearchBean = new Gson().fromJson(json, RcsChatbotSearchBean.class); mSearchInfo.start = rcsChatbotSearchBean.startIndex + rcsChatbotSearchBean.itemsReturned; mSearchInfo.totalItems = rcsChatbotSearchBean.totalItems; List<RcsChatbotHelper.RcsChatbot> temp = RcsChatbotHelper.parseChatbotListJson(json); if (mChatBotsListAdapter != null) { mChatBotsListAdapter.setEmptyViewText(getString(R.string.chatbot_empty_net)); mChatBotsListAdapter.setChatbots(temp); mChatBotsListAdapter.notifyDataSetChanged(); if (mSearchInfo.start >= mSearchInfo.totalItems) { mChatBotsListAdapter.setLoadState(RcsChatbotListLoadMoreAdapter.LOADING_END); } } } else { Toast.makeText(mHost, R.string.chatbot_search_fail, Toast.LENGTH_SHORT).show(); } } @Override public void onChatbotInfo(String s, boolean b, String s1) { } }; RcsBroadcastHelper.addChatbotListener(mChatbotListner); } private void searchNet(final SearchInfo searchInfo) { //todo Dialog RcsTokenHelper.getToken(new RcsTokenHelper.ResultOperation() { @Override public void run(boolean succ, String resultCode, String token) { boolean requestResult = succ; if (succ) { if (RcsCallWrapper.rcsGetChatbotList(searchInfo.cookie, token, searchInfo.perSearchNumber, searchInfo.start, searchInfo.searchKey) > 0) { requestResult = true; } else { Toast.makeText(mHost, R.string.chatbot_search_fail, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(mHost, "get token fail", Toast.LENGTH_SHORT).show(); } if (!requestResult) { cancelProgressBar(); } } }); } private void clearChatbotLists() { if (mChatBotsListAdapter != null) { mChatBotsListAdapter.setChatbots(null); mChatBotsListAdapter.notifyDataSetChanged(); } } private void refreshLocalChatBotsData() { showProgressBar(); Log.d(TAG, "refreshLocalChatBotsData"); //刷新本地chatbot列表 new AsyncTask<Void, Void, List<RcsChatbotHelper.RcsChatbot>>() { @Override protected List<RcsChatbotHelper.RcsChatbot> doInBackground(Void... voids) { List<RcsChatbotHelper.RcsChatbot> result = new ArrayList<>(); Cursor cursor = mHost.getContentResolver().query(RmsDefine.ChatbotInfo.CONTENT_URI, null, RmsDefine.ChatbotInfo.SAVELOCAL + "=1", null, null); if (cursor != null) { try { while (cursor.moveToNext()) { RcsChatbotHelper.RcsChatbot info = new RcsChatbotHelper.RcsChatbot(); info.name = cursor.getString(cursor.getColumnIndex(RmsDefine.ChatbotInfo.NAME)); info.icon = cursor.getString(cursor.getColumnIndex(RmsDefine.ChatbotInfo.ICON)); info.serviceId = cursor.getString(cursor.getColumnIndex(RmsDefine.ChatbotInfo.SERVICEID)); result.add(info); } } finally { cursor.close(); } } return result; } @Override protected void onPostExecute(List<RcsChatbotHelper.RcsChatbot> rcsChatbots) { if (mChatBotsListAdapter != null) { mChatBotsListAdapter.setEmptyViewText(getActivity().getString(R.string.chatbot_empty_local)); mChatBotsListAdapter.setChatbots(rcsChatbots); mChatBotsListAdapter.setLoadState(RcsChatbotListLoadMoreAdapter.LOADING_COMPLETE); mChatBotsListAdapter.notifyDataSetChanged(); } cancelProgressBar(); } }.execute(); } private void initChatBotsListView(View view) { mChatBotListView = view.findViewById(R.id.chatBots_recyclerView); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mHost); mChatBotListView.setLayoutManager(linearLayoutManager); mChatBotsListAdapter = new RcsChatbotListLoadMoreAdapter(mHost); mChatBotListView.setAdapter(mChatBotsListAdapter); mChatBotListView.addItemDecoration(new SimpleItemDecoration()); } @Override public void onDestroyView() { RcsBroadcastHelper.removeChatbotListener(mChatbotListner); super.onDestroyView(); } }
[ "tianyu_zhao@tcl.com" ]
tianyu_zhao@tcl.com
172bed9b2ba16702043a30bf3c87fa018595c48d
fef4770466c1e988792c983f494910dbbf8f9e0e
/app/src/main/java/com/synertone/dynamicskin/widget/RuntimeRationale.java
60c24cd121b773f8bb09cf3b3e1f1c294850f970
[]
no_license
yuxinabc/dynamicSkin
448c576a1a61c2aeeec8657d39b96b9dbe07ba05
db1fc383d9e4c56ee6080185a245d2941365815c
refs/heads/master
2020-03-17T09:08:52.371728
2018-05-18T07:07:30
2018-05-18T07:07:30
132,857,400
0
0
null
null
null
null
UTF-8
Java
false
false
1,547
java
package com.synertone.dynamicskin.widget; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.text.TextUtils; import com.synertone.dynamicskin.R; import com.yanzhenjie.permission.Permission; import com.yanzhenjie.permission.Rationale; import com.yanzhenjie.permission.RequestExecutor; import java.util.List; public final class RuntimeRationale implements Rationale<List<String>> { @Override public void showRationale(Context context, List<String> permissions, final RequestExecutor executor) { List<String> permissionNames = Permission.transformText(context, permissions); String message = context.getString(R.string.message_permission_rationale, TextUtils.join("\n", permissionNames)); new AlertDialog.Builder(context) .setCancelable(false) .setTitle(R.string.title_dialog) .setMessage(message) .setPositiveButton(R.string.resume, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { executor.execute(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { executor.cancel(); } }) .show(); } }
[ "snt1231@techtone.com" ]
snt1231@techtone.com
cf17c95c5aa390a81f5392d5c8394169b7b2dee3
e9daeea80ddb2fa64b6ba57addf14e363b497a79
/commonwebitems/src/uk/co/tui/fo/book/facade/impl/BookFacadeImpl.java
138e9a4227b126eb383f4281c97a6cac9884f9c7
[]
no_license
gousebashashaik/16.2.0.0
99922b8d5bf02cde3a8bf24dc7e044852078244f
4374ee6408d052df512a82e54621facefbf55f32
refs/heads/master
2021-01-10T10:51:51.288078
2015-09-29T09:30:14
2015-09-29T09:30:14
43,352,196
1
1
null
null
null
null
UTF-8
Java
false
false
16,188
java
/** * */ package uk.co.tui.fo.book.facade.impl; import de.hybris.platform.cms2.servicelayer.services.CMSSiteService; import de.hybris.platform.servicelayer.model.ModelService; import de.hybris.platform.servicelayer.session.SessionService; import de.hybris.platform.util.Config; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import uk.co.portaltech.commons.StringUtil; import uk.co.portaltech.travel.model.results.Holiday; import uk.co.portaltech.tui.web.view.data.WebAnalytics; import uk.co.tui.async.logging.TUILogUtils; import uk.co.tui.book.cart.services.PackageCartService; import uk.co.tui.book.comparator.feedback.Feedback; import uk.co.tui.book.domain.lite.BasePackage; import uk.co.tui.book.domain.lite.HighLights; import uk.co.tui.book.domain.lite.InclusivePackage; import uk.co.tui.book.domain.lite.InventoryType; import uk.co.tui.book.exception.BookServiceException; import uk.co.tui.book.exception.FlightSoldOutException; import uk.co.tui.book.payment.request.PaymentRequest; import uk.co.tui.book.services.PackageBookingService; import uk.co.tui.book.services.PackageComponentService; import uk.co.tui.book.services.inventory.CheckPriceAvailabilityService; import uk.co.tui.book.services.payment.PackagePaymentService; import uk.co.tui.book.utils.DefaultStaticContentWrapper; import uk.co.tui.book.utils.PackageUtilityService; import uk.co.tui.fo.book.constants.SessionObjectKeys; import uk.co.tui.fo.book.facade.BookFacade; import uk.co.tui.fo.book.populators.AlertPassengerViewDataPopulator; import uk.co.tui.fo.book.populators.AlertPopulator; import uk.co.tui.fo.book.populators.BookingDetailsViewDataPopulator; import uk.co.tui.fo.book.populators.HolidayInclusivePackagePopulator; import uk.co.tui.fo.book.store.CarHireUpgradeExtraFacilityStore; import uk.co.tui.fo.book.store.PackageExtraFacilityStore; import uk.co.tui.fo.book.view.data.AlertViewData; import uk.co.tui.fo.book.view.data.BookingDetailsViewData; import uk.co.tui.fo.exception.TUIBusinessException; import uk.co.tui.fo.exception.TUISystemException; import uk.co.tui.services.data.MultiCentreData; import uk.co.tui.services.item.LinkedItemService; import uk.co.tui.web.common.constants.CommonwebitemsConstants; /** * The Class BookFacadeImpl. * * @author extps3 */ public class BookFacadeImpl implements BookFacade { /** The holiday inclusive package populator. */ @Resource(name = "foHolidayInclusivePackagePopulator") private HolidayInclusivePackagePopulator holidayInclusivePackagePopulator; /** The model service. */ @Resource private ModelService packageModelService; @Resource private PackageComponentService packageComponentService; /** The session service. */ @Resource private SessionService sessionService; /** The package cart service. */ @Resource private PackageCartService packageCartService; /** The info book inventory service. */ @Resource private CheckPriceAvailabilityService checkPriceAvailabilityService; @Resource private PackageBookingService packageBookingService; /** The Payment Service . */ @Resource private PackagePaymentService packagePaymentService; /** The static page content service. */ @Resource private DefaultStaticContentWrapper staticContentServ; /** The linked item service. */ @Resource(name = "mainStreamTrvelLinkedItemService") private LinkedItemService linkedItemService; /** AlertViewData Populator . */ @Resource(name = "foAlertPopulator") private AlertPopulator alertPopulator; /** AlertPassengerViewDataPopulator */ @Resource(name = "foAlertPassengerViewDataPopulator") private AlertPassengerViewDataPopulator alertPassengerViewDataPopulator; @Resource(name = "foBookingDetailsViewDataPopulator") private BookingDetailsViewDataPopulator bookingDetailsViewDataPopulator; /** The Constant LOGGER. */ // private static final Logger LOGGER = private static final TUILogUtils LOGGER = new TUILogUtils("BookFacadeImpl"); /** The Constant TUI_EXCEPTION. */ private static final String TUI_EXCEPTION = "TUISystemException : "; private static final String MULTICOMERROR_PREFIX = "MC"; /** The cms site service. */ @Resource private CMSSiteService cmsSiteService; /** Custom Sold Out Error Code */ public static final String CUSTOM_SOLDOUTERRORCODE = "99999"; public static final String SALES_CHANNEL = "WEB"; /* * (non-Javadoc) * * @see uk.co.tui.th.book.facade.BookFacade#populateInclusivePackage * (uk.co.portaltech.travel.model.results.Holiday) */ @Override public BasePackage populatePackage(final Holiday holiday) { final BasePackage inclusivePackage = new InclusivePackage(); holidayInclusivePackagePopulator.populate(holiday, inclusivePackage); packageModelService.save(inclusivePackage); // store the packageCode for future reference // sessionService.setAttribute("packageCode", // store the packageModel sessionService.setAttribute("bookFlowPackageData", inclusivePackage); return inclusivePackage; } /** * Checks if the holiday package's price is changed. * * @param holidayPackage the holiday package * @param latestPacakgeFromInventory the latest pacakge from inventory * @return true, if there is a price change */ public boolean hasPriceChanged(final BasePackage holidayPackage, final BasePackage latestPacakgeFromInventory) { if (holidayPackage.equals(latestPacakgeFromInventory)) { return true; } return false; } /** * This method handles the infants not yet born scenario against the inventory. */ @Override public AlertViewData checkInfantNotYetBornCase() { final AlertViewData alertViewdata = new AlertViewData(); final Feedback feedback = new Feedback(); alertPassengerViewDataPopulator.populate(feedback, alertViewdata); return alertViewdata; } /** * this method checks the price and availability of the selected package against the inventory. */ @Override public List<AlertViewData> checkPriceAndAvailability() throws TUIBusinessException, FlightSoldOutException { List<Feedback> feedBackList = Collections.emptyList(); try { final BasePackage basePackage = packageCartService.getBasePackage(); feedBackList = checkPriceAvailabilityService.updatePriceAndAvailability(basePackage, InventoryType.ATCOM == basePackage.getInventory().getInventoryType()); } catch (final BookServiceException e) { handleBookServiceException(e); } List<AlertViewData> alertViewDataList = new ArrayList<AlertViewData>(); alertViewDataList = alertPopulator.populateTotalCostAlert(alertViewDataList, feedBackList); return alertViewDataList; } /** * @param e * @throws FlightSoldOutException * @throws TUIBusinessException */ private void handleBookServiceException(final BookServiceException e) throws FlightSoldOutException, TUIBusinessException { final List<String> multicomErrorCodes = Arrays.asList(StringUtils.split(Config.getParameter("multicom_error_codes"), ',')); final String errorCode = StringUtils.trim(e.getErrorCode()); if (multicomErrorCodes.contains(errorCode) || StringUtils.startsWithIgnoreCase(errorCode, MULTICOMERROR_PREFIX)) { throw new FlightSoldOutException(e.getErrorCode(), e); } LOGGER.error(TUI_EXCEPTION + e.getMessage()); final List<String> soldOutErrorCodes = Arrays.asList(StringUtils.split(Config.getParameter("soldOutErrorCodes"), ',')); if (isSoldoutError(e.getErrorCode(), soldOutErrorCodes)) { throw new TUIBusinessException(e.getErrorCode(), e.getCustomMessage(), e); } else { throw new TUISystemException(e.getErrorCode(), e.getCustomMessage(), e); } } /** * Checks if is soldout error. * * @param errorCode the error code * @param soldOutErrorCodes * @return true if the error is of type soldout error */ private boolean isSoldoutError(final String errorCode, final List<String> soldOutErrorCodes) { // Comparison logic has been moved to TibcoSoapFaultHandler return PackageUtilityService.isSoldOutErrorMatches(errorCode, soldOutErrorCodes); } /** * This method is called to render the confirmation page after successful booking. * */ @Override public BookingDetailsViewData confirmBooking() { final BookingDetailsViewData bookingDetailsViewData = new BookingDetailsViewData(); try { packageBookingService.confirmBooking(); } catch (final BookServiceException e) { LOGGER.error("Caught BookServiceExcepion " + e.getMessage(), e); } bookingDetailsViewDataPopulator.populate(packageCartService.getBasePackage(), bookingDetailsViewData); return bookingDetailsViewData; } /* * (non-Javadoc) * * @see uk.co.tui.th.book.facade.BookFacade#getPaymentPageRelativeUrl(uk.co.tui. * domain.model.InclusivePackageModel, java.lang.String, java.util.Map) */ @Override public String getPaymentPageRelativeUrl(final Map<String, String> urlMap, final String hostName, final String contextPath) throws FlightSoldOutException, TUIBusinessException { String[] paymentTokens = null; final String brandType = cmsSiteService.getCurrentSite().getUid(); final PaymentRequest paymentRequest = new PaymentRequest(); paymentRequest.setHostApplicationUrl(hostName); paymentRequest.getStepIndicators().putAll(urlMap); paymentRequest.setPrePaymentUrl(StringUtil.append(hostName, Config.getParameter(brandType + "_PRE_PAYMENT_URL"))); paymentRequest.setPaymentFailureUrl(StringUtil.append(hostName, Config.getParameter(brandType + "_PAYMENT_FAILURE_URL"))); paymentRequest.setClientURL(StringUtil.append(Config.getParameter(brandType + ".S2.home.page.url"))); paymentRequest.setBookingSessionIdentifier(sessionService.getCurrentSession().getSessionId()); paymentRequest.setClientApplication(brandType); paymentRequest.setSalesChannel(SALES_CHANNEL); populateWebAnalyticsData(paymentRequest); populateMultiCentreData(paymentRequest); final Map<String, String> toolTipsMap = new HashMap<String, String>(); toolTipsMap.putAll(staticContentServ.getPaymentContents()); paymentRequest.setToolTips(toolTipsMap); // Info book would be fired here try { final List<AlertViewData> alertViewDataList = checkPriceAndAvailability(); populateAlertViewData(paymentRequest, alertViewDataList); } catch (final TUIBusinessException e) { throw new TUIBusinessException(e.getErrorCode(), e.getCustomMessage(), e); } paymentTokens = packagePaymentService.getPaymentTokens(paymentRequest); // YTODO: correct below code. paymentRequest.setToken(paymentTokens[0]); paymentRequest.setServerInstance(paymentTokens[1]); sessionService.setAttribute(SessionObjectKeys.PAYMENTREQUEST, paymentRequest); return getPaymentPageRelativeUrl(paymentTokens); } /** * @param paymentRequest * @param alertViewDataList */ private void populateAlertViewData(final PaymentRequest paymentRequest, final List<AlertViewData> alertViewDataList) { final StringBuilder alertViewData = new StringBuilder(); for (final AlertViewData data : alertViewDataList) { alertViewData.append(data.getMessageText()); } paymentRequest.setAlertMessage(alertViewData.toString()); } /** * Populate multi centre data. * * @param paymentRequest the payment request */ private void populateMultiCentreData(final PaymentRequest paymentRequest) { if (packageCartService.getBasePackage().getListOfHighlights() .contains(HighLights.MULTI_CENTRE)) { paymentRequest.setMultiCentreData(convertMultiCentreData(linkedItemService .getMultiCentreData(packageComponentService .getStay(packageCartService.getBasePackage()).getCode()))); } } /** * Convert multi centre data. * * @param multiCentreData the multi centre data * @return the map */ private Map<String, List<String>> convertMultiCentreData( final List<MultiCentreData> multiCentreData) { final String name = "NAME"; final String duration = "DURATION"; final String location = "LOCATION"; final String nights = " nights "; final Map<String, List<String>> paymentData = new HashMap<String, List<String>>(); paymentData.put(name, new ArrayList<String>()); paymentData.put(location, new ArrayList<String>()); paymentData.put(duration, new ArrayList<String>()); for (final MultiCentreData eachData : multiCentreData) { paymentData.get(name).add(eachData.getName()); paymentData.get(location).add((String) eachData.getLocations().values().iterator().next()); paymentData.get(duration).add( new StringBuilder(eachData.getDuration()).append(nights).append(eachData.getName()) .toString()); } return paymentData; } /** * Populates the web analytics data onto payment request * * @param paymentRequest */ private void populateWebAnalyticsData(final PaymentRequest paymentRequest) { final List<WebAnalytics> webAnalyticsData = sessionService.getAttribute("webAnalyticData"); if (CollectionUtils.isNotEmpty(webAnalyticsData)) { final Map<String, String> webAnalyticsMap = new HashMap<String, String>(); for (final WebAnalytics webAnalytics : webAnalyticsData) { if (webAnalytics != null) { webAnalyticsMap.put(webAnalytics.getKey(), webAnalytics.getValue()); paymentRequest.setWebAnalyticsData(webAnalyticsMap); } } } } /** * Gets the payment page relative url. * * @param paymentTokens the payment tokens * @return paymentPage Relative Url */ private String getPaymentPageRelativeUrl(final String[] paymentTokens) { final MessageFormat url = new MessageFormat(CommonwebitemsConstants.PAYMENT_RELATIVE_URL); return url.format(paymentTokens); } @Override public void flushSessionObjects() { final PackageExtraFacilityStore packageExtraFacilityStore = sessionService.getAttribute("PackageExtraFacilityStore"); if (packageExtraFacilityStore != null) { packageExtraFacilityStore.flush(); sessionService.removeAttribute("PackageExtraFacilityStore"); } final CarHireUpgradeExtraFacilityStore carHireUpgradeExtraFacilityStore = sessionService.getAttribute("carHireUpgradeExtraFacilityStore"); if (carHireUpgradeExtraFacilityStore != null) { carHireUpgradeExtraFacilityStore.flush(); sessionService.removeAttribute("carHireUpgradeExtraFacilityStore"); } } @Override public boolean isPreAuthSuccess() { return packageBookingService.isPreAutherisationSuccess(); } }
[ "gousebasha.s@sonata-software.com" ]
gousebasha.s@sonata-software.com
fe28e121d1d96aa9efa6a3b43b438cd92492cffb
c19435aface677d3de0958c7fa8b0aa7e3b759f3
/base/config/src/main/java/org/artifactory/descriptor/security/PasswordExpirationPolicy.java
1295aca5c3de2158804af95edb0a58e8e202ae73
[]
no_license
apaqi/jfrog-artifactory-5.11.0
febc70674b4a7b90f37f2dfd126af36b90784c28
6a4204ed9ce9334d3eb7a8cb89c1d9dc72d709c1
refs/heads/master
2020-03-18T03:13:41.286825
2018-05-21T06:57:30
2018-05-21T06:57:30
134,229,368
0
0
null
null
null
null
UTF-8
Java
false
false
2,345
java
/* * * Artifactory is a binaries repository manager. * Copyright (C) 2016 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. * */ package org.artifactory.descriptor.security; import lombok.Data; import org.artifactory.descriptor.Descriptor; import org.jfrog.common.config.diff.GenerateDiffFunction; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.Optional; /** * Password expiration configuration * * @author Michael Pasternak */ @XmlType(name = "PasswordExpirationPolicyType", propOrder = {"enabled", "passwordMaxAge", "notifyByEmail", "currentPasswordValidFor"}, namespace = Descriptor.NS ) @GenerateDiffFunction @Data public class PasswordExpirationPolicy implements Descriptor { @XmlElement(defaultValue = "false", required = false) private Boolean enabled = false; /** * number of days for password to get expired (general password live time) */ @XmlElement(defaultValue = "60", required = false) private Integer passwordMaxAge = 60; @XmlElement(defaultValue = "true", required = false) private Boolean notifyByEmail = true; /** * number of days till password should be changed */ @XmlElement(required = false) private Integer currentPasswordValidFor; public void setNotifyByEmail(Boolean notifyByEmail) { this.notifyByEmail = Optional.ofNullable(notifyByEmail).orElse(true); } public void setEnabled(Boolean enabled) { this.enabled = Optional.ofNullable(enabled).orElse(false); } public void setPasswordMaxAge(Integer passwordMaxAge) { this.passwordMaxAge = Optional.ofNullable(passwordMaxAge).orElse(60); } }
[ "wangpeixuan00@126.com" ]
wangpeixuan00@126.com
79cbfeef64ea478fe0704e1ca8d605890a576187
3d22c538fe6337ca57abbcbe708ad8a7b61ccda4
/Homework 7/src/main/carPark/ICarPark.java
11a8257958b7ceccb0c8deeaad90e5cdf3029bf7
[]
no_license
Emmilaze/hillel_hw
e60130229ac89c19db217861979798a47f289c6b
ae6d031856a3c78b2121d1cc63d81b9dac59c748
refs/heads/master
2022-09-25T11:04:01.171729
2020-03-30T16:46:02
2020-03-30T16:46:02
224,016,367
0
1
null
2022-09-08T01:06:17
2019-11-25T18:36:40
Java
UTF-8
Java
false
false
202
java
package main.carPark; import main.vehicle.Car; import java.util.List; public interface ICarPark { List<Car> sortByFuel(); List<Car> findBySpeed(int min, int max); int countAllCost(); }
[ "" ]
f787f8d0bcb9f69f09f1fa8b20e55a78cd469614
e909f9a8870595a66ec964adebd5851162344446
/code-jam/minimum-scalar-product/Main.java
24eb298bc8277e6f826a18d3dd97d8cc9eb2a393
[]
no_license
sudonatalie/interview-prep
a2d8147b9569ee563e235a55e453b752234c48dd
fdcee149549bada1d86ae0aebbb07e4b75fd1a90
refs/heads/master
2021-09-08T13:57:30.883963
2018-03-10T03:38:33
2018-03-10T03:38:33
77,062,196
1
0
null
null
null
null
UTF-8
Java
false
false
1,001
java
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int cases = in.nextInt(); for (int i = 1; i <= cases; i++) { // Vector length int n = in.nextInt(); // Capture vector coordinates long[] v1 = new long[n]; long[] v2 = new long[n]; for (int j = 0; j < n; j++) { v1[j] = in.nextLong(); } for (int j = 0; j < n; j++) { v2[j] = in.nextLong(); } // Sort arrays Arrays.sort(v1); Arrays.sort(v2); // Calculate min scalar product long prod = 0; for (int j = 0; j < n; j++) { prod += v1[j] * v2[n - 1 - j]; } // Output System.out.println("Case #" + i + ": " + prod); } } }
[ "nmperna@gmail.com" ]
nmperna@gmail.com
1959c01091982add0ee0b2f9cc9a00575cbac6c2
69e336d4c9c58fff7c93395339cc0f840e31601c
/src/main/com/idamobile/vpb/courier/navigation/AlwaysOpenNewNavigationController.java
42f4b6c7b250b3202e02ca40eac3acac781b2c23
[]
no_license
idamobile/vpb-courier-app
d8ee1f4cad11a05c4e82b492defcee37c3affb43
760b5a271e6de21b4ea140d68f4e1b29f9de151a
refs/heads/master
2021-01-11T02:08:55.045189
2014-02-20T08:07:30
2014-02-20T08:07:30
8,136,215
0
1
null
null
null
null
UTF-8
Java
false
false
2,393
java
package com.idamobile.vpb.courier.navigation; import android.app.Activity; import android.content.Context; import android.content.Intent; import com.idamobile.vpb.courier.ApplicationMediator; import com.idamobile.vpb.courier.CoreApplication; import com.idamobile.vpb.courier.LoginActivity; import com.idamobile.vpb.courier.OrderListActivity; public class AlwaysOpenNewNavigationController extends AbstractNavigationController { private static final int NEXT_ACTIVITY_REQUEST_CODE = 2209; private RootActivityBackButtonController backButtonController; public AlwaysOpenNewNavigationController(Context context) { super(context, new AlwaysOpenNewNavigationMethodFactory()); if (context instanceof Activity) { backButtonController = new RootActivityBackButtonController((Activity) getContext()); } } @Override public boolean onBackPressed() { Activity activity = (Activity) getContext(); ApplicationMediator mediator = CoreApplication.getMediator(activity); boolean loggedIn = mediator.getLoginManager().isLoggedIn(); boolean hasPrevious = AlwaysOpenNewNavigationUtils.hasPreviousActivity(activity); if (loggedIn && !hasPrevious && backButtonController.dispatchOnBackPressed()) { return true; } else { if (activity instanceof OrderListActivity) { mediator.getLoginManager().logout(); activity.setResult(Activity.RESULT_OK); } return false; } } @Override public void onCreate() { } @Override public void onNewIntent(Intent intent) { } @Override public void processSuccessLogin() { getOrdersList().startForResult(NEXT_ACTIVITY_REQUEST_CODE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Activity activity = (Activity) getContext(); if (activity instanceof LoginActivity) { if (requestCode == NEXT_ACTIVITY_REQUEST_CODE) { activity.finish(); } } } @Override public void processSignOut() { NavigationMethod method = getLogin(); if (method instanceof AlwaysOpenNewLoginNavigationMethod) { ((AlwaysOpenNewLoginNavigationMethod) method).setSignOut(); } method.start(); } }
[ "shaubert.alexander@gmail.com" ]
shaubert.alexander@gmail.com
79a7e564cab5bda8686826ccf355058cef1e3439
77b7075cf4f0db533ec08407144eb4a82ccf185f
/src/br/com/caelum/leilao/teste/UsuariosWSTest.java
fa999e83e8f7359da7ef990abfb29382c387e100
[]
no_license
alxlino/RestAssuredAlura
9b8871407077149334d494a374bccbc43744acfb
13a9f9e2360507e424d33a4c089c3d4bcef44420
refs/heads/master
2020-04-01T22:30:05.878115
2018-10-19T01:57:59
2018-10-19T01:57:59
153,711,976
0
0
null
null
null
null
UTF-8
Java
false
false
3,454
java
package br.com.caelum.leilao.teste; import static com.jayway.restassured.RestAssured.given; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.jayway.restassured.path.xml.XmlPath; import br.com.caelum.leilao.modelo.Usuario; public class UsuariosWSTest { // @Test // public void deveRetornarListaDeUsuariosXml() { // // //http://localhost:8080/usuarios?_format=xml // // XmlPath path = given().header("accept","application/xml") // .get("/usuarios?_format=xml").andReturn().xmlPath(); // // List<Usuario> usuarios = path.getList("list.usuario", Usuario.class); // // Usuario esperado1 = new Usuario(1L,"Mauricio Aniche","mauricio.aniche@caelum.com.br"); // Usuario esperado2 = new Usuario(2L,"Guilherme Silveira","guilherme.silveira@caelum.com.br"); // // assertEquals(esperado1,usuarios.get(0)); // assertEquals(esperado2,usuarios.get(1)); // } // @Test // public void deveRetornarUsuarioPorIDJson() { // // //http://localhost:8080/usuarios/show?usuario.id=1&_format=json // //http://localhost:8080/leiloes/show?leilao.id=1&_format=json // // JsonPath path = given() // .header("accept","application/json") // .parameter("usuario.id", 1) // .get("/usuarios/show") // .andReturn() // .jsonPath(); // // Usuario usuario = path.getObject("usuario",Usuario.class); // Usuario esperado1 = new Usuario(1L,"Mauricio Aniche","mauricio.aniche@caelum.com.br"); // assertEquals(esperado1,usuario); // // } // @Test // public void deveRetornarLeilaoPorIDJson() { // // //http://localhost:8080/usuarios/show?usuario.id=1&_format=json // //http://localhost:8080/leiloes/show?leilao.id=1&_format=json // // JsonPath path = given() // .header("accept","application/json") // .parameter("leilao.id", 1) // .get("/leiloes/show") // .andReturn() // .jsonPath(); // // Leilao leilao = path.getObject("leilao", Leilao.class); // Usuario usuario = new Usuario(1L,"Mauricio Aniche","mauricio.aniche@caelum.com.br"); // Leilao leilaoEsperado = new Leilao(1L,"Geladeira", 800.0, usuario, false); // assertEquals(leilaoEsperado, leilao); // // } @Test public void deveAdicionarUmUsuarioXml() { Usuario joao = new Usuario("Joao da Silva", "joao@dasilva.com"); XmlPath retorno = given() .header("Accept", "application/xml") .contentType("application/xml") .body(joao) .expect() .statusCode(200) .when() .post("/usuarios") .andReturn() .xmlPath(); Usuario resposta = retorno.getObject("usuario", Usuario.class); assertEquals("Joao da Silva", resposta.getNome()); assertEquals("joao@dasilva.com", resposta.getEmail()); } // @Test // public void deveRetornarListaDeUsuariosJson() { // JsonPath path = given() // .header("Accept", "application/json") // .get("/usuarios") // .andReturn().jsonPath(); // // List<Usuario> usuarios = path.getList("list.usuario", Usuario.class); // // Usuario esperado1 = new Usuario(1L, "Mauricio Aniche", "mauricio.aniche@caelum.com.br"); // Usuario esperado2 = new Usuario(2L, "Guilherme Silveira", "guilherme.silveira@caelum.com.br"); // // assertEquals(esperado1, usuarios.get(0)); // assertEquals(esperado2, usuarios.get(1)); // // } }
[ "alx.lino@gmail.com" ]
alx.lino@gmail.com
710fb7c630f7016509e5bd4116d257216ce54c8a
bfe39e1347fe2dec2c238d0ee13ed5f68f769f44
/weblogic-workshop-book/BookProject-08/beanSources08/inventory/source/com/onlinestore/inventory/InventoryRemote.java
762d357a1e5c0e66782f2788119d4c13175953f9
[]
no_license
stevetraut/samples
e91298b0ed2e18fd3478a9276889e4f48bf7f8ee
fc8459d3f68843f9f84dd110f4383cae21268fcc
refs/heads/master
2021-09-08T23:18:44.994682
2021-08-30T15:03:52
2021-08-30T15:03:52
147,430,163
1
0
null
null
null
null
UTF-8
Java
false
false
354
java
package com.onlinestore.inventory; import java.rmi.RemoteException; import javax.ejb.FinderException; import com.onlinestore.item.ItemRemote; import com.onlinestore.item.Item; /* See InventoryBean.java for the logic of this EJB. */ public interface InventoryRemote extends javax.ejb.EJBObject { public Item[] listItems() throws RemoteException; }
[ "steve.traut@gmail.com" ]
steve.traut@gmail.com
443a6efccceb694f9bc5124bf55f26781c24a204
29c27c52beca80ce19051da8ee4c2353cafbe831
/src/main/java/in/ashwanthkumar/restvideos/module2/service/BeanParamResource.java
a7e1fce73d7681c3f04394b8bfe48db57f4562f1
[]
no_license
ashwanthkumar/rest-video
c314b7d11983e2a3bfad83fe31eb4a78ad8fbb54
d6df2d982dba98bb8941eed7c7c598579d6fbb77
refs/heads/master
2021-01-25T06:56:31.191970
2017-06-09T18:06:57
2017-06-09T18:06:57
93,631,078
0
1
null
null
null
null
UTF-8
Java
false
false
893
java
package in.ashwanthkumar.restvideos.module2.service; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/bean") @Produces(MediaType.APPLICATION_JSON) public class BeanParamResource { private static class Bean { @QueryParam("q") @Encoded @DefaultValue("default-value") private String q; @HeaderParam("X-Custom-Header") private String header; public String getQ() { return q; } public Bean setQ(String q) { this.q = q; return this; } public String getHeader() { return header; } public Bean setHeader(String header) { this.header = header; return this; } } @GET public String beanInfo(@BeanParam Bean bean) { return bean.getQ() + " -- " + bean.getHeader(); } }
[ "ashwanthkumar@googlemail.com" ]
ashwanthkumar@googlemail.com
ba721d525326e7d8847cc93e05f04daef512442b
5d69bc0b629608ea3a8d29cad236c54b97cd2b28
/src_jzy3d-api/org/jzy3d/maths/Coord2d.java
9271762d8c4112375cff457d977a37e3173c4833
[]
no_license
djamelz/WallMe
81e9ffe853ca27d76a355ac79de73125e08702e5
ed37666642813d6b1ff56ec724b22df19f67baa3
refs/heads/master
2021-01-01T19:16:04.046445
2013-05-17T11:36:01
2013-05-17T11:36:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,550
java
package org.jzy3d.maths; /** A {@link Coord2d} stores a 2 dimensional coordinate for cartesian (x,y) or * polar (a,r) mode, and provide operators allowing to add, substract, * multiply and divises coordinate values, as well as computing the distance between * two points, and converting polar and cartesian coordinates. * * @author Martin Pernollet */ public class Coord2d { /** The origin is a Coord2d having value 0 for each dimension.*/ public static final Coord2d ORIGIN = new Coord2d(0.0f, 0.0f); /** An invalid Coord2d has value NaN for each dimension.*/ public static final Coord2d INVALID = new Coord2d(Float.NaN, Float.NaN); /** Creates a 2d coordinate with the value 0 for each dimension.*/ public Coord2d(){ x = 0.0f; y = 0.0f; } /** Creates a 2d coordinate. * When using polar mode, x represents angle, and y represents distance.*/ public Coord2d(float xi, float yi){ x = xi; y = yi; } /** Creates a 2d coordinate. * When using polar mode, x represents angle, and y represents distance.*/ public Coord2d(double xi, double yi){ x = (float)xi; y = (float)yi; } /** Return a duplicate of this 3d coordinate.*/ public Coord2d clone(){ return new Coord2d(x,y); } /**************************************************************/ /** Add a Coord2d to the current one and return the result * in a new Coord2d. * @param c2 * @return the result Coord2d */ public Coord2d add(Coord2d c2){ return new Coord2d(x+c2.x, y+c2.y); } public void addSelf(Coord2d c2){ x+=c2.x; y+=c2.y; } public void addSelf(float x, float y){ this.x+=x; this.y+=y; } /** Add a value to all components of the current Coord and return the result * in a new Coord2d. * @param value * @return the result Coord2d */ public Coord2d add(float value){ return new Coord2d(x+value, y+value); } public Coord2d add(float x, float y){ return new Coord2d(this.x+x, this.y+y); } /** Substract a Coord2d to the current one and return the result * in a new Coord2d. * @param c2 * @return the result Coord2d */ public Coord2d sub(Coord2d c2){ return new Coord2d(x-c2.x, y-c2.y); } /** Substract a value to all components of the current Coord and return the result * in a new Coord2d. * @param value * @return the result Coord2d */ public Coord2d sub(float value){ return new Coord2d(x-value, y-value); } public Coord2d sub(float x, float y){ return new Coord2d(this.x-x, this.y-y); } /** Multiply a Coord2d to the current one and return the result * in a new Coord2d. * @param c2 * @return the result Coord2d */ public Coord2d mul(Coord2d c2){ return new Coord2d(x*c2.x, y*c2.y); } public Coord2d mul(float x, float y){ return new Coord2d(this.x*x, this.y*y); } /** Multiply all components of the current Coord and return the result * in a new Coord3d. * @param value * @return the result Coord3d */ public Coord2d mul(float value){ return new Coord2d(x*value, y*value); } /** Divise a Coord2d to the current one and return the result * in a new Coord2d. * @param c2 * @return the result Coord2d */ public Coord2d div(Coord2d c2){ return new Coord2d(x/c2.x, y/c2.y); } /** Divise all components of the current Coord by the same value and return the result * in a new Coord3d. * @param value * @return the result Coord3d */ public Coord2d div(float value){ return new Coord2d(x/value, y/value); } public Coord2d div(float x, float y){ return new Coord2d(this.x/x, this.y/y); } public void divSelf(float value){ x/=value; y/=value; } /** Converts the current Coord3d into cartesian coordinates * and return the result in a new Coord3d. * @return the result Coord3d */ public Coord2d cartesian(){ return new Coord2d( Math.cos(x) * y, Math.sin(x) * y); } /** Converts the current {@link Coord2d} into polar coordinates * and return the result in a new {@link Coord2d}. */ public Coord2d polar(){ return new Coord2d( Math.atan(y/x), Math.sqrt(x*x + y*y)); } /** * Return a real polar value, with an angle in the range [0;2*PI] * http://fr.wikipedia.org/wiki/Coordonn%C3%A9es_polaires */ public Coord2d fullPolar(){ double radius = Math.sqrt(x*x + y*y); if(x<0){ return new Coord2d(Math.atan(y/x)+Math.PI, radius); } else if(x>0){ if(y>=0) return new Coord2d(Math.atan(y/x), radius); else return new Coord2d(Math.atan(y/x)+2*Math.PI, radius); } else{ // x==0 if(y>0) return new Coord2d(Math.PI/2,radius); else if(y<0) return new Coord2d(3*Math.PI/2,radius); else // y==0 return new Coord2d(0,0); } } /** Compute the distance between two coordinates.*/ public double distance(Coord2d c){ return Math.sqrt( Math.pow(x-c.x,2) + Math.pow(y-c.y,2) ); } /**************************************************************/ /** Return a string representation of this coordinate.*/ public String toString(){ return ("x=" + x + " y=" + y); } /** Return an array representation of this coordinate.*/ public float[] toArray(){ float[] array = new float[2]; array[0] = x; array[1] = y; return array; } /**************************************************************/ public float x; public float y; }
[ "tvial@octo.com" ]
tvial@octo.com
7beaaed5e92fe282302c9876910bb7a1b61dc340
473b76b1043df2f09214f8c335d4359d3a8151e0
/benchmark/bigclonebenchdata_completed/21224972.java
322d88b8ebe49b21623d1ecd0a6fa666d7f2007d
[]
no_license
whatafree/JCoffee
08dc47f79f8369af32e755de01c52d9a8479d44c
fa7194635a5bd48259d325e5b0a190780a53c55f
refs/heads/master
2022-11-16T01:58:04.254688
2020-07-13T20:11:17
2020-07-13T20:11:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,265
java
import java.io.UncheckedIOException; import java.io.UncheckedIOException; class c21224972 { public MyHelperClass conexionBD; public MyHelperClass populatePreparedStatement(jugador o0){ return null; } public boolean update(int idJugador, jugador jugadorModificado) { int intResult = 0; String sql = "UPDATE jugador " + "SET apellidoPaterno = ?, apellidoMaterno = ?, nombres = ?, fechaNacimiento = ?, " + " pais = ?, rating = ?, sexo = ? " + " WHERE idJugador = " + idJugador; try { MyHelperClass connection = new MyHelperClass(); connection = conexionBD.getConnection(); // MyHelperClass connection = new MyHelperClass(); connection.setAutoCommit(false); MyHelperClass ps = new MyHelperClass(); ps = connection.prepareStatement(sql); populatePreparedStatement(jugadorModificado); // MyHelperClass ps = new MyHelperClass(); intResult =(int)(Object) ps.executeUpdate(); // MyHelperClass connection = new MyHelperClass(); connection.commit(); } catch (UncheckedIOException ex) { ex.printStackTrace(); try { MyHelperClass connection = new MyHelperClass(); connection.rollback(); } catch (UncheckedIOException exe) { exe.printStackTrace(); } } finally { MyHelperClass ps = new MyHelperClass(); conexionBD.close(ps); MyHelperClass connection = new MyHelperClass(); conexionBD.close(connection); } return (intResult > 0); } } // Code below this line has been added to remove errors class MyHelperClass { public MyHelperClass commit(){ return null; } public MyHelperClass rollback(){ return null; } public MyHelperClass executeUpdate(){ return null; } public MyHelperClass close(MyHelperClass o0){ return null; } public MyHelperClass getConnection(){ return null; } public MyHelperClass prepareStatement(String o0){ return null; } public MyHelperClass setAutoCommit(boolean o0){ return null; }} class jugador { } class SQLException extends Exception{ public SQLException(String errorMessage) { super(errorMessage); } }
[ "piyush16066@iiitd.ac.in" ]
piyush16066@iiitd.ac.in
5b15ee9fa08c001c6eccff9c97e7fab079d4c7a1
522c4abef6c0410d52dd5b8433bf4487d46c1c25
/efamily-task/src/main/java/com/winterframework/efamily/exception/ServerException.java
3b192d7a66ec7518543c7ee57d5d924c55384d81
[]
no_license
xjiafei/efamily
05b1c71e1f7f485132e5d6243e7af7208b567517
0401d6ec572c7959721c294408f6d525e3d12866
refs/heads/master
2020-03-10T11:42:00.359799
2018-04-13T08:13:58
2018-04-13T08:13:58
129,361,914
0
3
null
null
null
null
UTF-8
Java
false
false
655
java
package com.winterframework.efamily.exception; @SuppressWarnings("serial") public class ServerException extends Exception { private int code=9; public ServerException() { super(); } public ServerException(String message) { super(message); } public ServerException(Throwable cause) { super(cause); } public ServerException(int code, String msg, Throwable exception) { super(msg, exception); this.code = code; } public ServerException(int code) { super(); this.code = code; } public ServerException(int code,Throwable exception) { super(exception); this.code = code; } public int getCode() { return this.code; } }
[ "xjiafei126@126.com" ]
xjiafei126@126.com
ea0a2caf76952b4e2846986d72fe8cffb371cba1
b93dac0017f221f9bde466f71740f42c6fdf0567
/src/main/java/storyworlds/service/LRUCache.java
8e97fcbf80fe991139b0b392a32b283e5062395e
[]
no_license
natevaughan/storyworlds
f898c40413b240dee42a7f34f519b6e1c77428a3
8655d8e02f02efc59775fa138888ad44483613ed
refs/heads/master
2020-04-17T04:39:03.795119
2017-02-17T14:01:07
2017-02-17T14:01:07
66,155,393
0
0
null
null
null
null
UTF-8
Java
false
false
3,279
java
package storyworlds.service; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by nvaughan on 10/30/2016. */ public class LRUCache<K, V> { private Logger logr = LoggerFactory.getLogger(getClass()); private Map<K, V> hashMap; private Queue<K> lruEnforcer; private final Integer count; private final ReentrantLock lock; public LRUCache(Integer count) { this.count = count; lruEnforcer = new LinkedList<K>(); hashMap = new HashMap<K, V>(count + 2, 1.0F); // fairness seems to have a significant performance cost lock = new ReentrantLock(false); } public boolean containsKey(Object key) { lock.lock(); try { return hashMap.containsKey(key); } finally { lock.unlock(); } } public V get(K key) { lock.lock(); try { if (hashMap.containsKey(key)) { V value = hashMap.get(key); lruEnforcer.remove(key); lruEnforcer.add(key); return value; } return null; } finally { lock.unlock(); } } public V putIfAbsent(K key, V value) { if (key == null || value == null) { return null; } lock.lock(); try { if (hashMap.containsKey(key)) { lruEnforcer.remove(key); lruEnforcer.add(key); } else { hashMap.put(key, value); lruEnforcer.add(key); logr.info("Added " + value.getClass().getSimpleName() + " " + key + " to lruCache; capacity is " + hashMap.size() + " / " + count); } while (hashMap.size() > count) { hashMap.remove(lruEnforcer.poll()); logr.info("Evicted " + value.getClass().getSimpleName() + " from lruCache; capacity is " + hashMap.size() + " / " + count); } return hashMap.get(key); } finally { lock.unlock(); } } public V remove(Object key) { lock.lock(); try { if (hashMap.containsKey(key)) { lruEnforcer.remove(key); return hashMap.remove(key); } return null; } finally { lock.unlock(); } } public V put(K key, V value) { if (key == null || value == null) { return null; } lock.lock(); try { if (hashMap.containsKey(key)) { lruEnforcer.remove(key); hashMap.put(key, value); lruEnforcer.add(key); logr.info("Overwrote " + value.getClass().getSimpleName() + " " + key + " to lruCache"); } return value; } finally { lock.unlock(); } } public ArrayList<V> snapshot() { lock.lock(); try { return new ArrayList<V>(hashMap.values()); } finally { lock.unlock(); } } }
[ "nvaughanguitar@yahoo.com" ]
nvaughanguitar@yahoo.com
657ae948f9f757e519b72d1057e6ad1552fe0552
f66261ba0872a23e15b727d60544abe6a573d049
/src/main/java/com/chiknas/application/Loading.java
461c14268d66ac1ef795aecac2fbf19eb9226e51
[]
no_license
chiknas/Nikos-Invaders-The-humble-beginnings
a89b06748ad17ee4ca6943d564c5b6d6dcabcf64
11a07943470150c0d689cbac7942a1c133cb9ff9
refs/heads/master
2020-11-25T14:40:16.289057
2020-10-15T20:44:03
2020-10-15T20:44:03
228,722,330
2
0
null
null
null
null
UTF-8
Java
false
false
307
java
package com.chiknas.application; import javafx.fxml.Initializable; import java.net.URL; import java.util.ResourceBundle; /** * created by NikosK on 12/21/2019 */ public class Loading implements Initializable { @Override public void initialize(URL location, ResourceBundle resources) { } }
[ "nkuknas@gmail.com" ]
nkuknas@gmail.com
d56755b4953034c9c741e36a726f3b0c10831553
bfd5bd9e956ebcd05be3c00384e1032261898992
/week08/src/com/xiaoxiao/no145二叉树的后序遍历/Solution.java
cab3dab660fb0e2e8f29fab4839cdeefe60426e5
[]
no_license
xy19980319/algorithm
5c742b98b843052488d92b0c30d4aae6c25d02be
f67f53015ad399c68fa9e6e64d230637d6794f90
refs/heads/master
2021-05-19T00:14:05.417988
2020-07-27T13:46:54
2020-07-27T13:46:54
251,490,173
0
0
null
null
null
null
UTF-8
Java
false
false
1,138
java
package com.xiaoxiao.no145二叉树的后序遍历; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; /** * @author Xiaoyu * @date 2020/4/27 - 23:14 */ public class Solution { //迭代算法 public List<Integer> postorderTraversal(TreeNode root) { //考虑到加入一个数,然后把他的右边左边按顺序加入 if (root == null) return new ArrayList<>(); List<Integer> res = new ArrayList<>(); return res; } public class ListNode { int val; ListNode next; public ListNode(int x) { this.val = x; } } ; /* //递归算法 public List<Integer> postorderTraversal(TreeNode root) { if (root == null) return new ArrayList<>(); List<Integer> res = new ArrayList<> (); dfs(root,res); return res; } private void dfs(TreeNode root, List<Integer> res) { if(root == null) return; if(root.left != null) dfs(root.left,res); if(root.right != null) dfs(root.right,res); res.add(root.val); }*/ }
[ "272972805@qq.com" ]
272972805@qq.com
f1c5ecb55aebf9b8303d50c3e97392fe7ef798dc
4c124a7dad203f8c3fa4639dd44145a0d194fe8c
/src/com/kjjcsoft/controllers/EditCustomerController.java
be59467daab36f87ff8a7dd83f391a5e2966daf6
[]
no_license
bibek-shrestha/co-operatives-software-test
1e7e8e019712f311085e3d1dd482b18be67ac516
a045b8a026672f8213e59f5c707de1bc5c33832b
refs/heads/master
2021-09-02T09:50:17.231695
2018-01-01T16:50:05
2018-01-01T16:50:05
115,930,192
0
0
null
null
null
null
UTF-8
Java
false
false
3,146
java
package com.kjjcsoft.controllers; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.kjjcsoft.bean.CustomerBean; import com.kjjcsoft.bean.SearchBean; import com.kjjcsoft.model.Customer; /** * Servlet implementation class EditCustomerController */ @WebServlet(description = "to edit the details of customers", urlPatterns = {"/edit"}) public class EditCustomerController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public EditCustomerController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd = getServletContext().getRequestDispatcher("/view/editInfo.jsp"); if (request.getParameter("edit")!=null && request.getParameter("edit").equals("true")) { Customer changeInfo = new Customer(); CustomerBean fromDbInfo = new CustomerBean(); fromDbInfo = (CustomerBean)changeInfo.getDetails(Integer.parseInt(request.getParameter("customerid"))); request.getSession().setAttribute("storedInfo", fromDbInfo); response.sendRedirect("/KJJCSoft/com/kjjcsoft/controllers/change"); return; } rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Customer queryCustomer = new Customer(); List<CustomerBean> list = null; if (request.getParameter("search") != null) { SearchBean customerQuery = new SearchBean(); customerQuery.setCustomerListSearch(request.getParameter("query_string")); if (customerQuery.validateListSearch() == 0) { list = queryCustomer.searchForEdit(customerQuery.getCustomerListSearch()); } else if (customerQuery.validateListSearch() == 1) { list = queryCustomer.searchForEdit(Integer.parseInt(customerQuery.getCustomerListSearch())); } else if (customerQuery.validateListSearch() == 2) { request.setAttribute("errormsgcs", "No keywords entered"); } request.setAttribute("editList", list); } if (request.getParameter("disable")!=null) { queryCustomer.changeToInactive(Integer.parseInt(request.getParameter("customerid"))); list=queryCustomer.searchForEdit(Integer.parseInt(request.getParameter("customerid"))); request.setAttribute("editList", list); } if (request.getParameter("enable")!=null) { queryCustomer.changeToActive(Integer.parseInt(request.getParameter("customerid"))); list=queryCustomer.searchForEdit(Integer.parseInt(request.getParameter("customerid"))); request.setAttribute("editList", list); } doGet(request, response); } }
[ "rawseek@gmail.com" ]
rawseek@gmail.com
aa41efad98a9d3f0e3a293b6afcf947f8ac3aa24
97288799ee35d78fcdd0619bb654a32d8fbd1e78
/src/org/unclesniper/winter/mvc/util/EmptyIterator.java
4290e2b8e111b175c7d0717986f15e9df38534fb
[]
no_license
UncleSniper/winter-mvc
c2bb505ed48397418392769030d90c0fb9c94a55
0159be104ac2899c533da393e69920cf79265dcf
refs/heads/master
2020-03-09T18:23:25.836348
2019-03-11T12:09:24
2019-03-11T12:09:24
128,930,895
0
0
null
null
null
null
UTF-8
Java
false
false
930
java
package org.unclesniper.winter.mvc.util; import java.util.ListIterator; import java.util.function.Consumer; import java.util.NoSuchElementException; public class EmptyIterator<E> implements ListIterator<E> { public static final EmptyIterator instance = new EmptyIterator(); public EmptyIterator() {} public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException(); } public void remove() { throw new IllegalStateException(); } public void forEachRemaining(Consumer<? super E> action) {} public void set(E e) { throw new IllegalStateException(); } public void add(E e) { throw new UnsupportedOperationException(EmptyIterator.class.getName() + ".add(E)"); } public int nextIndex() { return 0; } public E previous() { throw new NoSuchElementException(); } public int previousIndex() { return -1; } public boolean hasPrevious() { return false; } }
[ "simon@bausch-alfdorf.de" ]
simon@bausch-alfdorf.de
044dc760afaa683b6ace0b200bec09dbbaacde7d
1dcf8009f03a6ca966aea27aad8c3695f16f5502
/src/main/java/fi/alekster/classical/security/JwtAuthenticationEntryPoint.java
2ffc15451cbf4d8bc95fb4e3c3ce042f4f5e55f0
[]
no_license
AleksTeresh/classical
8d0592b982b60ebc875fc619879682aa335c04dc
b5b8f5cb08cc2db33049e94d20b0be75ebc0fcf6
refs/heads/master
2018-11-09T11:56:52.900174
2018-08-26T09:07:26
2018-08-26T09:07:26
109,048,007
0
0
null
null
null
null
UTF-8
Java
false
false
1,113
java
package fi.alekster.classical.security; /** * Created by aleksandr on 16.11.2017. */ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Serializable; @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { // This is invoked when user tries to access a secured REST resource without supplying any credentials // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } }
[ "terap98@icloud.com" ]
terap98@icloud.com
6f3df30040a6c03665260a5371b60a346f8a1a94
dbe3e231628e705a04f86deac18c248a3a352fd2
/SHM_final/src/userInterface/ConstructionCompanyWorkArea/BiddingJPanel.java
0d3a8073f6bc253da78900618422c28d42a287d0
[]
no_license
xianlin666/Structural-Health-Monitoring-System
b4f5535e02ee2270e1e3534a18113675a70a7d34
6dd54fce742dabf0ff25737d5ebb7f0cdf8a313e
refs/heads/master
2023-04-26T08:38:27.578866
2016-07-02T17:01:34
2016-07-02T17:01:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,963
java
/* * 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 userInterface.ConstructionCompanyWorkArea; import Business.MunicipalCorporation.MunicipalCorporation; import Business.Organization.ConstructionCompanyOrganization; import Business.UserAccount.UserAccount; import Business.WorkQueue.BidWorkRequest; import Business.WorkQueue.WorkRequest; import java.awt.CardLayout; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.table.DefaultTableModel; /** * * @author User */ public class BiddingJPanel extends javax.swing.JPanel { /** * Creates new form BiddingJPanel */ private JPanel userProcessContainer; private UserAccount account; private ConstructionCompanyOrganization organization; private MunicipalCorporation municipalCorporation; public BiddingJPanel(JPanel userProcessContainer,UserAccount account, ConstructionCompanyOrganization organization,MunicipalCorporation municipalCorporation) { initComponents(); this.userProcessContainer=userProcessContainer; this.account=account; this.organization=organization; this.municipalCorporation=municipalCorporation; populateTable(); } public void populateTable(){ DefaultTableModel model = (DefaultTableModel)bidTable.getModel(); model.setRowCount(0); for(WorkRequest request : organization.getWorkQueue().getWorkRequestList()){ Object[] row = new Object[4]; row[0] = request; row[1]=request.getBuilding(); row[2] = request.getSender(); row[3] = request.getStatus(); model.addRow(row); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); bidTable = new javax.swing.JTable(); btnBid = new javax.swing.JButton(); btnBack = new javax.swing.JButton(); setBackground(new java.awt.Color(153, 153, 255)); bidTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Bid ID", "Building", "Organization", "Bid Status" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(bidTable); btnBid.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnBid.setText("Place Bid"); btnBid.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBidActionPerformed(evt); } }); btnBack.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnBack.setText("<< Back"); btnBack.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBackActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(77, 77, 77) .addComponent(btnBack) .addGap(93, 93, 93) .addComponent(btnBid))) .addContainerGap(331, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(57, 57, 57) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBid) .addComponent(btnBack)) .addContainerGap(310, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void btnBidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBidActionPerformed // TODO add your handling code here: int row=bidTable.getSelectedRow(); if(row<0){ JOptionPane.showMessageDialog(this, "Select a row"); return; } WorkRequest request = (WorkRequest)bidTable.getValueAt(row, 0); //request.setReceiver(account); BidWorkRequest bwr=(BidWorkRequest)bidTable.getValueAt(row, 0); if("Closed".equals(bwr.getStatus())){ JOptionPane.showMessageDialog(this, "Bid Closed. You cannot bid anymore"); } else{ PlaceBidsJPanel pb=new PlaceBidsJPanel(userProcessContainer,bwr,request,account); userProcessContainer.add("PlaceBidsJPanel", pb); CardLayout layout=(CardLayout) userProcessContainer.getLayout(); layout.next(userProcessContainer); } }//GEN-LAST:event_btnBidActionPerformed private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed // TODO add your handling code here: userProcessContainer.remove(this); CardLayout layout=(CardLayout) userProcessContainer.getLayout(); layout.previous(userProcessContainer); }//GEN-LAST:event_btnBackActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTable bidTable; private javax.swing.JButton btnBack; private javax.swing.JButton btnBid; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
[ "kennethpereira07@gmail.com" ]
kennethpereira07@gmail.com
d413510fb064fc58403b595f7aa46c4420232be1
18e70aac3ba9151dbe331e863ea45310fd28748a
/Ex82_Socket2/app/src/main/java/com/ict/ex82_socket2/MainActivity1.java
5c07cafa0dd01eb32e1dd2d9135bc634e60965a2
[]
no_license
woocharle/ict.edu.android
40ce4bc81dc2cf4cf0356cbb59e7bae6ebad0e9f
e0bab546feb8897c47c75d0829df4427797952de
refs/heads/master
2022-12-30T13:00:54.615897
2020-10-16T08:43:59
2020-10-16T08:43:59
285,203,261
0
0
null
null
null
null
UTF-8
Java
false
false
2,328
java
package com.ict.ex82_socket2; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class MainActivity1 extends AppCompatActivity { EditText editText1; Button button1; TextView result1; Handler handler = new Handler(); String msg = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); editText1 = findViewById(R.id.editText1); button1 = findViewById(R.id.button1_1); result1 = findViewById(R.id.result1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { String str = editText1.getText().toString(); msg = sendServer(str); handler.post(new Runnable() { @Override public void run() { result1.append(msg+"\n"); editText1.setText(""); } }); } }).start(); } }); } public String sendServer(String str){ String res = null; BufferedWriter writer = null; BufferedReader reader = null; try { Socket s = new Socket("203.236.220.86", 9999); writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); reader = new BufferedReader(new InputStreamReader(s.getInputStream())); writer.write(str + System.getProperty("line.separator")); writer.flush(); res = reader.readLine(); s.close(); }catch (Exception e){ Log.d("my",e+""); } return res; } }
[ "silvershots@naver.com" ]
silvershots@naver.com
4b6051fb17cd9d4a8476f01aea54de49948add5f
bc29b42f5027d077084bbb9907316d1a5dfcc0af
/ch19/Max/src/max/Max.java
de198dfcf85b14b137fc921245f363b6324f8ba3
[]
no_license
ilikeshell/liang
c2efaaebe7ddaa214d486efabefc557cea31de85
e6ebef3c42b8bf63c6714f2c15d95af2061c44e9
refs/heads/master
2020-03-28T22:59:57.568087
2018-09-30T03:08:39
2018-09-30T03:08:39
149,270,160
0
0
null
null
null
null
UTF-8
Java
false
false
623
java
/* * 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 max; /** * * @author kaiyan */ public class Max { /** * @param args the command line arguments */ public static void main(String[] args) { String string = "abc"; Integer a = 10; max(a, string); } public static Comparable max(Comparable o1, Comparable o2){ if(o1.compareTo(o2) > 0) return o1; else return o2; } }
[ "1007965673@qq.com" ]
1007965673@qq.com
ae1e4041b2e4f8fc05ea7bf6ba051e48cd92a9f3
acb7217f9eb7c4be1586cd3bff4c4f177b79321a
/gotopXmzh/src/com/eos/web/taglib/bean/RemoveTag.java
b4ba1c584a887ed2ee57dd980e57519217e4c3c6
[]
no_license
2416879170/XMpro
4f4650eff3428c12edfd9ade5eb8b7af0b375904
676dbcbf05ba25e7b49e623c0ebd3998b3f11535
refs/heads/master
2020-06-25T22:03:53.991120
2017-07-12T10:11:40
2017-07-12T10:11:40
94,502,163
0
0
null
null
null
null
UTF-8
Java
false
false
2,076
java
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) fieldsfirst ansi // Source File Name: RemoveTag.java package com.eos.web.taglib.bean; import com.eos.data.xpath.XPathLocator; import com.eos.web.taglib.basic.BaseIteratorTagSupport; import com.eos.web.taglib.util.XpathUtil; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; public class RemoveTag extends BaseIteratorTagSupport { private String ignore; private boolean _ignore; public RemoveTag() { ignore = "true"; _ignore = true; } public String isIgnore() { return ignore; } public void setIgnore(String ignore) { this.ignore = ignore; } public void initAttributes() throws JspException { super.initAttributes(); _ignore = XpathUtil.getBooleanByXpathSupport(getRootObj(), ignore, true, "ignore"); } public int doStartTag() throws JspException { initAttributes(); if(getScope().startsWith("f")) throw new JspException("b:remove tag ,unsupport remove flow context"); Object value = getPropertyValue(); if(value == null) { if(!_ignore) throw new JspException("b:remove tag, can not found oject !"); } else { try { if(getIterateId() != null) XPathLocator.getInstance().deleteValue(pageContext.getAttribute(getIterateId()), getProperty()); else XPathLocator.getInstance().deleteValue(getRootObj(), getProperty()); } catch(Exception e) { throw new JspException("b:remove tag,remove object exception !"); } } return 0; } public void release() { super.release(); ignore = "true"; } }
[ "2416879170@qq.com" ]
2416879170@qq.com
a36a939a058565798d204dac9f700edd5b1e7bfe
9deaca11408ea18619290f9269f05ef30dadbd0e
/src/main/java/com/mua/antlr/JsonListener.java
ad11cd8f9190fe69a844c042133a6e96b5ce30e7
[ "MIT" ]
permissive
maifeeulasad/JSON2MUAON
69de42efdf75ecf2ecb45ef3e727727f20b403b0
63326d3d2cb328726d14d56bb32aa183c4f6550f
refs/heads/main
2023-02-17T03:30:49.137294
2021-01-09T11:54:31
2021-01-09T11:54:31
327,883,572
0
0
null
null
null
null
UTF-8
Java
false
false
2,694
java
// Generated from /home/maifee/Desktop/JSON-to-MUAON-Java-Antlr/src/main/java/com/mua/antlr/Json.g4 by ANTLR 4.8 package com.mua.antlr; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link JsonParser}. */ public interface JsonListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link JsonParser#json}. * @param ctx the parse tree */ void enterJson(JsonParser.JsonContext ctx); /** * Exit a parse tree produced by {@link JsonParser#json}. * @param ctx the parse tree */ void exitJson(JsonParser.JsonContext ctx); /** * Enter a parse tree produced by {@link JsonParser#obj}. * @param ctx the parse tree */ void enterObj(JsonParser.ObjContext ctx); /** * Exit a parse tree produced by {@link JsonParser#obj}. * @param ctx the parse tree */ void exitObj(JsonParser.ObjContext ctx); /** * Enter a parse tree produced by {@link JsonParser#pairSet}. * @param ctx the parse tree */ void enterPairSet(JsonParser.PairSetContext ctx); /** * Exit a parse tree produced by {@link JsonParser#pairSet}. * @param ctx the parse tree */ void exitPairSet(JsonParser.PairSetContext ctx); /** * Enter a parse tree produced by {@link JsonParser#pair}. * @param ctx the parse tree */ void enterPair(JsonParser.PairContext ctx); /** * Exit a parse tree produced by {@link JsonParser#pair}. * @param ctx the parse tree */ void exitPair(JsonParser.PairContext ctx); /** * Enter a parse tree produced by {@link JsonParser#arr}. * @param ctx the parse tree */ void enterArr(JsonParser.ArrContext ctx); /** * Exit a parse tree produced by {@link JsonParser#arr}. * @param ctx the parse tree */ void exitArr(JsonParser.ArrContext ctx); /** * Enter a parse tree produced by {@link JsonParser#valueSet}. * @param ctx the parse tree */ void enterValueSet(JsonParser.ValueSetContext ctx); /** * Exit a parse tree produced by {@link JsonParser#valueSet}. * @param ctx the parse tree */ void exitValueSet(JsonParser.ValueSetContext ctx); /** * Enter a parse tree produced by {@link JsonParser#value}. * @param ctx the parse tree */ void enterValue(JsonParser.ValueContext ctx); /** * Exit a parse tree produced by {@link JsonParser#value}. * @param ctx the parse tree */ void exitValue(JsonParser.ValueContext ctx); /** * Enter a parse tree produced by {@link JsonParser#bool}. * @param ctx the parse tree */ void enterBool(JsonParser.BoolContext ctx); /** * Exit a parse tree produced by {@link JsonParser#bool}. * @param ctx the parse tree */ void exitBool(JsonParser.BoolContext ctx); }
[ "maifeeulasad@gmail.com" ]
maifeeulasad@gmail.com
4ada275e8dbed7c7c2589ebc70cd44dde7cc2081
331b0f329919166aa1be62a11850ba1090c5537e
/src/main/java/com/bindingdai/model/SymptomEntity.java
836379f03e5336aae986adb86c43f59f9a3d3e81
[]
no_license
landesire/SpringDiagnosisEMR
d50107c16cf46050f4e7bfb0df378d9f80b7ae19
33a57164c72442122441de57c5ec0ad11d6952e3
refs/heads/master
2020-04-06T07:08:45.268276
2016-08-26T14:17:07
2016-08-26T14:17:07
66,650,345
1
0
null
null
null
null
UTF-8
Java
false
false
1,325
java
package com.bindingdai.model; import javax.persistence.*; /** * Created by daibinding on 16/7/4. */ @Entity @Table(name = "Symptom", schema = "ElectronicHealthRecord", catalog = "") public class SymptomEntity { private int idSymptom; private String symptomName; @Id @Column(name = "idSymptom", nullable = false) public int getIdSymptom() { return idSymptom; } public void setIdSymptom(int idSymptom) { this.idSymptom = idSymptom; } @Basic @Column(name = "SymptomName", nullable = true, length = 45) public String getSymptomName() { return symptomName; } public void setSymptomName(String symptomName) { this.symptomName = symptomName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SymptomEntity that = (SymptomEntity) o; if (idSymptom != that.idSymptom) return false; if (symptomName != null ? !symptomName.equals(that.symptomName) : that.symptomName != null) return false; return true; } @Override public int hashCode() { int result = idSymptom; result = 31 * result + (symptomName != null ? symptomName.hashCode() : 0); return result; } }
[ "bindingdai@gmail.com" ]
bindingdai@gmail.com
eb9177dfbca0053da572ec28c2cf268c9e9afbd2
f97fd842e0024bca3a5cde2699c46e1a5eb40fbb
/src/com/zoran/leetcode/simple3/Test69.java
141d70dbb0d0babb8b4aaec31fbcaa1009ee4d93
[]
no_license
ZoranYaoYao/LeetCode
735af9f85e51867d583a03eff604d1fb220c955c
1d5d36ee9fbe1bd9faab0e07a3c679a03a1bfd05
refs/heads/master
2020-03-16T01:56:46.279937
2019-04-03T01:37:27
2019-04-03T01:37:27
132,452,919
2
0
null
null
null
null
GB18030
Java
false
false
514
java
package com.zoran.leetcode.simple3; /** * 3的幂 * https://leetcode-cn.com/submissions/detail/3514485/ */ public class Test69 { public static void main(String[] args) { System.out.println(isPowerOfThree(-3)); } public static boolean isPowerOfThree(int n) { if(n <= 0) return false; while (n != 1) { //Core: n != 1, 表示 因子里面还有其他的因子,eg: 45 = 3*3*5*1 if(n % 3 != 0) return false; n = n / 3; } return true; } }
[ "zhengqingsong@didapinche.com" ]
zhengqingsong@didapinche.com
111a439f1f407980838865771dee4f3800050374
8ec379a02be629165c97f12d75551e09279e5f97
/shop-manage/src/main/java/quick/pager/shop/response/EnumResponse.java
170b34d9f33366da27553175ee37b702bd8d81ae
[ "MIT" ]
permissive
donniezhanggit/spring-cloud-shop
73c9e99c714310cb4ecbacb2f764a452b24dfefc
aeeaba1be804d7197692fa6bef8bdcaedb2302ac
refs/heads/master
2020-06-19T14:15:02.682581
2019-10-14T06:25:38
2019-10-14T06:25:38
196,739,760
0
0
MIT
2019-10-14T06:25:40
2019-07-13T15:56:03
Java
UTF-8
Java
false
false
298
java
package quick.pager.shop.response; import java.io.Serializable; import lombok.Data; @Data public class EnumResponse implements Serializable { private static final long serialVersionUID = -1280398705355998555L; private Integer type; private String key; private String value; }
[ "siguiyang1992@outlook.com" ]
siguiyang1992@outlook.com
8d7b9fdaed5232d540d531a05b6c154047157a09
28f8f11e22a8fafbfe3b634f0974b4ad3b0c3cb6
/src/main/java/com/imooc/step4/ioc/demo6/UserDao.java
e608d4d0c8d3909df809736a82208737520baa59
[]
no_license
yxx010/moocstudy
60689d4c300425902446a94b77b2ee98b559fd0a
3be32fcc38d0b04cdafdeb04c70704f4b3083c74
refs/heads/master
2022-12-21T00:24:12.392971
2021-08-09T07:25:34
2021-08-09T07:25:34
172,302,783
0
0
null
2022-12-16T05:03:49
2019-02-24T06:07:11
Java
UTF-8
Java
false
false
274
java
package com.imooc.step4.ioc.demo6; import org.springframework.stereotype.Repository; @Repository("userDao1") //service里按照类型注入的,跟这个名字没关系 public class UserDao { public void save(){ System.out.println("Dao保存用户"); } }
[ "yxx_beijing@163.com" ]
yxx_beijing@163.com
76550fbc0f41e04028a6a9a72d5bb40e6f321713
4d823cd9665f799691adaaa37dd6704df69bb089
/app/src/main/java/com/example/myhealthbuddy/ForgetPassword.java
b133de75483b7a2320f610bd6ffae25e81e45240
[]
no_license
noufalmedlej/MyHealthBuddy
1126611c70d11360131065b154390fcb9d695e7d
46869f9b8cdae86645caef2c28cf9847b86409d5
refs/heads/master
2021-01-06T21:48:49.380861
2020-05-06T07:56:04
2020-05-06T07:56:04
241,490,486
1
0
null
null
null
null
UTF-8
Java
false
false
352
java
package com.example.myhealthbuddy; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class ForgetPassword extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forget_password); } }
[ "haifa.almans@gmail.com" ]
haifa.almans@gmail.com
87468173b71d2ab76367465e2e0ee805aa5ff10f
9ca7da1dac630b1c04698e186b764471204728a1
/src/main/java/com/lying/lyingdisk/aop/auth/AuthCheckTokenAop.java
cc24652e777f41f6450f84b64c1c85dcb0bc47bb
[]
no_license
YBeing/lying-disk
7726570f9ef1e0306a994618526c39286afbea6f
0f60cb9c87855f1b431ae780835a4fa3fe46de18
refs/heads/master
2023-01-21T21:00:44.680994
2020-11-20T14:05:53
2020-11-20T14:05:53
297,119,136
0
0
null
null
null
null
UTF-8
Java
false
false
3,122
java
package com.lying.lyingdisk.aop.auth; import cn.hutool.core.util.StrUtil; import com.lying.lyingdisk.service.UserService; import com.lying.lyingdisk.util.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Order(0) @Component @Slf4j public class AuthCheckTokenAop { private static final String HEAD_AUTHORIZATION ="Authorization"; @Autowired private UserService userService; /** * 请求切点方法(已提供@RequestMapping,@GetMapping,@PostMapping注解,需要其它请增加) */ @Pointcut(" @annotation(org.springframework.web.bind.annotation.RequestMapping) || " + " @annotation(org.springframework.web.bind.annotation.GetMapping) || " + " @annotation(org.springframework.web.bind.annotation.PostMapping)") public void requestMapping(){ } /** * 范围切点方法 */ @Pointcut("execution(* com.lying.lyingdisk.controller.*.*(..))") public void methodPointCut() { } /** * 除了我们的登录注册方法,其他均需要被我们的aop拦截进行权限校验 */ @Before("requestMapping() && methodPointCut() && !execution(* com.lying.lyingdisk.controller.UserController.*(..))") void doBefore(JoinPoint joinPoint) throws Exception{ log.info("进入AOP方法认证..."); authLogic(joinPoint); } /** * 认证逻辑 * @param joinPoint * @throws Exception */ private void authLogic(JoinPoint joinPoint) throws Exception { log.info("认证开始..."); String classType = joinPoint.getTarget().getClass().getName(); Class<?> clazz = Class.forName(classType); String clazzName = clazz.getName(); String methodName = joinPoint.getSignature().getName(); log.info("ClassName: "+clazzName); log.info("MethodName:"+methodName); //获取当前http请求 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String token = request.getHeader(HEAD_AUTHORIZATION); String username = request.getHeader("username"); //此处的TOKEN验证业务逻辑自行编写 if (StrUtil.isEmpty(token)){ throw new Exception("token为空!"); } boolean checkToken = JwtUtils.checkToken(token,username); log.debug(token); if(checkToken){ log.debug("请求认证通过!"); }else { throw new Exception("token过期了!!"); } } }
[ "610398531@qq.com" ]
610398531@qq.com
cde4f3503ec61eb70e309f775dd6f119043065fa
a9b810921219da029677212975cbb9f79c927522
/Java web/PM2.5/src/Servlet/GetData.java
db4fedc61aa87f024c66f15df10fdd53c02cee99
[]
no_license
solidjerryc/PM2.5_sensor
54ebaf07c1328d5bc8b337e5703c66a03fb78a90
3249fbf9ee5e906098b25329188e9734f550f739
refs/heads/master
2020-03-21T02:05:36.738647
2019-03-20T06:11:56
2019-03-20T06:11:56
137,979,153
0
0
null
null
null
null
UTF-8
Java
false
false
979
java
package Servlet; import com.Database; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "GetData", urlPatterns = {"/test"}) public class GetData extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Database db = new Database(); if( db.dbTestConnect()) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Connect succeeded!"); out.println(db.showDatabases()); } } }
[ "solidjerryc@gmail.com" ]
solidjerryc@gmail.com
f365f1b8585ce6e5fde8eaa29ddf4a19e7f3bc53
96f8d42c474f8dd42ecc6811b6e555363f168d3e
/baike/sources/pl/droidsonroids/gif/f.java
d2762cc14e2b6d5ce25c2ba5d5633cbee0311660
[]
no_license
aheadlcx/analyzeApk
050b261595cecc85790558a02d79739a789ae3a3
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
refs/heads/master
2020-03-10T10:24:49.773318
2018-04-13T09:44:45
2018-04-13T09:44:45
129,332,351
6
2
null
null
null
null
UTF-8
Java
false
false
237
java
package pl.droidsonroids.gif; class f extends a { final /* synthetic */ GifDrawable a; f(GifDrawable gifDrawable) { this.a = gifDrawable; super(); } public void doWork() { this.a.h.c(); } }
[ "aheadlcxzhang@gmail.com" ]
aheadlcxzhang@gmail.com
26a4ff728f06ae94bbbb2b6f2b0cf8830db4e3d5
0bfd16be8e456104d7f55faeaa71c06f68a56af1
/parserBackEnd/src/main/java/com/denis/parserbackend/dao/TypeInstrumentDAO.java
2292e6344d2e5790b0249cfe9204e3249f5b2e7c
[]
no_license
DenisTmenov/parserOnl
20d6d84ab4469c56e9497ffbd2075bd9823b3de0
4c33792940ff0b2c28910c165b1b2ac2541db8d5
refs/heads/master
2021-08-24T01:42:38.482689
2017-12-07T14:04:21
2017-12-07T14:04:21
111,998,428
0
0
null
null
null
null
UTF-8
Java
false
false
471
java
package com.denis.parserbackend.dao; import java.util.List; import com.denis.parserbackend.dto.DtoException; import com.denis.parserbackend.dto.TypeInstrument; public interface TypeInstrumentDAO { List<TypeInstrument> loadAllInfo() throws DtoException; TypeInstrument getById(int id) throws DtoException; TypeInstrument getByName(String name) throws DtoException; boolean add(TypeInstrument entity); boolean update(TypeInstrument entity); }
[ "denis.tmenov@gmail.com" ]
denis.tmenov@gmail.com
bfd76ece1f2f64bc5f58c7c4e448f17eac2ecd8c
6234757cfaa619977f7adde266b06ebffd923ae2
/src/main/java/com/goosen/commons/utils/RequestBindDataUtil.java
ddf3cc0a0a84daedf41c0b3d366b20439fe4fc32
[ "MIT" ]
permissive
goosen123/mp-demo2
b42f1e02f4dfae95b1d602e1f91fc965353683fd
e37a388f05acf72f2a79d9607ad41990b0e00374
refs/heads/master
2020-03-22T19:44:14.833097
2018-07-27T09:21:52
2018-07-27T09:21:52
140,547,440
0
0
null
null
null
null
UTF-8
Java
false
false
2,764
java
package com.goosen.commons.utils; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; import com.goosen.commons.model.commons.http.ReqParams; /** * 设置请求头的信息和参数到请求信息中 * 2018-04-25 14:47:01 * @author Goosen * */ public class RequestBindDataUtil { public static void bindDataToRequest(HttpEntityEnclosingRequestBase httpMethodEntity, ReqParams reqParams) throws UnsupportedEncodingException{ if(null == reqParams) return; boolean sign = false; //设置请求头 Map<String, String> headerMap = reqParams.getHeaderMap(); if(null != headerMap && headerMap.size() > 0){ for(String key : headerMap.keySet()){ String value = headerMap.get(key); httpMethodEntity.addHeader(key, value); // if("Content-Type".equals(key)){ // sign = true; // } } } String postText = reqParams.getPostText(); if(postText != null){ if(!sign){ String type = "application/"; String postType = reqParams.getPostType(); if(null == postType || postType.trim().length() == 0){ postType = "json"; } type = type + postType; // httpMethodEntity.addHeader("Content-Type", type); sign = true; } //设置 httpMethodEntity.setEntity(new StringEntity(postText, "UTF-8")); return; } Map<String, String> paramsMap = reqParams.getParamsMap(); if(null != paramsMap && paramsMap.size() > 0){ List<NameValuePair> params = new ArrayList<NameValuePair>(); for(String key : paramsMap.keySet()){ String value = paramsMap.get(key); params.add(new BasicNameValuePair(key,value)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8"); // entity.setContentType("application/json"); httpMethodEntity.setEntity(entity); if(!sign){ // httpMethodEntity.addHeader("Content-Type", "application/json;charset=UTF-8"); sign = true; } return; } } public static void bindDataToRequest(HttpRequestBase httpMethodEntity, ReqParams reqParams){ if(null == reqParams) return; boolean sign = false; //设置请求头 Map<String, String> headerMap = reqParams.getHeaderMap(); if(null != headerMap && headerMap.size() > 0){ for(String key : headerMap.keySet()){ String value = headerMap.get(key); httpMethodEntity.addHeader(key, value); if("Content-Type".equals(key)){ sign = true; } } } } }
[ "2630344884@qq.com" ]
2630344884@qq.com
2b1d4a18c1bdf2114be7aad67fb80b5bdb80db2b
d1bd1246f161b77efb418a9c24ee544d59fd1d20
/java/Common/src/org/javenstudio/common/indexdb/analysis/Analyzer.java
6ab5d9a7e4325bbc36908cd1e207893f45b3c700
[]
no_license
navychen2003/javen
f9a94b2e69443291d4b5c3db5a0fc0d1206d2d4a
a3c2312bc24356b1c58b1664543364bfc80e816d
refs/heads/master
2021-01-20T12:12:46.040953
2015-03-03T06:14:46
2015-03-03T06:14:46
30,912,222
0
1
null
2023-03-20T11:55:50
2015-02-17T10:24:28
Java
UTF-8
Java
false
false
4,208
java
package org.javenstudio.common.indexdb.analysis; import java.io.IOException; import java.io.Reader; import org.javenstudio.common.indexdb.IAnalyzer; import org.javenstudio.common.indexdb.ITokenStream; /** * An Analyzer builds TokenStreams, which analyze text. It thus represents a * policy for extracting index terms from text. * <p> * In order to define what analysis is done, subclasses must define their * {@link TokenComponents} in {@link #createComponents(String, Reader)}. * The components are then reused in each call to {@link #tokenStream(String, Reader)}. */ public abstract class Analyzer implements IAnalyzer { private final ReuseStrategy mReuseStrategy; public Analyzer() { this(new GlobalReuseStrategy()); } public Analyzer(ReuseStrategy reuseStrategy) { mReuseStrategy = reuseStrategy; } /** * Creates a new {@link TokenComponents} instance for this analyzer. * * @param fieldName * the name of the fields content passed to the * {@link TokenComponents} sink as a reader * @param reader * the reader passed to the {@link Tokenizer} constructor * @return the {@link TokenComponents} for this analyzer. */ public abstract TokenComponents createComponents(String fieldName, Reader reader) throws IOException; /** * Creates a TokenStream that is allowed to be re-use from the previous time * that the same thread called this method. Callers that do not need to use * more than one TokenStream at the same time from this analyzer should use * this method for better performance. * <p> * This method uses {@link #createComponents(String, Reader)} to obtain an * instance of {@link TokenComponents}. It returns the sink of the * components and stores the components internally. Subsequent calls to this * method will reuse the previously stored components after resetting them * through {@link TokenComponents#reset(Reader)}. * </p> * * @param fieldName the name of the field the created TokenStream is used for * @param reader the reader the streams source reads from */ @Override public final ITokenStream tokenStream(final String fieldName, final Reader reader) throws IOException { TokenComponents components = mReuseStrategy.getReusableComponents(fieldName); final Reader r = initReader(fieldName, reader); if (components == null) { components = createComponents(fieldName, r); mReuseStrategy.setReusableComponents(fieldName, components); } else { components.reset(r); } return components.getTokenStream(); } /** * Override this if you want to add a CharFilter chain. */ public Reader initReader(String fieldName, Reader reader) throws IOException { return reader; } /** * Invoked before indexing a IField instance if * terms have already been added to that field. This allows custom * analyzers to place an automatic position increment gap between * IndexbleField instances using the same field name. The default value * position increment gap is 0. With a 0 position increment gap and * the typical default token position increment of 1, all terms in a field, * including across IField instances, are in successive positions, allowing * exact PhraseQuery matches, for instance, across IField instance boundaries. * * @param fieldName IField name being indexed. * @return position increment gap, added to the next token emitted * from {@link #tokenStream(String,Reader)} */ @Override public int getPositionIncrementGap(String fieldName) throws IOException { return 0; } /** * Just like {@link #getPositionIncrementGap}, except for * Token offsets instead. By default this returns 1. * This method is only called if the field * produced at least one token for indexing. * * @param fieldName the field just indexed * @return offset gap, added to the next token emitted from * {@link #tokenStream(String,Reader)}. * This value must be {@code >= 0}. */ @Override public int getOffsetGap(String fieldName) throws IOException { return 1; } /** Frees persistent resources used by this Analyzer */ public void close() throws IOException { mReuseStrategy.close(); } }
[ "navychen2003@hotmail.com" ]
navychen2003@hotmail.com
638b4c90262b4a1689371638de012bd620c88889
9ad399f25dae98389d2333bc03bffb0167c6ff1f
/Manager_JFace/src/com/gxf/dao/DisplayDao.java
82915974a4a2622d94f797c092927421c0e602c8
[]
no_license
luckygxf/SNMP_MANAGER
6f8132a8028d0ccb4e1313171374be88b7ef657b
a2e22282431f0082231db7eac0e9f6b5bff0ed75
refs/heads/master
2021-01-23T02:54:01.219949
2015-11-11T07:31:18
2015-11-11T07:31:18
34,603,870
0
0
null
null
null
null
GB18030
Java
false
false
1,040
java
package com.gxf.dao; import java.util.List; import com.gxf.beans.Display; /** * 屏幕管理DAO * @author Administrator * */ public interface DisplayDao { /** * 添加屏幕到数据库 * @param display */ public void addDisplay(Display display); /** * 查询所有的显示屏 * @return */ public List<Display> queryAllDisplay(); /** * 根据屏幕id删除屏幕 * @param displayId */ public void deleteDisplayById(int displayId); /** * 根据名字查询显示屏 * @param name * @return */ public Display queryDisplayByName(String name); /** * 更新显示屏信息 * @param display */ public void updateDisplay(Display display); /** * 根据id查询显示屏 * @param id * @return */ public Display queryDisplayById(int id); /** * 更新当前播放方案 * @param displayName * @param curPlaySolutionName */ public void updateCurPlaySolution(String displayName, String curPlaySolutionName); }
[ "403261934@qq.com" ]
403261934@qq.com
ee075d60486dce13b918f8ee3e36ed4be9548ddc
a38c3f39e6891171e81fd40a263b06bb338a9ce9
/src/main/java/TestJOL.java
e00428bf43e4e08dd8e1d5d1ee0f067664f1cb11
[]
no_license
yiye-youshang/configtest
0b89bff3cedded881f34e51f5a5b592c50b1863c
c0b5b1e36f4ab228fa70cbd888919054d2d4aa4b
refs/heads/master
2023-01-18T16:32:17.532620
2020-11-19T08:27:34
2020-11-19T08:27:34
314,173,282
0
0
null
null
null
null
UTF-8
Java
false
false
1,161
java
import org.openjdk.jol.info.ClassLayout; //假如锁处于偏向状态,这时候来了竞争者,那他的状态是什么 public class TestJOL { public static void main(String[] args) { Object o = new Object(); /**解析一个对象的布局把他转成打印的类型 Instance size: 16 bytes 刚new一个对象无任何变量 占16个字节 前8个字节 叫markword 后4个字节 new出来的对象属于哪个类 叫klasspoint 最后4个字节是补出来的 为了能让8整除 提高效率 **/ System.out.println(ClassLayout.parseInstance(o).toPrintable()); // /* markword的值 未加锁状态 01 00 00 00 (00000001 00000000 00000000 00000000) (1) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) 28 f8 bd 02(00101000 11111000 10111101 00000010) (46004264) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) 加锁状态 简单来说 就是修改markword的值 * */ synchronized (o){ System.out.println(ClassLayout.parseInstance(o).toPrintable()); } } }
[ "tingyiyeyoushang@163.com" ]
tingyiyeyoushang@163.com
eb335a907e2e86d2632f158454c9299402b7d720
954dc04ed66f9e60e2dae8175bcdb62eb3f64e76
/src/main/java/com/ancientshores/AncientRPG/Classes/Spells/Parameters/BlockInSightParameter.java
54b73b2a9581ff3b56ad8cde5dee5a7e0b939c55
[]
no_license
ibornlp/AncientRPG
290e8c80ec835ea462bdf1f4afda9331c3e68dcd
0bcd45c00a633f187dd653218512dda81827d70c
refs/heads/master
2021-01-20T16:35:47.474009
2014-08-29T20:16:53
2014-08-29T20:16:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,054
java
package com.ancientshores.AncientRPG.Classes.Spells.Parameters; import com.ancientshores.AncientRPG.AncientRPG; import com.ancientshores.AncientRPG.Classes.Spells.Commands.EffectArgs; import com.ancientshores.AncientRPG.Classes.Spells.IParameter; import com.ancientshores.AncientRPG.Classes.Spells.ParameterDescription; import com.ancientshores.AncientRPG.Classes.Spells.ParameterType; import com.ancientshores.AncientRPG.Classes.Spells.SpellInformationObject; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.Arrays; import java.util.logging.Level; @ParameterDescription(amount = 1, description = "<html>returns the nearest block in sight of the player</html>", returntype = "Location", name = "BlockInSight") public class BlockInSightParameter implements IParameter { @Override public void parseParameter(EffectArgs ea, Player mPlayer, String[] subparam, ParameterType pt) { int range = 10; if (subparam != null) { try { if (ea.getSpell().variables.contains(subparam[0].toLowerCase())) { range = ea.getSpellInfo().parseVariable(mPlayer, subparam[0].toLowerCase()); } else { range = Integer.parseInt(subparam[0]); } } catch (Exception e) { AncientRPG.plugin.getLogger().log(Level.WARNING, "Error in subparameter " + Arrays.toString(subparam) + " in command " + ea.getCommand().commandString + " falling back to default"); } } if (subparam != null || ea.getSpellInfo().blockInSight == null) { Location nBlock = ea.getSpellInfo().getBlockInSight(mPlayer, range); ea.getSpellInfo().blockInSight = nBlock; if (nBlock == null) { return; } } switch (pt) { case Location: Location[] l = {ea.getSpellInfo().blockInSight}; ea.getParams().addLast(l); return; default: AncientRPG.plugin.getLogger().log(Level.SEVERE, "Syntax error in command " + ea.getCommand().commandString); } } @Override public String getName() { return "blockinsight"; } @Override public Object parseParameter(Player mPlayer, String[] subparam, SpellInformationObject so) { int range = 10; if (subparam != null) { try { if (so.mSpell.variables.contains(subparam[0].toLowerCase())) { range = so.parseVariable(mPlayer, subparam[0].toLowerCase()); } else { range = Integer.parseInt(subparam[0]); } } catch (Exception ignored) { } } if (subparam != null || so.blockInSight == null) { Location nBlock = so.getBlockInSight(mPlayer, range); so.blockInSight = nBlock; if (nBlock == null) { return null; } } return so.blockInSight; } }
[ "keyle@t-online.de" ]
keyle@t-online.de
ac75e70a264b9edb12e9b34c55a21d439919f476
c2eddf5d39727a839796eb5b436750d5948ee188
/app/src/main/java/com/josepmtomas/runstonerun/objects/MainMenu.java
8603cea9753e4394d663d6237419dd2f7ae3c91e
[]
no_license
JosepMTomas/RunStoneRun
0795384171bfa29ecb635a6b1a103410545b79d2
5fad7709454e9d9f3a8ba45c42cd77f248a94c0e
refs/heads/master
2021-01-10T19:34:05.399735
2015-02-25T10:04:49
2015-02-25T10:04:49
31,307,672
0
0
null
null
null
null
UTF-8
Java
false
false
32,350
java
package com.josepmtomas.runstonerun.objects; import android.content.SharedPreferences; import com.josepmtomas.runstonerun.ForwardRenderer; import com.josepmtomas.runstonerun.programs.ScorePanelProgram; import com.josepmtomas.runstonerun.programs.UIPanelProgram; import com.josepmtomas.runstonerun.util.UIHelper; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import static com.josepmtomas.runstonerun.Constants.*; import static com.josepmtomas.runstonerun.algebra.operations.*; import static android.opengl.GLES30.*; import static android.opengl.Matrix.*; /** * Created by Josep on 22/12/2014. * @author Josep */ public class MainMenu { // Geometry attributes constants private static final int POSITION_BYTE_OFFSET = 0; private static final int TEXCOORD_BYTE_OFFSET = 3 * BYTES_PER_FLOAT; private static final int BYTE_STRIDE = 5 * BYTES_PER_FLOAT; // private ForwardRenderer renderer; private MenuTextures textures; private SharedPreferences sharedPreferences; // State private int currentState; // Menu common attributes private static final float menuAppearTime = 0.5f; private static final float menuDisappearTime = 0.5f; private float menuTimer = 0f; private float menuOpacity = 1f; private float buttonsOpacity = 0.25f; private static final float BUTTONS_BASE_OPACITY = 0.25f; private boolean menuEnabled = true; // Matrices private float[] view = new float[16]; private float[] projection = new float[16]; private float[] viewProjection = new float[16]; // UI Panel private int uiPanelVaoHandle; private int buttonsBackPanelVaoHandle; private int recordBackPanelVaoHandle; // Buttons back panel private float[] buttonsBackPanelPosition = new float[2]; private float[] buttonsBackPanelCurrentScale = new float[2]; private float[] buttonsBackPanelCurrentPosition = new float[2]; // Record back panel private float[] recordBackPanelPosition = new float[2]; private float[] recordBackPanelCurrentScale = new float[2]; private float[] recordBackPanelCurrentPosition = new float[2]; // Game title private float[] gameTitleScale = new float[2]; private float[] gameTitlePosition = new float[2]; private float[] gameTitleCurrentScale = new float[2]; private float[] gameTitleCurrentPosition = new float[2]; // New game button private int newGameButtonCurrentTexture; private float[] newGameButtonScale = new float[2]; private float[] newGameButtonPosition = new float[2]; private float[] newGameButtonCurrentScale = new float[2]; private float[] newGameButtonCurrentPosition = new float[2]; private float[] newGameButtonLimits = new float[4]; // How to play button private int howToPlayButtonCurrentTexture; private float[] howToPlayButtonScale = new float[2]; private float[] howToPlayButtonPosition = new float[2]; private float[] howToPlayButtonCurrentScale = new float[2]; private float[] howToPlayButtonCurrentPosition = new float[2]; private float[] howToPlayButtonLimits = new float[4]; // Options button private int optionsButtonCurrentTexture; private float[] optionsButtonScale = new float[2]; private float[] optionsButtonPosition = new float[2]; private float[] optionsButtonCurrentScale = new float[2]; private float[] optionsButtonCurrentPosition = new float[2]; private float[] optionsButtonLimits = new float[4]; // Credits button private int creditsButtonCurrentTexture; private float[] creditsButtonScale = new float[2]; private float[] creditsButtonPosition = new float[2]; private float[] creditsButtonCurrentScale = new float[2]; private float[] creditsButtonCurrentPosition = new float[2]; private float[] creditsButtonLimits = new float[4]; // Exit button private int exitButtonCurrentTexture; private float[] exitButtonScale = new float[2]; private float[] exitButtonPosition = new float[2]; private float[] exitButtonCurrentScale = new float[2]; private float[] exitButtonCurrentPosition = new float[2]; private float[] exitButtonLimits = new float[4]; // Record button private float[] recordButtonScale = new float[2]; private float[] recordButtonPosition = new float[2]; private float[] recordButtonCurrentScale = new float[2]; private float[] recordButtonCurrentPosition = new float[2]; // Speed button private boolean speedButtonEnabled = false; private float[] speedButtonScale = new float[2]; private float[] speedButtonPosition = new float[2]; private float[] speedButtonCurrentScale = new float[2]; private float[] speedButtonCurrentPosition = new float[2]; private float[] speedButtonLimits = new float[4]; private int speedButtonTexture; // Visibility button private boolean visibilityButtonEnabled = true; private float[] visibilityButtonScale = new float[2]; private float[] visibilityButtonPosition = new float[2]; private float[] visibilityButtonCurrentScale = new float[2]; private float[] visibilityButtonCurrentPosition = new float[2]; private float[] visibilityButtonLimits = new float[4]; private int visibilityButtonTexture; // Score panel private int[] scoreVboHandles = new int[2]; private int[] scoreVaoHandle = new int[1]; private float[] scoreOpacities = new float[8]; private float[] scorePositionsX = new float[8]; private float scorePositionY = 0; private float[] scoreTexCoordOffsetsX = { 0f, 0f, 0f, 0f, 0.25f, 0.25f, 0.25f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.75f, 0.75f}; private float[] scoreTexCoordOffsetsY = {-0.75f, -0.5f, -0.25f, 0f, -0.75f, -0.5f, -0.25f, 0f, -0.75f, -0.5f, -0.25f, 0f, -0.75f, -0.5f}; private float scoreNumberWidth; private int[] scoreNumbers = {0, 0, 0, 0, 0, 0, 0, 0}; private float scoreCurrentScale = 1f; private float[] scoreCurrentPositionsX = new float[8]; private float scoreCurrentPositionY = 0f; // renderer ui programs private UIPanelProgram uiPanelProgram; private ScorePanelProgram scorePanelProgram; public MainMenu(ForwardRenderer renderer, SharedPreferences sharedPreferences, UIPanelProgram panelProgram, ScorePanelProgram scorePanelProgram, MenuTextures textures, float screenWidth, float screenHeight) { this.renderer = renderer; this.sharedPreferences = sharedPreferences; this.textures = textures; this.uiPanelProgram = panelProgram; this.scorePanelProgram = scorePanelProgram; this.currentState = UI_STATE_VISIBLE; createMatrices(screenWidth, screenHeight); loadTextures(); uiPanelVaoHandle = UIHelper.makePanel(1f, 1f, UI_BASE_CENTER_CENTER); createGameTitle(screenWidth, screenHeight); createButtons(screenWidth, screenHeight); createButtonsBackPanel(screenWidth, screenHeight); createRecordBackPanel(screenWidth, screenHeight); createRecordButton(screenWidth, screenHeight); createScoreGeometry(screenWidth, screenHeight); setScore(screenWidth, screenHeight); setCurrentPositions(); loadPreferences(); } private void createMatrices(float screenWidth, float screenHeight) { float right = screenWidth * 0.5f; float left = -right; float top = screenHeight * 0.5f; float bottom = -top; float near = 0.5f; float far = 10f; // Initialize view matrix setIdentityM(view, 0); setLookAtM(view, 0, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f); // Initialize projection matrix setIdentityM(projection, 0); orthoM(projection, 0, left, right, bottom, top, near, far); // Calculate view x projection matrix multiplyMM(viewProjection, 0, projection, 0, view, 0); } private void loadTextures() { newGameButtonCurrentTexture = textures.newGameButtonIdleTexture; howToPlayButtonCurrentTexture = textures.howToPlayButtonIdleTexture; optionsButtonCurrentTexture = textures.optionsButtonIdleTexture; creditsButtonCurrentTexture = textures.creditsButtonIdleTexture; exitButtonCurrentTexture = textures.exitButtonIdle; speedButtonTexture = textures.speedNormalTexture; visibilityButtonTexture = textures.visibilityEnabledTexture; } private void loadPreferences() { speedButtonEnabled = !sharedPreferences.getBoolean("SpeedEnabled", false); touchSpeedButton(); } private void savePreferences() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("SpeedEnabled", speedButtonEnabled); editor.putBoolean("VisibilityEnabled", visibilityButtonEnabled); editor.apply(); } private void createGameTitle(float screenWidth, float screenHeight) { float width = screenWidth * 0.9f; float height = width * 0.17647f; gameTitleScale[0] = width; gameTitleScale[1] = height; gameTitlePosition[0] = 0f; gameTitlePosition[1] = screenHeight * 0.3375f; gameTitleCurrentScale[0] = gameTitleScale[0]; gameTitleCurrentScale[1] = gameTitleScale[1]; gameTitleCurrentPosition[0] = gameTitlePosition[0]; gameTitleCurrentPosition[1] = gameTitlePosition[1]; } private void createButtons(float screenWidth, float screenHeight) { float width = screenWidth * 0.3f; float height = screenWidth * 0.0902f; createNewGameButton(width, height); createHowToPlayButton(width, height); createOptionsButton(width, height); createCreditsButton(width, height); createExitButton(screenWidth, screenHeight); createSpeedButton(screenWidth, screenHeight); createVisibilityButton(screenWidth, screenHeight); } public void createButtonsBackPanel(float screenWidth, float screenHeight) { float borderSize = screenHeight * 0.025f; //float cornerSize = screenWidth * 0.06f * 0.3f + borderSize; float cornerSize = screenWidth * 0.0902f * 0.3f + borderSize; float width = (screenWidth * 0.6f) + (borderSize * 2f); float height = (screenWidth * 0.0902f * 2f) + (borderSize * 2f); buttonsBackPanelVaoHandle = UIHelper.make9PatchPanel(width, height, cornerSize, UI_BASE_CENTER_CENTER); buttonsBackPanelCurrentScale[0] = 1f; buttonsBackPanelCurrentScale[1] = 1f; buttonsBackPanelPosition[0] = 0f; buttonsBackPanelPosition[1] = newGameButtonPosition[1] - (screenWidth * 0.0451f);//optionsButtonPosition[1] + (screenWidth * 0.03f); buttonsBackPanelCurrentPosition[0] = buttonsBackPanelPosition[0]; buttonsBackPanelCurrentPosition[1] = buttonsBackPanelPosition[1]; } @SuppressWarnings("unused") private void createRecordBackPanel(float screenWidth, float screenHeight) { float borderSize = screenHeight * 0.025f; float cornerSize = screenHeight * 0.03f + borderSize;// 0.048 float width = (screenHeight * 0.9f) + (borderSize * 2f);//0.8 float height = (screenHeight * 0.1f) + (borderSize * 2f); recordBackPanelVaoHandle = UIHelper.make9PatchPanel(width, height, cornerSize, UI_BASE_CENTER_CENTER); recordBackPanelCurrentScale[0] = 1f; recordBackPanelCurrentScale[1] = 1f; recordBackPanelPosition[0] = 0f; recordBackPanelPosition[1] = height * 0.75f; recordBackPanelCurrentPosition[0] = recordBackPanelPosition[0]; recordBackPanelCurrentPosition[1] = recordBackPanelPosition[1]; } private void createNewGameButton(float width, float height) { newGameButtonScale[0] = width; newGameButtonScale[1] = height; newGameButtonPosition[0] = width * -0.5f; newGameButtonPosition[1] = height * -0.5f; //-0.375f; // left-right-bottom-top newGameButtonLimits[0] = newGameButtonPosition[0] - (width * 0.5f); newGameButtonLimits[1] = newGameButtonPosition[0] + (width * 0.5f); newGameButtonLimits[2] = newGameButtonPosition[1] - (height * 0.5f); newGameButtonLimits[3] = newGameButtonPosition[1] + (height * 0.5f); } private void createHowToPlayButton(float width, float height) { howToPlayButtonScale[0] = width; howToPlayButtonScale[1] = height; howToPlayButtonPosition[0] = newGameButtonPosition[0]; howToPlayButtonPosition[1] = newGameButtonPosition[1] - height; howToPlayButtonLimits[0] = howToPlayButtonPosition[0] - (width * 0.5f); howToPlayButtonLimits[1] = howToPlayButtonPosition[0] + (width * 0.5f); howToPlayButtonLimits[2] = howToPlayButtonPosition[1] - (height * 0.5f); howToPlayButtonLimits[3] = howToPlayButtonPosition[1] + (height * 0.5f); } private void createOptionsButton(float width, float height) { optionsButtonScale[0] = width; optionsButtonScale[1] = height; optionsButtonPosition[0] = newGameButtonPosition[0] + width; optionsButtonPosition[1] = newGameButtonPosition[1]; // left-right-bottom-top optionsButtonLimits[0] = optionsButtonPosition[0] - (width * 0.5f); optionsButtonLimits[1] = optionsButtonPosition[0] + (width * 0.5f); optionsButtonLimits[2] = optionsButtonPosition[1] - (height * 0.5f); optionsButtonLimits[3] = optionsButtonPosition[1] + (height * 0.5f); } private void createCreditsButton(float width, float height) { creditsButtonScale[0] = width; creditsButtonScale[1] = height; creditsButtonPosition[0] = optionsButtonPosition[0]; creditsButtonPosition[1] = optionsButtonPosition[1] - height; // left-right-bottom-top creditsButtonLimits[0] = creditsButtonPosition[0] - (width * 0.5f); creditsButtonLimits[1] = creditsButtonPosition[0] + (width * 0.5f); creditsButtonLimits[2] = creditsButtonPosition[1] - (height * 0.5f); creditsButtonLimits[3] = creditsButtonPosition[1] + (height * 0.5f); } @SuppressWarnings("unused") private void createExitButton(float screenWidth, float screenHeight) { float size = screenHeight * 0.15f; float sizeHalf = size * 0.5f; float positionOffset = size * 0.75f; exitButtonScale[0] = size; exitButtonScale[1] = size; exitButtonPosition[0] = screenWidth * 0.5f - positionOffset; exitButtonPosition[1] = screenHeight * -0.5f + positionOffset; // left-right-bottom-top exitButtonLimits[0] = exitButtonPosition[0] - sizeHalf; exitButtonLimits[1] = exitButtonPosition[0] + sizeHalf; exitButtonLimits[2] = exitButtonPosition[1] - sizeHalf; exitButtonLimits[3] = exitButtonPosition[1] + sizeHalf; } @SuppressWarnings("unused") private void createRecordButton(float screenWidth, float screenHeight) { float height = screenHeight * 0.1f; float width = height * 3f; recordButtonScale[0] = width; recordButtonScale[1] = height; recordButtonPosition[0] = recordBackPanelPosition[0] - (screenHeight * 0.3f);//25 recordButtonPosition[1] = recordBackPanelPosition[1]; } private void createSpeedButton(float screenWidth, float screenHeight) { float buttonSize = screenHeight * 0.15f; float buttonSizeHalf = buttonSize * 0.5f; speedButtonScale[0] = buttonSize; speedButtonScale[1] = buttonSize; speedButtonPosition[0] = screenWidth * -0.5f + buttonSizeHalf; speedButtonPosition[1] = buttonSize * 0.5f; // left-right-bottom-top speedButtonLimits[0] = speedButtonPosition[0] - (buttonSizeHalf); speedButtonLimits[1] = speedButtonPosition[0] + (buttonSizeHalf); speedButtonLimits[2] = speedButtonPosition[1] - (buttonSizeHalf); speedButtonLimits[3] = speedButtonPosition[1] + (buttonSizeHalf); } private void createVisibilityButton(float screenWidth, float screenHeight) { float buttonSize = screenHeight * 0.15f; float buttonSizeHalf = buttonSize * 0.5f; visibilityButtonScale[0] = buttonSize; visibilityButtonScale[1] = buttonSize; visibilityButtonPosition[0] = screenWidth * -0.5f + buttonSizeHalf; visibilityButtonPosition[1] = buttonSize * -0.5f; // left-right-bottom-top visibilityButtonLimits[0] = visibilityButtonPosition[0] - (buttonSizeHalf); visibilityButtonLimits[1] = visibilityButtonPosition[0] + (buttonSizeHalf); visibilityButtonLimits[2] = visibilityButtonPosition[1] - (buttonSizeHalf); visibilityButtonLimits[3] = visibilityButtonPosition[1] + (buttonSizeHalf); } @SuppressWarnings("unused") private void createScoreGeometry(float screenWidth, float screenHeight) { float[] vertices = new float[20]; short[] elements = new short[6]; float numberHeight = screenHeight * 0.2f; float numberWidth = numberHeight * 0.7134f; scoreNumberWidth = numberWidth; float bottom = -numberHeight * 0.5f; float left = -numberWidth * 0.5f; // D - C // | \ | // A - B int offset = 0; for(int y=0; y<2; y++) { for(int x=0; x<2; x++) { // Position vertices[offset++] = left + ((float)x * numberWidth); vertices[offset++] = bottom + ((float)y * numberHeight); vertices[offset++] = 0.0f; // Texture Coordinates vertices[offset++] = (float)x * 0.25f; vertices[offset++] = 1.0f - (float)y * 0.25f; } } // Indices elements[0] = 0; elements[1] = 1; elements[2] = 2; elements[3] = 1; elements[4] = 3; elements[5] = 2; // Java native buffers FloatBuffer verticesBuffer; ShortBuffer elementsBuffer; verticesBuffer = ByteBuffer .allocateDirect(vertices.length * BYTES_PER_FLOAT) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(vertices); verticesBuffer.position(0); elementsBuffer = ByteBuffer .allocateDirect(elements.length * BYTES_PER_SHORT) .order(ByteOrder.nativeOrder()) .asShortBuffer() .put(elements); elementsBuffer.position(0); // Create and populate the buffer objects glGenBuffers(2, scoreVboHandles, 0); glBindBuffer(GL_ARRAY_BUFFER, scoreVboHandles[0]); glBufferData(GL_ARRAY_BUFFER, verticesBuffer.capacity() * BYTES_PER_FLOAT, verticesBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scoreVboHandles[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementsBuffer.capacity() * BYTES_PER_SHORT, elementsBuffer, GL_STATIC_DRAW); // Create the VAO glGenVertexArrays(1, scoreVaoHandle, 0); glBindVertexArray(scoreVaoHandle[0]); // Vertex positions glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, scoreVboHandles[0]); glVertexAttribPointer(0, 3, GL_FLOAT, false, BYTE_STRIDE, POSITION_BYTE_OFFSET); // Vertex texture coordinates glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, scoreVboHandles[0]); glVertexAttribPointer(1, 2, GL_FLOAT, false, BYTE_STRIDE, TEXCOORD_BYTE_OFFSET); // Elements glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scoreVboHandles[1]); glBindVertexArray(0); } private void setCurrentPositions() { newGameButtonCurrentScale[0] = newGameButtonScale[0]; newGameButtonCurrentScale[1] = newGameButtonScale[1]; newGameButtonCurrentPosition[0] = newGameButtonPosition[0]; newGameButtonCurrentPosition[1] = newGameButtonPosition[1]; howToPlayButtonCurrentScale[0] = howToPlayButtonScale[0]; howToPlayButtonCurrentScale[1] = howToPlayButtonScale[1]; howToPlayButtonCurrentPosition[0] = howToPlayButtonPosition[0]; howToPlayButtonCurrentPosition[1] = howToPlayButtonPosition[1]; optionsButtonCurrentScale[0] = optionsButtonScale[0]; optionsButtonCurrentScale[1] = optionsButtonScale[1]; optionsButtonCurrentPosition[0] = optionsButtonPosition[0]; optionsButtonCurrentPosition[1] = optionsButtonPosition[1]; creditsButtonCurrentScale[0] = creditsButtonScale[0]; creditsButtonCurrentScale[1] = creditsButtonScale[1]; creditsButtonCurrentPosition[0] = creditsButtonPosition[0]; creditsButtonCurrentPosition[1] = creditsButtonPosition[1]; exitButtonCurrentScale[0] = exitButtonScale[0]; exitButtonCurrentScale[1] = exitButtonScale[1]; exitButtonCurrentPosition[0] = exitButtonPosition[0]; exitButtonCurrentPosition[1] = exitButtonPosition[1]; recordButtonCurrentScale[0] = recordButtonScale[0]; recordButtonCurrentScale[1] = recordButtonScale[1]; recordButtonCurrentPosition[0] = recordButtonPosition[0]; recordButtonCurrentPosition[1] = recordButtonPosition[1]; speedButtonCurrentScale[0] = speedButtonScale[0]; speedButtonCurrentScale[1] = speedButtonScale[1]; speedButtonCurrentPosition[0] = speedButtonPosition[0]; speedButtonCurrentPosition[1] = speedButtonPosition[1]; visibilityButtonCurrentScale[0] = visibilityButtonScale[0]; visibilityButtonCurrentScale[1] = visibilityButtonScale[1]; visibilityButtonCurrentPosition[0] = visibilityButtonPosition[0]; visibilityButtonCurrentPosition[1] = visibilityButtonPosition[1]; } @SuppressWarnings("unused") public void setScore(float screenWidth, float screenHeight) { // get current high score from shared preferences int score = sharedPreferences.getInt("LocalHighScore",0); int i; boolean end = false; int number; int nextScore = score; for(i=0; i<8; i++) { scoreNumbers[i] = 0; scoreOpacities[i] = 0.375f; } i=0; //scoreNumberOfDigits = 0; while(i < 8 && !end) { number = nextScore % 10; nextScore = nextScore / 10; scoreNumbers[i] = number; scoreOpacities[i] = 1f; //scoreNumberOfDigits++; if(nextScore == 0) end = true; i++; } scorePositionY = recordButtonPosition[1] + (screenHeight * 0.115f); scoreCurrentPositionY = scorePositionY; float initialX = screenHeight * 0.815f; for(i=0; i<8; i++) { scorePositionsX[i] = initialX - (i*scoreNumberWidth); scoreCurrentPositionsX[i] = scorePositionsX[i]; } } public void updateScore() { int i; boolean end = false; int number; int nextScore = sharedPreferences.getInt("LocalHighScore",0); for(i=0; i<8; i++) { scoreNumbers[i] = 0; scoreOpacities[i] = 0.375f; } i=0; while(i < 8 && !end) { number = nextScore % 10; nextScore = nextScore / 10; scoreNumbers[i] = number; scoreOpacities[i] = 1f; if(nextScore == 0) end = true; i++; } } public void touch(float x, float y) { if(menuEnabled) { if( x >= newGameButtonLimits[0] && x <= newGameButtonLimits[1] && y >= newGameButtonLimits[2] && y <= newGameButtonLimits[3]) { touchNewGameButton(); } else if(x >= howToPlayButtonLimits[0] && x <= howToPlayButtonLimits[1] && y >= howToPlayButtonLimits[2] && y <= howToPlayButtonLimits[3]) { touchHowToPlayButton(); } else if(x >= optionsButtonLimits[0] && x <= optionsButtonLimits[1] && y >= optionsButtonLimits[2] && y <= optionsButtonLimits[3]) { touchOptionsButton(); } else if(x >= optionsButtonLimits[0] && x <= optionsButtonLimits[1] && y >= creditsButtonLimits[2] && y <= creditsButtonLimits[3]) { touchCreditsButton(); } else if(x >= exitButtonLimits[0] && x <= exitButtonLimits[1] && y >= exitButtonLimits[2] && y <= exitButtonLimits[3]) { touchExitButton(); } } if( x >= speedButtonLimits[0] && x <= speedButtonLimits[1] && y >= speedButtonLimits[2] && y <= speedButtonLimits[3]) { touchSpeedButton(); } else if(x >= visibilityButtonLimits[0] && x <= visibilityButtonLimits[1] && y >= visibilityButtonLimits[2] && y <= visibilityButtonLimits[3]) { touchVisibilityButton(); } } public void releaseTouch() { newGameButtonCurrentTexture = textures.newGameButtonIdleTexture; howToPlayButtonCurrentTexture = textures.howToPlayButtonIdleTexture; optionsButtonCurrentTexture = textures.optionsButtonIdleTexture; creditsButtonCurrentTexture = textures.creditsButtonIdleTexture; exitButtonCurrentTexture = textures.exitButtonIdle; } private void touchNewGameButton() { newGameButtonCurrentTexture = textures.newGameButtonSelectedTexture; renderer.newGame(); currentState = UI_STATE_DISAPPEARING; } private void touchHowToPlayButton() { howToPlayButtonCurrentTexture = textures.howToPlayButtonSelectedTexture; renderer.changingToHowToPlayMenu(); currentState = UI_STATE_DISAPPEARING; } private void touchOptionsButton() { optionsButtonCurrentTexture = textures.optionsButtonSelectedTexture; renderer.changingToOptionsMenuFromMainMenu(); currentState = UI_STATE_DISAPPEARING; } private void touchCreditsButton() { creditsButtonCurrentTexture = textures.creditsButtonSelectedTexture; renderer.changingToCreditsMenu(); currentState = UI_STATE_DISAPPEARING; } private void touchExitButton() { exitButtonCurrentTexture = textures.exitButtonSelected; renderer.onBackPressed(); } private void touchSpeedButton() { speedButtonEnabled = !speedButtonEnabled; if(speedButtonEnabled) { speedButtonTexture = textures.speedFastTexture; } else { speedButtonTexture = textures.speedNormalTexture; } savePreferences(); renderer.setMenuSpeed(speedButtonEnabled); } private void touchVisibilityButton() { visibilityButtonEnabled = !visibilityButtonEnabled; if(visibilityButtonEnabled) { visibilityButtonTexture = textures.visibilityEnabledTexture; menuOpacity = 1.0f; menuEnabled = true; } else { visibilityButtonTexture = textures.visibilityDisabledTexture; menuOpacity = 0.0f; menuEnabled = false; } savePreferences(); } public void setNotVisible() { currentState = UI_STATE_NOT_VISIBLE; buttonsOpacity = 0f; } public void setAppearing() { loadPreferences(); updateScore(); currentState = UI_STATE_APPEARING; } public void setCurrentElementsAttributes(float alpha) { buttonsBackPanelCurrentScale[0] = lerp(0f, 1f, alpha); buttonsBackPanelCurrentScale[1] = lerp(0f, 1f, alpha); buttonsBackPanelCurrentPosition[0] = lerp(0f, buttonsBackPanelPosition[0], alpha); buttonsBackPanelCurrentPosition[1] = lerp(0f, buttonsBackPanelPosition[1], alpha); recordBackPanelCurrentScale[0] = lerp(0f, 1f, alpha); recordBackPanelCurrentScale[1] = lerp(0f, 1f, alpha); recordBackPanelCurrentPosition[0] = lerp(0f, recordBackPanelPosition[0], alpha); recordBackPanelCurrentPosition[1] = lerp(0f, recordBackPanelPosition[1], alpha); gameTitleCurrentScale[0] = lerp(0f, gameTitleScale[0], alpha); gameTitleCurrentScale[1] = lerp(0f, gameTitleScale[1], alpha); gameTitleCurrentPosition[0] = lerp(0f, gameTitlePosition[0], alpha); gameTitleCurrentPosition[1] = lerp(0f, gameTitlePosition[1], alpha); newGameButtonCurrentScale[0] = lerp(0f, newGameButtonScale[0], alpha); newGameButtonCurrentScale[1] = lerp(0f, newGameButtonScale[1], alpha); newGameButtonCurrentPosition[0] = lerp(0f, newGameButtonPosition[0], alpha); newGameButtonCurrentPosition[1] = lerp(0f, newGameButtonPosition[1], alpha); howToPlayButtonCurrentScale[0] = lerp(0f, howToPlayButtonScale[0], alpha); howToPlayButtonCurrentScale[1] = lerp(0f, howToPlayButtonScale[1], alpha); howToPlayButtonCurrentPosition[0] = lerp(0f, howToPlayButtonPosition[0], alpha); howToPlayButtonCurrentPosition[1] = lerp(0f, howToPlayButtonPosition[1], alpha); optionsButtonCurrentScale[0] = lerp(0f, optionsButtonScale[0], alpha); optionsButtonCurrentScale[1] = lerp(0f, optionsButtonScale[1], alpha); optionsButtonCurrentPosition[0] = lerp(0f, optionsButtonPosition[0], alpha); optionsButtonCurrentPosition[1] = lerp(0f, optionsButtonPosition[1], alpha); creditsButtonCurrentScale[0] = lerp(0f, creditsButtonScale[0], alpha); creditsButtonCurrentScale[1] = lerp(0f, creditsButtonScale[1], alpha); creditsButtonCurrentPosition[0] = lerp(0f, creditsButtonPosition[0], alpha); creditsButtonCurrentPosition[1] = lerp(0f, creditsButtonPosition[1], alpha); exitButtonCurrentScale[0] = lerp(exitButtonScale[0] * 2f, exitButtonScale[0], alpha); exitButtonCurrentScale[1] = lerp(exitButtonScale[1] * 2f, exitButtonScale[1], alpha); exitButtonCurrentPosition[0] = lerp(exitButtonPosition[0] * 2f, exitButtonPosition[0], alpha); exitButtonCurrentPosition[1] = lerp(exitButtonPosition[1] * 2f, exitButtonPosition[1], alpha); recordButtonCurrentScale[0] = lerp(0f, recordButtonScale[0], alpha); recordButtonCurrentScale[1] = lerp(0f, recordButtonScale[1], alpha); recordButtonCurrentPosition[0] = lerp(0f, recordButtonPosition[0], alpha); recordButtonCurrentPosition[1] = lerp(0f, recordButtonPosition[1], alpha); scoreCurrentScale = alpha; scoreCurrentPositionY = lerp(0f, scorePositionY, alpha); for(int i=0; i<8; i++) { scoreCurrentPositionsX[i] = lerp(0f, scorePositionsX[i], alpha); } } public void update(float deltaTime) { if(currentState == UI_STATE_APPEARING) { menuTimer += deltaTime; menuOpacity = menuTimer / menuAppearTime; buttonsOpacity = menuOpacity * BUTTONS_BASE_OPACITY; if(menuTimer >= menuAppearTime) { currentState = UI_STATE_VISIBLE; menuOpacity = 1f; buttonsOpacity = BUTTONS_BASE_OPACITY; menuTimer = 0f; renderer.changedToMainMenu(); } setCurrentElementsAttributes(menuOpacity); } else if(currentState == UI_STATE_DISAPPEARING) { menuTimer += deltaTime; menuOpacity = 1f - (menuTimer / menuDisappearTime); buttonsOpacity = menuOpacity * BUTTONS_BASE_OPACITY; if(menuTimer >= menuDisappearTime) { currentState = UI_STATE_NOT_VISIBLE; menuOpacity = 0f; buttonsOpacity = 0f; menuTimer = 0f; } setCurrentElementsAttributes(menuOpacity); } } public void draw() { if(currentState != UI_STATE_NOT_VISIBLE && menuEnabled) { uiPanelProgram.useProgram(); glBindVertexArray(buttonsBackPanelVaoHandle); uiPanelProgram.setUniforms(viewProjection, buttonsBackPanelCurrentScale, buttonsBackPanelCurrentPosition, textures.background9PatchPanelTexture, 0.75f * menuOpacity); glDrawElements(GL_TRIANGLES, 54, GL_UNSIGNED_SHORT, 0); glBindVertexArray(recordBackPanelVaoHandle); uiPanelProgram.setUniforms(viewProjection, recordBackPanelCurrentScale, recordBackPanelCurrentPosition, textures.background9PatchPanelTexture, 0.75f * menuOpacity); glDrawElements(GL_TRIANGLES, 54, GL_UNSIGNED_SHORT, 0); glBindVertexArray(uiPanelVaoHandle); uiPanelProgram.setUniforms(viewProjection, gameTitleCurrentScale, gameTitleCurrentPosition, textures.gameTitleTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, newGameButtonCurrentScale, newGameButtonCurrentPosition, newGameButtonCurrentTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, howToPlayButtonCurrentScale, howToPlayButtonCurrentPosition, howToPlayButtonCurrentTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, optionsButtonCurrentScale, optionsButtonCurrentPosition, optionsButtonCurrentTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, creditsButtonCurrentScale, creditsButtonCurrentPosition, creditsButtonCurrentTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, exitButtonCurrentScale, exitButtonCurrentPosition, exitButtonCurrentTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, recordButtonCurrentScale, recordButtonCurrentPosition, textures.recordButtonTexture, menuOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, speedButtonCurrentScale, speedButtonCurrentPosition, speedButtonTexture, buttonsOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, visibilityButtonCurrentScale, visibilityButtonCurrentPosition, visibilityButtonTexture, buttonsOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); //if(previousScoreSet) { scorePanelProgram.useProgram(); scorePanelProgram.setCommonUniforms(viewProjection, textures.numbersAtlasTexture); glBindVertexArray(scoreVaoHandle[0]); for(int i=0; i < 8; i++) { scorePanelProgram.setSpecificUniforms(scoreCurrentScale, scoreCurrentPositionsX[i], scoreCurrentPositionY, scoreTexCoordOffsetsX[scoreNumbers[i]], scoreTexCoordOffsetsY[scoreNumbers[i]], 1f, 1f, 1f, menuOpacity * scoreOpacities[i]); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); } } } else { uiPanelProgram.useProgram(); glBindVertexArray(uiPanelVaoHandle); uiPanelProgram.setUniforms(viewProjection, speedButtonCurrentScale, speedButtonCurrentPosition, speedButtonTexture, buttonsOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); uiPanelProgram.setUniforms(viewProjection, visibilityButtonCurrentScale, visibilityButtonCurrentPosition, visibilityButtonTexture, buttonsOpacity); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); } } public boolean onBackPressed() { if(!menuEnabled) { touchVisibilityButton(); return false; } else { return true; } } }
[ "josepmtomas90@gmail.com" ]
josepmtomas90@gmail.com
7fee5297a7312bed790043ec9499718a3c6beac3
7074402137d4b4df6c114e5153ba543f2a8fc35e
/com.yd.parent/com.yd.api/src/main/java/com/yd/api/service/common/PayService.java
740123bba769825ad694f31ba5e284566fa6ab7d
[]
no_license
wushiba/source-code
f03d61c319274bb779df854ef4f81bb9febe634a
aa3e4cb7e778855b49076a7520ef36c9bf97fcd5
refs/heads/main
2023-01-30T20:28:48.061818
2020-12-16T15:16:02
2020-12-16T15:16:02
305,932,850
0
3
null
null
null
null
UTF-8
Java
false
false
981
java
package com.yd.api.service.common; import java.util.Date; import com.yd.api.pay.EnumPayMethod; import com.yd.api.pay.req.PayReq; import com.yd.api.pay.result.PayParam; import com.yd.api.result.common.WbAlipayAccountResult; import com.yd.api.result.common.WbPayOrderResult; import com.yd.api.result.common.WbPaySecretResult; import com.yd.api.result.common.WbWeixinAccountResult; import com.yd.core.utils.BusinessException; public interface PayService { WbAlipayAccountResult findAlipayAccountById(int id); WbWeixinAccountResult findWexinAccountById(int id); WbPaySecretResult findPaySecretById(int id); WbPayOrderResult payNotifyWithPayAccountId(Integer payOrderId, EnumPayMethod alipayWap, String totalFee,String tradeNo, Date date, Integer id); PayParam createOrderAndPay(PayReq req) throws BusinessException; WbPayOrderResult findPayOrderById(Integer id); WbAlipayAccountResult findDefaultAlipayAccount(); WbWeixinAccountResult findDefaultWexinAccount(); }
[ "363648823@qq.com" ]
363648823@qq.com
7c74d5ee8459efb2a3bf625c7d87d63b5b22754d
76a7c720f8c0c5babd092093708e7323dd941aa4
/bubing_tools/src/main/java/com/bubing/tools/utils/JsonUtils.java
6aa4569d08e8575df94dbed707637e26422cb2b3
[]
no_license
General757/BubingTools
13b2622a65cdba982a8f5ab2b6d6541ce4f1d14a
550af7395935e3f2e1411a9c80eed6698343a607
refs/heads/master
2023-02-23T03:53:10.106504
2020-11-02T03:35:04
2020-11-02T03:35:04
260,145,210
0
0
null
null
null
null
UTF-8
Java
false
false
3,469
java
package com.bubing.tools.utils; import android.text.TextUtils; import org.json.JSONException; import org.json.JSONObject; //json解析辅助工具 public class JsonUtils { /* 移除bom */ public static final String removeBOM(String data) { if (TextUtils.isEmpty(data)) return data; if (data.startsWith("\ufeff")) return data.substring(1); else return data; } /* * json字段是Boolean */ public static boolean getJSONBoolean(JSONObject json, String name) throws JSONException { if (json.has(name)) return json.getBoolean(name); else return false; } /* * json字段是Double */ public static double getJSONDouble(JSONObject json, String name) throws JSONException { if (json.has(name)) { if (TextUtils.isEmpty(json.getString(name))) return 0; else return Double.valueOf(json.getString(name)); } else return 0; } /* * json字段是Float */ public static float getJSONFloat(JSONObject json, String name) throws JSONException { if (json.has(name)) { if (TextUtils.isEmpty(json.getString(name))) return 0; else return Float.valueOf(json.getString(name)); } else return 0; } /* * json字段是Int */ public static int getJSONInt(JSONObject json, String name) throws JSONException { if (json.has(name)) { if (TextUtils.isEmpty(json.getString(name))) return 0; else return json.getInt(name); } else return 0; } /* * json字段是LOng */ public static long getJSONLong(JSONObject json, String name) throws JSONException { if (json.has(name)) { if (TextUtils.isEmpty(json.getString(name))) return 0; else return json.getLong(name); } else return 0; } /* * json字段是String */ public static String getJSONString(JSONObject json, String name) throws JSONException { if (json.has(name)) { String value = json.getString(name); if (TextUtils.isEmpty(value)) return ""; else return value; } else return ""; } /* * json字段是否为空 */ public static boolean getJSONObjectText(JSONObject json, String name) throws JSONException { if (json.has(name)) { String value = json.getString(name); if (TextUtils.isEmpty(value)) return false; else if (value.equals("[]")) return false; else if (value.equals("{}")) return false; else return true; } else return false; } /* * json数组是否为空 */ public static String getJSONArrayText(JSONObject json, String name) throws JSONException { if (json.has(name)) { String value = json.getString(name); if (TextUtils.isEmpty(value)) return "[]"; else if (value.equals("{}")) return "[]"; else return value; } else return "[]"; } }
[ "1183561804@qq.com" ]
1183561804@qq.com
cebbbb134ddd99af198a7205e9514db3479a0c33
e569b326aeb7b6c8f848abdc6997ed81481da68f
/src/hw5/HW5.java
63f9b9ccd06ea1f5beee0781592d379eb9ca7a06
[]
no_license
MichaelDevries1/CS2
a58a433185f20f48d79b88c15019daea562ad92b
4decda3eec7ec6dddd7de31fdf20ef8557ad82b0
refs/heads/master
2021-04-25T20:49:05.013963
2017-12-02T22:55:53
2017-12-02T22:55:53
109,176,546
0
0
null
null
null
null
UTF-8
Java
false
false
6,758
java
package hw5; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; /* Program: Concordance of a text file Created by: Michael DeVries Created on: 10/2017 This program pulls in a text file and sorts the individual words counting how many times each word was used and removing the duplicates. It produces a file of the sorted words and how many times each word was used. */ public class HW5 { public static void main(String[] args) throws IOException { // Create output file PrintWriter output = new PrintWriter(new FileWriter("HW5.txt")); // Ask which file to use Scanner location = new Scanner (System.in); sop("What is the location and name of the file you wish to sort?"); // Create string of the file String fileLocation = location.next(); @SuppressWarnings ("resource") String fullBook = new Scanner (new FileReader(fileLocation)).useDelimiter("\\Z").next(); // Create Results buffer StringBuffer results = new StringBuffer("Filename: "); results.append(fileLocation + "\n"); // Remove all special characters and returns and make it all lower case fullBook = fullBook.replaceAll("[^a-zA-Z0-9'\\s]", ""); fullBook = fullBook.replaceAll("\\s+", " "); fullBook = fullBook.toLowerCase(); // Create ArrayList and Linked List List<WordCount> alConcord = new ArrayList<WordCount>(); LinkedList<WordCount> llConcord = new LinkedList<WordCount>(); // Create temporary lists List<String> word = new ArrayList<String> // Split book into individual words (Arrays.asList(fullBook.split(" "))); List<String> unique = new ArrayList<String>(); // Create a temporary list for unique words alConcord = checkWord(alConcord, word, unique); // Fill in and sort array list llConcord = checkWordLL(llConcord, word, unique); // Fill in and sort linked list results.append("Number of words: " + alConcord.size()); print(alConcord, results, output); // Prints HW5.txt and console location.close(); } // end main //========================================================================================================================================= public static List<WordCount> checkWord (List<WordCount> arr, List<String> word, List<String> unique) { // Creates the array list unique = collectSort(word, unique); // Finds unique words and sorts them Iterator<String> itr = unique.iterator(); // Create iterator for unique list while (itr.hasNext()) { // Add unique words and their counts to arr String move = itr.next(); // Step through unique list int freq = Collections.frequency(word, move); // Find number of times word was used in book WordCount temp = new WordCount(move, freq); // Add word and count to new instance of WordCount arr.add(temp); // Add the instance to arr } // end while return arr; // Return filled array list } // end checkWord //========================================================================================================================================= public static LinkedList<WordCount> checkWordLL (LinkedList<WordCount> list, List<String> word, List<String> unique) { // Creates the linked list unique = collectSort(word, unique); // Finds unique words and sorts them Iterator<String> itr = unique.iterator(); // Create iterator for unique list while (itr.hasNext()) { // Add unique words and their counts to list String move = itr.next(); // Step through unique list int freq = Collections.frequency(word, move); // Find number of times word was used in book WordCount temp = new WordCount(move, freq); // Add word and count to new instance of WordCount list.add(temp); // Add the instance to list } // end while return list; // Return filled linked list } // end checkWordLL //========================================================================================================================================= public static List<String> collectSort (List<String> word, List<String> unique) { Iterator<String> witr = word.iterator(); // Create iterator for word list while (witr.hasNext()) { // Find unique words String newWord = (String) witr.next(); // Step through word list if (!unique.contains(newWord)) { // Check if unique unique.add(newWord); // if unique add to arr } // end if } // end while Collections.sort(unique); // Sort unique list return unique; // Return sorted unique words } // end collectSort //========================================================================================================================================= public static void print (List<WordCount> arr, StringBuffer results, PrintWriter output) throws IOException { // Prints the results Iterator<WordCount> itr = arr.iterator(); // Create iterator for printing while (itr.hasNext()) { // Print to HW5.txt WordCount wc = itr.next(); // Step through the array list output.println(padString(wc.word, 20, "", " ") + wc.count); // Print current word and count } // end while sop(results); // Prints results on console } //========================================================================================================================================= public static String padString(String str, int width, String padLeft, String padRight) { // Create a pad to the left or right of a string for formating String strPad = str; // String to be returned int charsToPad; // The number of characters to pad // Using the length of the String str, calculate the number of characters // to pad on the left. Note the number could be <= 0 charsToPad = width - strPad.length(); // Pad str by spaces on the left and/or right so that the // resulting length of strPad is 'width' characters for (int i = 0; i < charsToPad; i++) { strPad = padLeft + strPad + padRight; } // End for return strPad; } // end padString //========================================================================================================================================= public static void sop (String s) { System.out.println(s); } // General print statements public static void sop (StringBuffer s ) {System.out.println(s); } } // end HW5
[ "Tu35%^dMpXhQWrA2!^F^9fxzP59CkHQ1q87@hPgN" ]
Tu35%^dMpXhQWrA2!^F^9fxzP59CkHQ1q87@hPgN
febe5aa42b595fa09a5080ee4bf5070430079ccc
de94265dd3bffaa5206d0b419d1d06f916f9d14c
/course2/four/src/controller/LoginActionServlet.java
81f51fcdd1bca06bbeceb1f54af37379abc57a9c
[ "MIT" ]
permissive
moe3000/things
25fedaf2edb89676c16f275ea4bff0fa5ab39883
da9810c1f438558ef22d406a783634da055b8a3c
refs/heads/master
2021-01-19T07:06:33.366356
2019-10-16T02:21:23
2019-10-16T02:21:23
87,521,402
0
0
null
null
null
null
UTF-8
Java
false
false
1,803
java
package controller; import model.UserBean; import utils.SysUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; @WebServlet("/login.do") public class LoginActionServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String account = req.getParameter("account"); String pwd = req.getParameter("pwd"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); String path = this.getServletContext().getRealPath("/")+ "user.txt"; File file = new File(path); List<UserBean> users = SysUtils.getAllUsers(file); for (UserBean user: users ) { if (!user.getAccount().equals(account)) { continue; } if (!user.getPwd().equals(pwd)) { out.println("密码错误"); } req.getSession().setAttribute("user", user); if ("学生".equals(user.getType())) { req.getRequestDispatcher(resp.encodeURL("/studentOperation.jsp")).forward(req, resp); } else { req.getRequestDispatcher(resp.encodeURL("/homework.html")).forward(req, resp); } return; } out.println("不存在的用户"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
[ "lyc1@erongdu.com" ]
lyc1@erongdu.com
10751200f9ae16f614cee2793f62badc19e7fc7a
846eec775e45e1f8a1148ad417eb082510fd6e4f
/src/Main/Java/tastysearch/Query.java
4c579c637cbfa359e9a8f779f5716359bb9770e8
[]
no_license
PrabhaSatya/TastySearch
b98a06605cf3f7bc022d0a7961d5c1dfda51b02d
3ac330c574e3650327e2f385b961f601a5032fbd
refs/heads/master
2020-04-11T05:57:55.199084
2016-09-19T06:36:00
2016-09-19T06:36:00
68,134,790
0
0
null
null
null
null
UTF-8
Java
false
false
3,810
java
package tastysearch; import java.util.*; /** * This class contains functions to find the topK reviews given a query and index of input dataset. */ class Query { ArrayList<Document> getTopKDocuments(List<List<Integer>> queryTokenDocumentLists, Map<Integer,Document> documents, Integer numQueryWords, Integer K){ Integer numQueryTokensInIndex = queryTokenDocumentLists.size(); Map<Integer,Integer> documentCounts = getDocumentCounts(queryTokenDocumentLists); Map<Integer,ArrayList<Integer>> countBuckets = getBuckets(documentCounts); ArrayList<Document> topKDocuments = new ArrayList<>(); for(Integer count = numQueryTokensInIndex; count >= 0; count--){ ArrayList<Integer> bucket = countBuckets.get(count); if(null != bucket){ ArrayList<Document> sortedBucket = sortBucketAsPerReviewScore(bucket,documents); Double matchScore = (1.0 * count)/numQueryWords; for(Document document: sortedBucket){ document.matchingScore = matchScore; topKDocuments.add(document); } if(topKDocuments.size() >= K){ break; } } } return topKDocuments; } private ArrayList<Document> sortBucketAsPerReviewScore(ArrayList<Integer> bucket, Map<Integer,Document> documents) { ArrayList<Document> sortedBucket = new ArrayList<>(); for (Integer documentId : bucket) { sortedBucket.add(documents.get(documentId)); } Collections.sort(sortedBucket,new ScoreCompartor()); return sortedBucket; } /* Returns a map containing the number of matches as key and a list of document ids with that particular number of matches as value */ private Map<Integer,ArrayList<Integer>> getBuckets(Map<Integer, Integer> documentCounts) { Map<Integer,ArrayList<Integer>> countBuckets = new HashMap<>(); for(Map.Entry<Integer,Integer> entry : documentCounts.entrySet()){ Integer documentId = entry.getKey(); Integer count = entry.getValue(); ArrayList<Integer> bucket = countBuckets.get(count); if(null == bucket){ bucket = new ArrayList<>(); countBuckets.put(count,bucket); } bucket.add(documentId); } return countBuckets; } /* Returns a map containing the document id as the key and the number of matches found in the documents value */ private Map<Integer,Integer> getDocumentCounts(List<List<Integer>> documentLists){ Map<Integer,Integer> documentCounts = new HashMap<>(); for (List<Integer> documentList : documentLists) { for (Integer documentId : documentList) { Integer count = documentCounts.get(documentId); if (null == count) { documentCounts.put(documentId, 1); } else { documentCounts.put(documentId, count + 1); } } } return documentCounts; } private class ScoreCompartor implements Comparator<Document>{ @Override public int compare(Document doc1, Document doc2) { if(Double.parseDouble(doc1.reviewScore) < Double.parseDouble(doc2.reviewScore)){ return 1; }else if (Double.parseDouble(doc1.reviewScore) > Double.parseDouble(doc2.reviewScore)){ return -1; }else{ return 0; } } } }
[ "satya.139@gmail.com" ]
satya.139@gmail.com
d639bbffe7ac50b13734aa0716aad8df533dcfb8
04f508d222e034fb3cda86e49db52de27876421c
/src/main/java/com/unibro/group/GroupService.java
f34e0b1ac48b2f2f0327c5b22b50a57f92ff7623
[]
no_license
thodt6/updoituong
ca20579b37f518cc80ec22b578938c90a71b40fd
b4f60292e36a82c0ef230920260d56218660ddce
refs/heads/master
2021-05-02T06:10:19.873348
2018-04-10T01:00:09
2018-04-10T01:00:09
120,853,093
0
0
null
null
null
null
UTF-8
Java
false
false
5,069
java
/* * 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.unibro.group; import com.unibro.utils.Global; import com.unibro.utils.RequestFilter; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import org.primefaces.event.RowEditEvent; /** * * @author THOND */ @SuppressWarnings("serial") @ManagedBean @ViewScoped public class GroupService { private List<Group> objects; private Group selectedObject; private Group newObject; private String selectedId; public void initSelectedObject() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.isPostback() && !facesContext.isValidationFailed()) { //Add code for init object here GroupDAO dao = new GroupDAO(); this.selectedObject = dao.getObjectByKey(selectedId); } } @PostConstruct public void init() { this.loadObjects(); } public final void loadObjects() { //Add code to load object here this.objects = Group.loadAllGroups(); } public void createObject() { if (this.getNewObject() != null) { GroupDAO dao = new GroupDAO(); Group result = dao.create(getNewObject()); if (result != null) { this.newObject = result; FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, Global.getResourceLanguage("general.operationSuccess"), ""); FacesContext.getCurrentInstance().addMessage(null, msg); } else { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, Global.getResourceLanguage("general.operationFail"), ""); FacesContext.getCurrentInstance().addMessage(null, msg); } } } public void editSelected() { if (this.selectedObject != null) { GroupDAO dao = new GroupDAO(); if (dao.edit(this.selectedObject) != null) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, Global.getResourceLanguage("general.operationSuccess"), ""); FacesContext.getCurrentInstance().addMessage(null, msg); } else { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, Global.getResourceLanguage("general.operationFail"), ""); FacesContext.getCurrentInstance().addMessage(null, msg); } } } public void deleteObject() { if (this.selectedObject != null) { GroupDAO dao = new GroupDAO(); dao.delete(selectedObject); this.loadObjects(); } } public void rowEdit(RowEditEvent event) { Group sf = (Group) event.getObject(); if (sf != null) { this.setSelectedObject(sf); this.editSelected(); } } public List<Group> completeObject(String query) { GroupDAO dao = new GroupDAO(); if (query == null || query.equals("")) { return dao.load(0, -1, "null", 0, new ArrayList()); } else { RequestFilter filter = new RequestFilter(); //replace name by the query field filter.setName("name"); filter.setType(RequestFilter.CONTAIN); filter.setValue(query); List filter_list = new ArrayList(); filter_list.add(filter); return dao.load(0, -1, "null", 0, filter_list); } } /** * @return the objects */ public List<Group> getObjects() { return objects; } /** * @param objects the objects to set */ public void setObjects(List<Group> objects) { this.objects = objects; } /** * @return the selectedObject */ public Group getSelectedObject() { return selectedObject; } /** * @param selectedObject the selectedObject to set */ public void setSelectedObject(Group selectedObject) { this.selectedObject = selectedObject; } /** * @return the newObject */ public Group getNewObject() { return newObject; } /** * @param newObject the newObject to set */ public void setNewObject(Group newObject) { this.newObject = newObject; } /** * @return the selectedId */ public String getSelectedId() { return selectedId; } /** * @param selectedId the selectedId to set */ public void setSelectedId(String selectedId) { this.selectedId = selectedId; } }
[ "THOND@192.168.1.15" ]
THOND@192.168.1.15
675237de964783c7da91e3ef8e33b0daadf3e3df
042bebd173184469c083739f128d0b8593aac3d7
/src/main/java/it/richkmeli/RMC/model/Device.java
2b4cbde7f7137d9ff0f5818197f9dedad7a84481
[ "Apache-2.0" ]
permissive
ldh0227/Richkware-Manager-Client
463432c5087c1f16d958ffc16da1faca9a6f4abb
a7301c4d4ce1e998916be826467d31039911a7e4
refs/heads/master
2020-05-27T21:07:21.623396
2019-05-26T17:40:04
2019-05-26T17:40:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,292
java
package it.richkmeli.RMC.model; public class Device { private String name; private String IP; private String serverPort; private String lastConnection; private String encryptionKey; public Device(String name, String iP, String serverPort, String lastConnection, String encryptionKey) { super(); this.name = name; IP = iP; this.serverPort = serverPort; this.lastConnection = lastConnection; this.encryptionKey = encryptionKey; } public String getIP() { return IP; } public String getLastConnection() { return lastConnection; } public String getServerPort() { return serverPort; } public String getName() { return name; } public String getEncryptionKey() { return encryptionKey; } public void setEncryptionKey(String encryptionKey) { this.encryptionKey = encryptionKey; } public void setServerPort(String serverPort) { this.serverPort = serverPort; } public void setIP(String iP) { IP = iP; } public void setLastConnection(String lastConnection) { this.lastConnection = lastConnection; } public void setName(String name) { this.name = name; } }
[ "richkmeli@gmail.com" ]
richkmeli@gmail.com
69221b808b5bd15a4dbc866b52c5018d422a3dbe
df04dfe964f9cf035717106205101e6f8e583ea7
/domain/OccupationStaus.java
4d70168ff3fecb38a3aabbe19cd4fc931314fe49
[]
no_license
nishantsinghcarnation/Cj-Project
88e2173cdd450584f543231af4c29b66503c7a3b
06fa9dd7f0d0760143ffb43d48abcdac717f1f68
refs/heads/master
2023-02-27T08:09:51.682092
2021-02-01T09:59:39
2021-02-01T09:59:39
334,212,362
0
0
null
null
null
null
UTF-8
Java
false
false
624
java
package com.cts.cj.domain; import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; @NodeEntity public class OccupationStaus { @Id @GeneratedValue private Long occupStatusId; private String occupationStatus; public Long getOccupStatusId() { return occupStatusId; } public void setOccupStatusId(Long occupStatusId) { this.occupStatusId = occupStatusId; } public String getOccupationStatus() { return occupationStatus; } public void setOccupationStatus(String occupationStatus) { this.occupationStatus = occupationStatus; } }
[ "you@example.com" ]
you@example.com
f483782eda6d15ace600387a43f1a0a2f47a3a20
f214ebeb43d78aa83cea312d3f8f4d7134b8d21c
/app/src/main/java/com/nlpproject/callrecorder/ORMLiteTools/model/BaseModel.java
8c93257aedcc3b3f1b0a289836cb339ba90ebe97
[]
no_license
PiotrekSotor/nlp_project
59000521df0d7509fa88b4241b82cb1f91fe21b8
97fe429c12f71c15681a73e1deb64d2afee7503c
refs/heads/master
2021-06-09T14:18:17.769048
2017-01-14T02:14:22
2017-01-14T02:14:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
513
java
package com.nlpproject.callrecorder.ORMLiteTools.model; import com.j256.ormlite.field.DatabaseField; import java.io.Serializable; /** * Created by Piotrek on 05.01.2017. */ public abstract class BaseModel implements Serializable, Comparable { @DatabaseField (generatedId = true) private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { return 101*id.hashCode(); } }
[ "piotrsotor@gmail.com" ]
piotrsotor@gmail.com
465c424c5470804304b33461b40fc1b57ff0ccb1
0ab89edc07e129ee95e5543a790cbf694ffa76ed
/sam-core/src/main/java/com/til/service/linkedin/api/OAuthRequest.java
1908a897ff1af5fc2ff382fd6d9ac33e5340f69e
[]
no_license
reshift-projects/socialaudiencemanager
6b8f561050827d5af4ba69aeebd490f70ca42d45
9cf2370589c490f768aa81eaf3ccfe4f8ca797aa
refs/heads/master
2020-06-19T07:09:12.242848
2019-04-14T10:39:14
2019-04-14T10:39:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,608
java
package com.til.service.linkedin.api; import java.util.HashMap; import java.util.Map; /** * The representation of an OAuth HttpRequest. * * Adds OAuth-related functionality to the {@link Request} * * @author Sanjay Gupta */ public class OAuthRequest extends Request { private static final String OAUTH_PREFIX = "oauth_"; private Map<String, String> oauthParameters; /** * Default constructor. * * @param verb Http verb/method * @param url resource URL */ public OAuthRequest(Verb verb, String url) { super(verb, url); this.oauthParameters = new HashMap<String, String>(); } /** * Adds an OAuth parameter. * * @param key name of the parameter * @param value value of the parameter * * @throws IllegalArgumentException if the parameter is not an OAuth parameter */ public void addOAuthParameter(String key, String value) { oauthParameters.put(checkKey(key), value); } private String checkKey(String key) { if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) { return key; } else { throw new IllegalArgumentException(String.format("OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX)); } } /** * Returns the {@link Map} containing the key-value pair of parameters. * * @return parameters as map */ public Map<String, String> getOauthParameters() { return oauthParameters; } @Override public String toString() { return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl()); } }
[ "harsh.gupta1@gmail.com" ]
harsh.gupta1@gmail.com
402dcf6764300dd010040614ce132ff8af338e15
92225460ebca1bb6a594d77b6559b3629b7a94fa
/src/com/kingdee/eas/fdc/market/IAppraise.java
a49019d35d88c4913e168b4bc75c486cf66ab63a
[]
no_license
yangfan0725/sd
45182d34575381be3bbdd55f3f68854a6900a362
39ebad6e2eb76286d551a9e21967f3f5dc4880da
refs/heads/master
2023-04-29T01:56:43.770005
2023-04-24T05:41:13
2023-04-24T05:41:13
512,073,641
0
1
null
null
null
null
UTF-8
Java
false
false
2,935
java
package com.kingdee.eas.fdc.market; import com.kingdee.bos.BOSException; //import com.kingdee.bos.metadata.*; import com.kingdee.bos.framework.*; import com.kingdee.bos.util.*; import com.kingdee.bos.Context; import java.lang.String; import com.kingdee.eas.fdc.basedata.IFDCDataBase; import com.kingdee.bos.metadata.entity.EntityViewInfo; import com.kingdee.eas.common.EASBizException; import com.kingdee.bos.dao.IObjectPK; import com.kingdee.bos.metadata.entity.SelectorItemCollection; import com.kingdee.bos.metadata.entity.SorterItemCollection; import com.kingdee.eas.framework.CoreBaseCollection; import com.kingdee.bos.util.*; import com.kingdee.bos.metadata.entity.FilterInfo; import com.kingdee.bos.BOSException; import com.kingdee.bos.Context; import com.kingdee.eas.framework.CoreBaseInfo; import com.kingdee.bos.framework.*; public interface IAppraise extends IFDCDataBase { public boolean exists(IObjectPK pk) throws BOSException, EASBizException; public boolean exists(FilterInfo filter) throws BOSException, EASBizException; public boolean exists(String oql) throws BOSException, EASBizException; public AppraiseInfo getAppraiseInfo(IObjectPK pk) throws BOSException, EASBizException; public AppraiseInfo getAppraiseInfo(IObjectPK pk, SelectorItemCollection selector) throws BOSException, EASBizException; public AppraiseInfo getAppraiseInfo(String oql) throws BOSException, EASBizException; public IObjectPK addnew(AppraiseInfo model) throws BOSException, EASBizException; public void addnew(IObjectPK pk, AppraiseInfo model) throws BOSException, EASBizException; public void update(IObjectPK pk, AppraiseInfo model) throws BOSException, EASBizException; public void updatePartial(AppraiseInfo model, SelectorItemCollection selector) throws BOSException, EASBizException; public void updateBigObject(IObjectPK pk, AppraiseInfo model) throws BOSException; public void delete(IObjectPK pk) throws BOSException, EASBizException; public IObjectPK[] getPKList() throws BOSException, EASBizException; public IObjectPK[] getPKList(String oql) throws BOSException, EASBizException; public IObjectPK[] getPKList(FilterInfo filter, SorterItemCollection sorter) throws BOSException, EASBizException; public AppraiseCollection getAppraiseCollection() throws BOSException; public AppraiseCollection getAppraiseCollection(EntityViewInfo view) throws BOSException; public AppraiseCollection getAppraiseCollection(String oql) throws BOSException; public IObjectPK[] delete(FilterInfo filter) throws BOSException, EASBizException; public IObjectPK[] delete(String oql) throws BOSException, EASBizException; public void delete(IObjectPK[] arrayPK) throws BOSException, EASBizException; public boolean enabled(IObjectPK ctPK) throws BOSException, EASBizException; public boolean disEnabled(IObjectPK ctPK) throws BOSException, EASBizException; }
[ "yfsmile@qq.com" ]
yfsmile@qq.com
8e5094583381cd14960b7424f5c7564258924e45
878fc13b3358c11fcb05a375c819da4777d31755
/OriaLibs/gen/com/lib/play_rec/BuildConfig.java
9e51e7fdff9053d228054e10d80dc2261cf72730
[]
no_license
wuyong0087/TongZhenMooc
62bf103c94724a4e01ebc475b7bc2d6d4fbddd44
524a5d0e42beea6a8f13ce614d553b2c4e1ab44c
refs/heads/master
2020-06-21T04:15:41.496302
2016-12-30T07:13:16
2016-12-30T07:13:16
74,807,574
0
0
null
null
null
null
UTF-8
Java
false
false
158
java
/** Automatically generated file. DO NOT MODIFY */ package com.lib.play_rec; public final class BuildConfig { public final static boolean DEBUG = true; }
[ "wuyong0087@163.com" ]
wuyong0087@163.com
42f98ca20b8cba0e39335491d83401ef3e35f2e7
dfdffa2c82ef37aa5ba5614ccf8846b00555a756
/epamProjecttraining/src/main/java/com/epam/java8/ResponsesJSONAnd400_Q8.java
12a307c9e69517ffdac6962bcf5ad7551033f8ef
[]
no_license
SabariGanesh1987/OnboardingExercises
82a96fd4cc50e8512b0c18afebb71376d447e9e4
38eeaddc849df5fefe2aca001c880c5d9ce071b6
refs/heads/master
2023-04-06T02:46:25.411590
2021-05-03T04:27:44
2021-05-03T04:27:44
362,687,863
0
0
null
null
null
null
UTF-8
Java
false
false
416
java
package com.epam.java8; import java.util.List; import java.util.stream.Collectors; public class ResponsesJSONAnd400_Q8 extends ResponseList { public static void main(String[] args) { List<Response> responses = getResponseList().stream() .filter(a -> a.getResponsetype().equalsIgnoreCase("json")&&a.getStatusCode()==400) .collect(Collectors.toList()); System.out.println(responses.toString()); } }
[ "ganesh_kollepara@epam.com" ]
ganesh_kollepara@epam.com
17b49ea19471e9c1a1e3614d458ad5d095659e7b
778f3372d7db8508414a5ff021c40e6f402700b2
/springcloud-gateway/src/main/java/com/hgsoft/springcloud/gateway/filter/UriKeyResolver.java
137fcd7cd1add7f5a26327c15332d900bb3b9e45
[]
no_license
charlesvaez/Microservice
049cb38fab48d7a5c52ea83be33807a9089834cd
d7ef4f461e6a1423aef3a10b6c531a1fd876fbf0
refs/heads/master
2022-06-29T11:11:40.132488
2020-02-24T11:57:36
2020-02-24T11:57:36
181,639,308
0
1
null
null
null
null
UTF-8
Java
false
false
760
java
package com.hgsoft.springcloud.gateway.filter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; public class UriKeyResolver implements KeyResolver { private final Logger logger = LoggerFactory.getLogger(UriKeyResolver.class); @Override public Mono<String> resolve(ServerWebExchange exchange) { ServerHttpRequest serverHttpRequest = exchange.getRequest(); String path = serverHttpRequest.getURI().getPath(); logger.info("path > {}",path); return Mono.just(path); } }
[ "839019311@qq.com" ]
839019311@qq.com
095862eb0b94df6c37647052bba3af79d1133dc0
5f96f3d19a2b77850d3dbec0a1caa1de92bd4f5a
/app/src/main/java/com/caidong/wechat/util/TimerUtils.java
2ea371669e683385211b33597bac350ced1069be
[]
no_license
xiaoyaomimi/wechat
20a57ff134c6e2b8594e0da784099dd940584ec8
61c7fd617d412bee661d20c771086070cd273aba
refs/heads/master
2020-03-23T07:41:52.326831
2018-07-17T12:45:19
2018-07-17T12:45:19
141,286,333
0
0
null
null
null
null
UTF-8
Java
false
false
680
java
package com.caidong.wechat.util; import android.annotation.SuppressLint; import com.caidong.wechat.util.interfaces.OnTimerResultListener; import java.util.concurrent.TimeUnit; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; public class TimerUtils { @SuppressLint("CheckResult") public static void timerTranslation(OnTimerResultListener onTimerResultListener) { Single.timer(1000, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()).subscribe(aLong -> { if (onTimerResultListener != null) { onTimerResultListener.onTimerResult(); } }); } }
[ "mircaidong@163.com" ]
mircaidong@163.com
efaa1a3f483eff29fbbe5aa6c7bb7b24c811db39
71397b86f472c8f78c1ade7d2eca60bab025d49b
/src/main/java/br/com/alpi/financeiro/service/NegocioException.java
c5ba44910b8ff8dc23d4b10dc45325a4402f0fec
[]
no_license
alanpontoinfo/JAVAEE7-JFS-CDI-PRIMEFACES
a432d7926d0c05a53c64c9fcacd14763e148a26a
e226094435ba6f48a9c700dbaaa57920e73c1a82
refs/heads/master
2020-03-22T13:58:22.142994
2018-07-08T07:02:00
2018-07-08T07:02:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
193
java
package br.com.alpi.financeiro.service; public class NegocioException extends Exception { private static final long serialVersionUID = 1L; public NegocioException(String msg) { super(msg); } }
[ "alanpontoinfo@gmail.com" ]
alanpontoinfo@gmail.com
818a00dea8d06b647c35f1e65d0cfd54334897c8
09612e91a82faf984568d7e8c6c48089699575b2
/hw0-bom/src/main/java/DependencyExample.java
435feb3c7b80646e3756241675a2666765692f89
[]
no_license
mabodx/hw0-bom
3325ede6f276b1e4529eef90a3e717ec04a34fe6
52312f5a02bc177afc62586488591d1459885747
refs/heads/master
2021-03-12T23:19:11.411537
2013-09-04T00:25:32
2013-09-04T00:25:32
12,564,411
0
1
null
2020-02-11T06:18:26
2013-09-03T13:25:47
null
UTF-8
Java
false
false
790
java
import java.io.StringReader; import edu.stanford.nlp.ling.Word; import edu.stanford.nlp.objectbank.TokenizerFactory; import edu.stanford.nlp.process.PTBTokenizer.PTBTokenizerFactory; import edu.stanford.nlp.process.Tokenizer; /** * An example for Homework 0 of 11791 F13 * * @author bom <bom@andrew.cmu.edu> */ public class DependencyExample { /** * Tokenize a sentence in the argument, and print out * the tokens to the console. * * @param args Set the first argument as the sentence to * be tokenized. * */ public static void main(String[] args) { TokenizerFactory<Word> factory = PTBTokenizerFactory.newTokenizerFactory(); Tokenizer<Word> tokenizer = factory.getTokenizer(new StringReader(args[0])); System.out.println(tokenizer.tokenize()); } }
[ "mabodx@mabodx-Lenovo-IdeaPad-V450" ]
mabodx@mabodx-Lenovo-IdeaPad-V450
223845fa12f454a543ff787cfed78c26723c40ac
9384cf0f26835ec06c142c48af52947cf18d079b
/Core/src/main/java/net/devcowsoftware/networkcore/core/core/spigot/module/ModuleLoader.java
d58c28bfa9b0c6dd5d6a0157696412c51eb90572
[]
no_license
DevCowMC/NetworkCore.ModuleSystem
c561465d00fd48fde1663eed6300e2d947e32fa6
d9f5d570a9760d1cf3a3181c31225d3b4b3e9dd1
refs/heads/master
2023-08-11T08:22:12.064507
2021-10-08T03:35:20
2021-10-08T03:35:20
414,835,115
2
0
null
null
null
null
UTF-8
Java
false
false
4,396
java
package net.devcowsoftware.networkcore.core.core.spigot.module; import lombok.Getter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @Getter public class ModuleLoader { @Getter private static ModuleLoader coreInstance; private Yaml yaml = new Yaml(); private String path; private Map<String, Module> toLoad = new HashMap<>(); private List<Module> loadedModules = new ArrayList<>(); /** * * Create constructor to load modules by path * * @param path Path for the modules */ public ModuleLoader( String path ) { long l = System.currentTimeMillis(); coreInstance = this; this.path = path; new File( path ).mkdirs(); loadModulesFromFolder(); while ( !toLoad.isEmpty() ) { List<Module> toRemove = new ArrayList<>(); for ( Module module : toLoad.values() ) { for ( String s : module.getDependencies() ) { if ( toLoad.containsKey( s ) ) continue; } module.onEnable(); loadedModules.add( module ); toRemove.add( module ); } for ( Module module : toRemove ) { toLoad.remove( module.getName() ); } } System.out.println( "loaded " + loadedModules.size() + " modules in " + ( System.currentTimeMillis() - l ) + "ms" ); } /** * Load all modules form constructor's given folder */ private void loadModulesFromFolder() { for ( File file : Objects.requireNonNull( new File( path ).listFiles() ) ) { if ( file.getName().endsWith( ".jar" ) ) { try { ZipFile javaFile = new ZipFile( file ); ZipEntry entry = javaFile.getEntry( "Spigot-Module.yml" ); FileConfiguration config = YamlConfiguration.loadConfiguration( new InputStreamReader( javaFile.getInputStream( entry ) ) ); String main = config.getString( "main" ); Module module = loadIntoRuntime( file, main ); module.setName( config.getString( "name" ) ); module.setAuthor( config.getString( "author" ) ); module.setVersion( config.getDouble( "version" ) ); module.setDependencies( config.getStringList( "dependencies" ).toArray( new String[ 0 ] ) ); module.setFile( file.getParentFile() ); module.setMain( main ); module.onLoad(); module.setupConfig(); toLoad.put( module.getName(), module ); javaFile.close(); } catch ( IOException | IllegalAccessException | ClassNotFoundException | InstantiationException | NoSuchMethodException | InvocationTargetException e ) { e.printStackTrace(); } } } } /** * * Load module into runtime of the core * * @param file the modules path (file) * @param mainClass the URI of the main class * @return Module * @throws NoSuchMethodException * @throws MalformedURLException * @throws ClassNotFoundException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException */ private Module loadIntoRuntime( File file, String mainClass ) throws NoSuchMethodException, MalformedURLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException { ClassLoader loader = URLClassLoader.newInstance( new URL[] { file.toURL() }, getClass().getClassLoader() ); Class<?> clazz = Class.forName(mainClass, true, loader); Constructor<?> constructor = clazz.getConstructor(); return (Module) constructor.newInstance(); } }
[ "kieranhouse19@gmail.com" ]
kieranhouse19@gmail.com
ab406fe0c379f1f9a177b3efc0cec7863f88f5fe
bf93ca7d3f5d7acfe2b349f956f4a367645f0af8
/src/main/java/com/kaixin8848/home/utility/sms/request/SmsBalanceRequest.java
d99662fcf701c7aff1ff9dc5c6b5b8e739e7b891
[]
no_license
tmy110/kaixinhome-api
3db918755775f2cfa36b511c0f2fc7298e9558fa
b041b60090d644faa3acd73b12c62048ed739929
refs/heads/master
2022-07-28T00:26:36.426044
2020-03-14T09:50:51
2020-03-14T09:50:51
247,201,097
0
0
null
2022-06-29T18:01:00
2020-03-14T02:58:11
Java
UTF-8
Java
false
false
803
java
package com.kaixin8848.home.utility.sms.request; /** * @author tianyh * @Description:查询账号余额实体类 */ public class SmsBalanceRequest { /** * 创蓝API账号,必填 */ private String account; /** * 创蓝API密码,必填 */ private String password; public SmsBalanceRequest() { } public SmsBalanceRequest(String account, String password) { super(); this.account = account; this.password = password; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
[ "“18361036456@163.com”" ]
“18361036456@163.com”
e2184021f73b910ea059acefd9c1dd69808a1159
5e1870af0822cbfb39fd215fb4a565deb7b89b90
/src/main/java/de/malkusch/whoisServerList/compiler/filter/ListFilter.java
b9a96eca9bacf69d45b0372790aaaddd7c310f39
[ "WTFPL" ]
permissive
wendelas/whois-server-list-maven-plugin
679c48f40b278ef2233d70160d2053aa48e57d01
ae4a8725fd7712f8660e1e7a9c2445258913a231
refs/heads/master
2021-01-15T20:32:55.294081
2016-03-24T21:50:15
2016-03-24T21:50:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,070
java
package de.malkusch.whoisServerList.compiler.filter; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * Filters each item of a list. * * @author markus@malkusch.de * @param <T> the list item type * @see <a href="bitcoin:1335STSwu9hST4vcMRppEPgENMHD2r1REK">Donations</a> */ @Immutable final class ListFilter<T> extends AbstractListFilter<T> { /** * Sets the item filter. * * @param filter the item filter */ ListFilter(final Filter<T> filter) { super(filter); } @Override @Nullable public List<T> filter(@Nullable final List<T> list) throws InterruptedException { if (list == null) { return null; } List<T> filteredList = new ArrayList<>(); for (T item : list) { T filteredItem = filterItem(item); if (filteredItem != null) { filteredList.add(filteredItem); } } return filteredList; } }
[ "markus@malkusch.de" ]
markus@malkusch.de
c093d89aeb3b24ad56ae4cf741aead3463c956a0
1fffaeedde153130f6939c237292ab61a3508bec
/librecord/src/main/java/jp/co/cyberagent/android/gpuimage/filter/base/GPUImageDissolveBlendFilter.java
3d6f79ee091e75de02b092fde81480e7595836fd
[]
no_license
AipingLei/VideoRecorder
c52ea1d6ec786babd9942d25dc893a0e1c86ca0d
63a3a497f3cfb8ca90ba99f590be437dee741876
refs/heads/master
2021-01-19T09:03:20.123833
2017-05-27T09:02:19
2017-05-27T09:02:19
87,717,746
4
0
null
null
null
null
UTF-8
Java
false
false
1,797
java
/* * Copyright (C) 2012 CyberAgent * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.cyberagent.android.gpuimage.filter.base; /** * Mix ranges from 0.0 (only image 1) to 1.0 (only image 2), with 0.5 (half of either) as the normal level */ public class GPUImageDissolveBlendFilter extends GPUImageMixBlendFilter{ public static final String DISSOLVE_BLEND_FRAGMENT_SHADER = "varying highp vec2 textureCoordinate;\n" + " varying highp vec2 textureCoordinate2;\n" + "\n" + " uniform sampler2D inputImageTexture;\n" + " uniform sampler2D inputImageTexture2;\n" + " uniform lowp float mixturePercent;\n" + " \n" + " void main()\n" + " {\n" + " lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\n" + " lowp vec4 textureColor2 = texture2D(inputImageTexture2, textureCoordinate2);\n" + " \n" + " gl_FragColor = mix(textureColor, textureColor2, mixturePercent);\n" + " }"; public GPUImageDissolveBlendFilter() { super(DISSOLVE_BLEND_FRAGMENT_SHADER); } public GPUImageDissolveBlendFilter(float mix) { super(DISSOLVE_BLEND_FRAGMENT_SHADER, mix); } }
[ "leiap@codoon.com" ]
leiap@codoon.com
51c42aef7fb7273f26be5295bfdb7879de515411
eb28bc08dcd56875bd5cc67b85922ef8330b010a
/src/main/java/com/stephen/learning/thread/PhaserUse.java
107fcb37c4eeaac7ad283e2420645d47b4e7e2d5
[]
no_license
doraemon4/goodProgramming
4e1bc6791a54ef30840bed2c60648cf486e5153f
a201b1c04a7ccf0f5cad561c10c3169052eca9f7
refs/heads/master
2022-11-25T02:24:06.979458
2019-06-20T09:55:39
2019-06-20T09:55:39
146,319,577
0
0
null
2022-11-16T10:50:57
2018-08-27T15:47:46
Java
UTF-8
Java
false
false
2,268
java
package com.stephen.learning.thread; import java.util.concurrent.Phaser; /** * @author: jack * @Date: 2019/6/20 16:21 * @Description: 阶段器使用 */ public class PhaserUse { static class MyPhaser extends Phaser { private int phaseToTerminate = 2; @Override protected boolean onAdvance(int phase, int registeredParties) { System.out.println("*第" + phase + "阶段完成*"); //到达结束阶段,或者还没到结束阶段但是party为0,都返回true,结束phaser return phase == phaseToTerminate || registeredParties == 0; } } static class Swimmer implements Runnable{ private Phaser phaser; public Swimmer(Phaser phaser) { this.phaser = phaser; } @Override public void run() { //从这里到第一个phaser.arriveAndAwaitAdvance()是第一阶段做的事 System.out.println("游泳选手-"+Thread.currentThread().getName()+":已到达赛场"); phaser.arriveAndAwaitAdvance(); //从这里到第二个phaser.arriveAndAwaitAdvance()是第二阶段做的事 System.out.println("游泳选手-"+Thread.currentThread().getName()+":已准备好"); phaser.arriveAndAwaitAdvance(); //从这里到第三个phaser.arriveAndAwaitAdvance()是第三阶段做的事 System.out.println("游泳选手-"+Thread.currentThread().getName()+":完成比赛"); phaser.arriveAndAwaitAdvance(); } } public static void main(String[] args) { int swimmerNum = 6; MyPhaser phaser = new MyPhaser(); //注册主线程,用于控制phaser何时开始第二阶段 phaser.register(); for(int i=0; i<swimmerNum; i++) { phaser.register(); new Thread(new Swimmer(phaser),"swimmer"+i).start(); } //主线程到达第一阶段并且不参与后续阶段.其它线程从此时可以进入后面的阶段. phaser.arriveAndDeregister(); //加while是为了防止其它线程没结束就打印了"比赛结束” while (!phaser.isTerminated()) { } System.out.println("===== 比赛结束 ====="); } }
[ "zhangkun@51dojo.com" ]
zhangkun@51dojo.com
cf5279d7691a54500edbc99ac5ec84af7211c7d8
60e96e7e1f5359b3228e2325565b05f58e610d17
/GraphEditor_V11/src/br/com/upf/view/internalframe/StateEditor.java
8d58353bd26249686fb47e43f8e136adb49b7810
[]
no_license
GiordaniCe/MPDOUG
c70510b4fc9334ec9bde47970a9e61b108bb8a28
bb489af22c5b54a6077dfc78f93aeec5bf19fc3a
refs/heads/master
2021-01-23T21:34:30.814079
2015-01-13T23:11:25
2015-01-13T23:11:25
29,213,374
1
0
null
null
null
null
UTF-8
Java
false
false
34,677
java
/* * 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 graphEditor. */ package br.com.upf.view.internalframe; import br.com.upf.beans.BasicState; import br.com.upf.beans.ClassElement; import br.com.upf.beans.ClassModel; import br.com.upf.beans.DiagramOfStateModel; import br.com.upf.beans.StandartExpression; import br.com.upf.beans.FinalState; import br.com.upf.beans.InitialState; import br.com.upf.beans.State; import br.com.upf.beans.Transition; import br.com.upf.jgraph.custom.StateGraph; import br.com.upf.jgraph.custom.StateGraphComponent; import br.com.upf.view.EditorKeyboardHandler; import br.com.upf.view.GraphEditor; import br.com.upf.view.StateEditorPopupMenu; import br.com.upf.view.StateEditorToolBar; import br.com.upf.view.StatePalette; import com.mxgraph.model.mxCell; import com.mxgraph.swing.handler.mxKeyboardHandler; import com.mxgraph.swing.handler.mxRubberband; import com.mxgraph.util.mxEvent; import com.mxgraph.util.mxEventObject; import com.mxgraph.util.mxEventSource; import com.mxgraph.util.mxRectangle; import com.mxgraph.util.mxResources; import com.mxgraph.util.mxUndoManager; import com.mxgraph.util.mxUndoableEdit; import com.mxgraph.view.mxGraphSelectionModel; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Objects; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JToolBar; import static javax.swing.SwingConstants.CENTER; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; /** * * @author GiordaniAntonio */ public class StateEditor extends javax.swing.JInternalFrame { private static final long serialVersionUID = 6181123989323951836L; /** * */ public static final String IMAGE_PATH = "/br/com/upf/images/"; /** * */ private StateGraphComponent stateGraphComponent; /** * */ private StateGraph stateGraph; /** * */ private ClassElement classElement; /** * */ private ClassModel classModel; /** * */ private DiagramOfStateModel diagramOfStateModel; /** * */ private StatePalette palette; /** * */ private StateEditorToolBar toolBar; /** * */ private StateEditorPopupMenu popupMenu; /** * */ private ArrayList<StandartExpression> arrayListExpressions; /** * */ private GraphEditor graphEditor; /** * * Sinalizador indicando se o gráfico atual foi modificado */ private boolean modified = false; /** * */ private mxUndoManager undoManager; /** * */ protected mxRubberband rubberband; /** * */ protected mxKeyboardHandler keyboardHandler; /** * Histórico de comandos */ protected mxEventSource.mxIEventListener undoHandler = new mxEventSource.mxIEventListener() { @Override public void invoke(Object source, mxEventObject evt) { getUndoManager().undoableEditHappened((mxUndoableEdit) evt .getProperty("edit")); } }; /** * */ protected mxEventSource.mxIEventListener changeTracker = new mxEventSource.mxIEventListener() { @Override public void invoke(Object source, mxEventObject evt) { setModified(true); } }; /** * Creates new form DiagramaDeClassModels * * @param editor * @param element */ public StateEditor(GraphEditor editor, ClassElement element) { super("Diagrama de Estados"); initComponents(); this.graphEditor = editor; this.classElement = element; this.classModel = classElement.getClassModel(); this.diagramOfStateModel = classModel.getDiagramOfStateModel(); stateGraph = new StateGraph(diagramOfStateModel); stateGraphComponent = new StateGraphComponent(graphEditor, stateGraph, diagramOfStateModel); stateGraph.setStateGraphComponent(stateGraphComponent); createUndoManager(); stateGraph.setResetViewOnRootChange(false); stateGraph.getModel().addListener(mxEvent.CHANGE, changeTracker); stateGraph.getModel().addListener(mxEvent.UNDO, undoHandler); stateGraph.getView().addListener(mxEvent.UNDO, undoHandler); mxEventSource.mxIEventListener undoHandler = new mxEventSource.mxIEventListener() { @Override public void invoke(Object source, mxEventObject evt) { List<mxUndoableEdit.mxUndoableChange> changes = ((mxUndoableEdit) evt .getProperty("edit")).getChanges(); stateGraph.setSelectionCells(stateGraph .getSelectionCellsForChanges(changes)); } }; undoManager.addListener(mxEvent.UNDO, undoHandler); undoManager.addListener(mxEvent.REDO, undoHandler); installGraphComponent(); installPalette(); installToolBar(); installRepaintListener(); installHandlers(); installListeners(); installSelectListener(); setAlignColumnJTable(); } /** * Configuração -Define o alinhamento do conteudo de células da tabela */ private void setAlignColumnJTable() { TableColumn column; TableCellRenderer tcr = new AlinharCentro(); for (int i = 0; i < jTableExpressions.getColumnCount(); i++) { column = jTableExpressions.getColumnModel().getColumn(i); column.setCellRenderer(tcr); } } private void installGraphComponent() { jPanelContent.add(BorderLayout.CENTER, stateGraphComponent); } private void installPalette() { palette = new StatePalette(); addItemsPalette(); jPanelPalette.add(BorderLayout.CENTER, palette); } private void installToolBar() { toolBar = new StateEditorToolBar(this, JToolBar.HORIZONTAL); jPanelNorth.add(BorderLayout.CENTER, toolBar); } private void addItemsPalette() { palette .addTemplate( "Inicial", new ImageIcon( StateEditor.class .getResource(IMAGE_PATH + "inicial.png")), "inicial", 30, 30, new InitialState("Estado Inicial")); palette .addTemplate( "Estado", new ImageIcon( StateEditor.class .getResource(IMAGE_PATH + "rounded.png")), "rounded=1", 100, 60, new State()); palette .addTemplate( "Final", new ImageIcon( StateEditor.class .getResource(IMAGE_PATH + "final.png")), "final;shape=doubleEllipse", 30, 30, new FinalState("Estado Final")); } private void createUndoManager() { undoManager = new mxUndoManager(); } private void installHandlers() { rubberband = new mxRubberband(stateGraphComponent); keyboardHandler = new EditorKeyboardHandler(stateGraphComponent); } private void installRepaintListener() { stateGraphComponent.getGraph().addListener(mxEvent.REPAINT, new mxEventSource.mxIEventListener() { @Override public void invoke(Object source, mxEventObject evt) { String buffer = (stateGraphComponent.getTripleBuffer() != null) ? "" : " (unbuffered)"; mxRectangle dirty = (mxRectangle) evt .getProperty("region"); if (dirty == null) { status("Repaint all" + buffer); } else { status("Repaint: x=" + (int) (dirty.getX()) + " y=" + (int) (dirty.getY()) + " w=" + (int) (dirty.getWidth()) + " h=" + (int) (dirty.getHeight()) + buffer); } } }); } protected void mouseWheelMoved(MouseWheelEvent e) { if (e.getWheelRotation() < 0) { stateGraphComponent.zoomIn(); } else { stateGraphComponent.zoomOut(); } status(mxResources.get("scale") + ": " + (int) (100 * stateGraphComponent.getGraph().getView().getScale()) + "%"); } protected void showGraphPopupMenu(MouseEvent e) { Point pt = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), stateGraphComponent); popupMenu = new StateEditorPopupMenu(StateEditor.this); popupMenu.show(stateGraphComponent, pt.x, pt.y); e.consume(); } protected void mouseLocationChanged(MouseEvent e) { status(e.getX() + ", " + e.getY()); } private void installSelectListener() { stateGraphComponent.getGraph().getSelectionModel().addListener(mxEvent.CHANGE, new mxEventSource.mxIEventListener() { @Override public void invoke(Object sender, mxEventObject evt) { if (sender instanceof mxGraphSelectionModel) { mxGraphSelectionModel sm = (mxGraphSelectionModel) sender; Object selecao[] = sm.getCells(); if (selecao != null) { if (selecao.length == 1) { mxCell cell = (mxCell) sm.getCell(); // Ativa painel de propriedades displayJPanelProperties(true); // Vértice if (cell.isVertex()) { if (cell.getValue() instanceof BasicState) { BasicState basicState = (BasicState) cell.getValue(); displayJPanelBase(true); if (cell.getValue() instanceof State) { State state = (State) basicState; displayState(state); } else { if (cell.getValue() instanceof InitialState) { InitialState initialState = (InitialState) basicState; displayInitialState(initialState); } else { if (cell.getValue() instanceof FinalState) { FinalState finalState = (FinalState) basicState; displayFinalState(finalState); } } } } else { // Não é instância de BasicState } }// Aresta else { if ((cell.getSource() != null) && (cell.getTarget() != null)) { if (cell.getValue() instanceof Transition) { Transition transition = (Transition) cell.getValue(); displayTransition(transition); } else { // Não é instância de Transition } } else { //Aresta não esta completamente conectada } } } else { displayJPanelProperties(false); } } else { displayJPanelProperties(false); } } } }); } public void loadAttributes(ArrayList<StandartExpression> expressions) { listExpressions.clear(); listExpressions.addAll(expressions); } private void displayJPanelProperties(Boolean selected) { CardLayout painel = (CardLayout) jPanelProperties.getLayout(); if (selected) { painel.show(jPanelProperties, "card2"); } else { painel.show(jPanelProperties, "card1"); } } private void displayJPanelBase(Boolean state) { CardLayout painel = (CardLayout) jPanelBase.getLayout(); if (state) { painel.show(jPanelBase, "card1"); } else { painel.show(jPanelBase, "card2"); } } private void displayjTabbedPaneProperties(Boolean state) { if (state) { jTabbedPaneProperties.setEnabledAt(0, true); jTabbedPaneProperties.setEnabledAt(1, true); jTabbedPaneProperties.setSelectedIndex(1); } else { jTabbedPaneProperties.setEnabledAt(0, true); jTabbedPaneProperties.setEnabledAt(1, false); jTabbedPaneProperties.setSelectedIndex(0); } } private void displayTransition(Transition t) { displayJPanelBase(false); displayjTabbedPaneProperties(false); jTextFieldConnectionName.setText(t.getName()); jTextFieldConnectionSource.setText(t.getSource().getName()); jTextFieldConnectionTarget.setText(t.getTarget().getName()); } private void displayState(State s) { displayjTabbedPaneProperties(true); loadAttributes(s.getStandartExpressions()); jTextFieldStateName.setText(s.getName()); } private void displayInitialState(InitialState is) { displayjTabbedPaneProperties(false); jTextFieldStateName.setText(is.getName()); } private void displayFinalState(FinalState fs) { displayjTabbedPaneProperties(false); jTextFieldStateName.setText(fs.getName()); } public void status(String msg) { jLabelStatusInformation.setText(msg); } public void updateTitle() { this.setTitle("Diagrama de Estados - " + classModel.getName()); } private void installListeners() { // Instala o popup menu no componente "gráfico" graph stateGraphComponent.getGraphControl().addMouseListener(new MouseAdapter() { /** * */ @Override public void mousePressed(MouseEvent e) { // Alças menu de contexto no Mac, onde o gatilho está na mousePressed mouseReleased(e); } /** * */ @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showGraphPopupMenu(e); } } }); // Instala um ouvinte de movimento do mouse para exibir a localização do mouse stateGraphComponent.getGraphControl().addMouseMotionListener( new MouseMotionListener() { /* * (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent) */ public void mouseDragged(MouseEvent e) { mouseLocationChanged(e); } /* * (non-Javadoc) * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent) */ public void mouseMoved(MouseEvent e) { mouseDragged(e); } }); } /** * Classe Interna - Utilizada no alinhamento do conteudo das colunas da * Tabela */ class AlinharCentro extends DefaultTableCellRenderer { public AlinharCentro() { setHorizontalAlignment(CENTER); // ou LEFT, RIGHT, etc } } public Action bind(String name, final Action action) { return bind(name, action, null); } public Action bind(String name, final Action action, String iconUrl) { AbstractAction newAction = new AbstractAction(name, (iconUrl != null) ? new ImageIcon( StateEditor.class.getResource(iconUrl)) : null) { @Override public void actionPerformed(ActionEvent e) { action.actionPerformed(new ActionEvent(getStateGraphComponent(), e .getID(), e.getActionCommand())); } }; newAction.putValue(Action.SHORT_DESCRIPTION, action.getValue(Action.SHORT_DESCRIPTION)); return newAction; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); listExpressions = new LinkedList<br.com.upf.beans.StandartExpression>(); jPanelPrincipal = new javax.swing.JPanel(); jPanelNorth = new javax.swing.JPanel(); jPanelCenter = new javax.swing.JPanel(); jSplitPaneCenter = new javax.swing.JSplitPane(); jPanelWest = new javax.swing.JPanel(); jSplitPaneWest = new javax.swing.JSplitPane(); jPanelPalette = new javax.swing.JPanel(); jPanelProperties = new javax.swing.JPanel(); jPanelEmpty = new javax.swing.JPanel(); jLabelNoSelect = new javax.swing.JLabel(); jPanelFull = new javax.swing.JPanel(); jTabbedPaneProperties = new javax.swing.JTabbedPane(); jPanelBase = new javax.swing.JPanel(); jPanelBaseState = new javax.swing.JPanel(); jLabelStateName = new javax.swing.JLabel(); jTextFieldStateName = new javax.swing.JTextField(); jPanelBaseConnection = new javax.swing.JPanel(); jLabelConnectionName = new javax.swing.JLabel(); jTextFieldConnectionName = new javax.swing.JTextField(); jLabelConnectionSource = new javax.swing.JLabel(); jTextFieldConnectionSource = new javax.swing.JTextField(); jLabelConnectionTarget = new javax.swing.JLabel(); jTextFieldConnectionTarget = new javax.swing.JTextField(); jPanelExpressions = new javax.swing.JPanel(); jScrollPaneExpressions = new javax.swing.JScrollPane(); jTableExpressions = new javax.swing.JTable(); jPanelContent = new javax.swing.JPanel(); jPanelSouth = new javax.swing.JPanel(); jLabelStatusInformation = new javax.swing.JLabel(); listExpressions = org.jdesktop.observablecollections.ObservableCollections.observableList(listExpressions); setMaximizable(true); setPreferredSize(new java.awt.Dimension(410, 294)); setRequestFocusEnabled(false); setVisible(true); jPanelPrincipal.setLayout(new java.awt.BorderLayout()); jPanelNorth.setPreferredSize(new java.awt.Dimension(484, 25)); jPanelNorth.setLayout(new java.awt.BorderLayout()); jPanelPrincipal.add(jPanelNorth, java.awt.BorderLayout.PAGE_START); jPanelCenter.setLayout(new java.awt.BorderLayout()); jSplitPaneCenter.setDividerLocation(250); jSplitPaneCenter.setDividerSize(7); jSplitPaneCenter.setResizeWeight(0.1); jPanelWest.setPreferredSize(new java.awt.Dimension(150, 318)); jPanelWest.setLayout(new java.awt.BorderLayout()); jSplitPaneWest.setDividerLocation(80); jSplitPaneWest.setDividerSize(7); jSplitPaneWest.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPaneWest.setOneTouchExpandable(true); jPanelPalette.setLayout(new java.awt.BorderLayout()); jSplitPaneWest.setTopComponent(jPanelPalette); jPanelProperties.setLayout(new java.awt.CardLayout()); jPanelEmpty.setLayout(new java.awt.BorderLayout()); jLabelNoSelect.setForeground(new java.awt.Color(102, 102, 102)); jLabelNoSelect.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelNoSelect.setText("<Selecione um Estado>"); jPanelEmpty.add(jLabelNoSelect, java.awt.BorderLayout.CENTER); jPanelProperties.add(jPanelEmpty, "card1"); jPanelFull.setLayout(new java.awt.BorderLayout()); jTabbedPaneProperties.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT); jPanelBase.setLayout(new java.awt.CardLayout()); jLabelStateName.setText("Nome:"); jTextFieldStateName.setEditable(false); jTextFieldStateName.setOpaque(false); javax.swing.GroupLayout jPanelBaseStateLayout = new javax.swing.GroupLayout(jPanelBaseState); jPanelBaseState.setLayout(jPanelBaseStateLayout); jPanelBaseStateLayout.setHorizontalGroup( jPanelBaseStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBaseStateLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabelStateName) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldStateName, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE) .addContainerGap()) ); jPanelBaseStateLayout.setVerticalGroup( jPanelBaseStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBaseStateLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelBaseStateLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelStateName) .addComponent(jTextFieldStateName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(171, Short.MAX_VALUE)) ); jPanelBase.add(jPanelBaseState, "card1"); jLabelConnectionName.setText("Nome:"); jTextFieldConnectionName.setEditable(false); jTextFieldConnectionName.setOpaque(false); jLabelConnectionSource.setText("Origem:"); jTextFieldConnectionSource.setEditable(false); jTextFieldConnectionSource.setOpaque(false); jLabelConnectionTarget.setText("Destino:"); jTextFieldConnectionTarget.setEditable(false); jTextFieldConnectionTarget.setOpaque(false); javax.swing.GroupLayout jPanelBaseConnectionLayout = new javax.swing.GroupLayout(jPanelBaseConnection); jPanelBaseConnection.setLayout(jPanelBaseConnectionLayout); jPanelBaseConnectionLayout.setHorizontalGroup( jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBaseConnectionLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelConnectionName) .addComponent(jLabelConnectionSource) .addComponent(jLabelConnectionTarget)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldConnectionTarget, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE) .addComponent(jTextFieldConnectionSource, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextFieldConnectionName, javax.swing.GroupLayout.Alignment.TRAILING)) .addContainerGap()) ); jPanelBaseConnectionLayout.setVerticalGroup( jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanelBaseConnectionLayout.createSequentialGroup() .addContainerGap() .addGroup(jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelConnectionName) .addComponent(jTextFieldConnectionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelConnectionSource) .addComponent(jTextFieldConnectionSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanelBaseConnectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelConnectionTarget) .addComponent(jTextFieldConnectionTarget, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelBase.add(jPanelBaseConnection, "card2"); jTabbedPaneProperties.addTab("Base", jPanelBase); jPanelExpressions.setLayout(new java.awt.BorderLayout()); jTableExpressions.getTableHeader().setReorderingAllowed(false); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listExpressions, jTableExpressions); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${attribute}")); columnBinding.setColumnName("Atributo"); columnBinding.setColumnClass(br.com.upf.beans.Attribute.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${operator}")); columnBinding.setColumnName("Operador"); columnBinding.setColumnClass(br.com.upf.util.Operator.class); columnBinding.setEditable(false); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${value}")); columnBinding.setColumnName("Valor"); columnBinding.setColumnClass(String.class); columnBinding.setEditable(false); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPaneExpressions.setViewportView(jTableExpressions); if (jTableExpressions.getColumnModel().getColumnCount() > 0) { jTableExpressions.getColumnModel().getColumn(0).setResizable(false); jTableExpressions.getColumnModel().getColumn(1).setResizable(false); jTableExpressions.getColumnModel().getColumn(2).setResizable(false); } jPanelExpressions.add(jScrollPaneExpressions, java.awt.BorderLayout.CENTER); jTabbedPaneProperties.addTab("Expressões", jPanelExpressions); jPanelFull.add(jTabbedPaneProperties, java.awt.BorderLayout.CENTER); jPanelProperties.add(jPanelFull, "card2"); jSplitPaneWest.setRightComponent(jPanelProperties); jPanelWest.add(jSplitPaneWest, java.awt.BorderLayout.CENTER); jSplitPaneCenter.setLeftComponent(jPanelWest); jPanelContent.setLayout(new java.awt.BorderLayout()); jSplitPaneCenter.setRightComponent(jPanelContent); jPanelCenter.add(jSplitPaneCenter, java.awt.BorderLayout.CENTER); jPanelPrincipal.add(jPanelCenter, java.awt.BorderLayout.CENTER); jPanelSouth.setPreferredSize(new java.awt.Dimension(484, 25)); jPanelSouth.setLayout(new java.awt.BorderLayout()); jPanelSouth.add(jLabelStatusInformation, java.awt.BorderLayout.CENTER); jPanelPrincipal.add(jPanelSouth, java.awt.BorderLayout.PAGE_END); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanelPrincipal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabelConnectionName; private javax.swing.JLabel jLabelConnectionSource; private javax.swing.JLabel jLabelConnectionTarget; private javax.swing.JLabel jLabelNoSelect; private javax.swing.JLabel jLabelStateName; private javax.swing.JLabel jLabelStatusInformation; private javax.swing.JPanel jPanelBase; private javax.swing.JPanel jPanelBaseConnection; private javax.swing.JPanel jPanelBaseState; private javax.swing.JPanel jPanelCenter; private javax.swing.JPanel jPanelContent; private javax.swing.JPanel jPanelEmpty; private javax.swing.JPanel jPanelExpressions; private javax.swing.JPanel jPanelFull; private javax.swing.JPanel jPanelNorth; private javax.swing.JPanel jPanelPalette; private javax.swing.JPanel jPanelPrincipal; private javax.swing.JPanel jPanelProperties; private javax.swing.JPanel jPanelSouth; private javax.swing.JPanel jPanelWest; private javax.swing.JScrollPane jScrollPaneExpressions; private javax.swing.JSplitPane jSplitPaneCenter; private javax.swing.JSplitPane jSplitPaneWest; private javax.swing.JTabbedPane jTabbedPaneProperties; private javax.swing.JTable jTableExpressions; private javax.swing.JTextField jTextFieldConnectionName; private javax.swing.JTextField jTextFieldConnectionSource; private javax.swing.JTextField jTextFieldConnectionTarget; private javax.swing.JTextField jTextFieldStateName; private java.util.List<br.com.upf.beans.StandartExpression> listExpressions; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables public StateGraphComponent getStateGraphComponent() { return stateGraphComponent; } public void setStateGraphComponent(StateGraphComponent stateGraphComponent) { this.stateGraphComponent = stateGraphComponent; } public StateGraph getStateGraph() { return stateGraph; } public void setStateGraph(StateGraph stateGraph) { this.stateGraph = stateGraph; } public StatePalette getPalette() { return palette; } public void setPalette(StatePalette palette) { this.palette = palette; } public GraphEditor getGraphEditor() { return graphEditor; } public void setGraphEditor(GraphEditor graphEditor) { this.graphEditor = graphEditor; } public boolean isModified() { return modified; } public void setModified(boolean modified) { this.modified = modified; } public mxUndoManager getUndoManager() { return undoManager; } public void setUndoManager(mxUndoManager undoManager) { this.undoManager = undoManager; } public ClassModel getClassModel() { return classModel; } public void setClasseModel(ClassModel classeModel) { this.classModel = classeModel; } public DiagramOfStateModel getDiagramOfStateModel() { return diagramOfStateModel; } public void setDiagramOfStateModel(DiagramOfStateModel diagramOfStateModel) { this.diagramOfStateModel = diagramOfStateModel; } public ClassElement getClassElement() { return classElement; } public void setClassElement(ClassElement classElement) { this.classElement = classElement; } @Override public int hashCode() { int hash = 7; hash = 19 * hash + Objects.hashCode(this.classElement); hash = 19 * hash + Objects.hashCode(this.classModel); hash = 19 * hash + Objects.hashCode(this.diagramOfStateModel); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final StateEditor other = (StateEditor) obj; if (!Objects.equals(this.classElement, other.classElement)) { return false; } if (!Objects.equals(this.classModel, other.classModel)) { return false; } if (!Objects.equals(this.diagramOfStateModel, other.diagramOfStateModel)) { return false; } return true; } }
[ "giord.ce@gmail.com" ]
giord.ce@gmail.com
981cd420bd41620bcb6fbfbe70f50f76d93ebdc7
3b52a7c5548fe28876fdebd42ff8ba3335f68bd5
/HelloWorld/app/src/main/java/com/example/lzw/myapp/Provider/services/ReadDatabaseContext.java
26e17f8730b9c18e74a1a445bf90c9dc28881e2f
[]
no_license
nanchuanliu/App
2f7a32f9c11db4fc40c6606cbd4c3a0d2bc02067
1ff680925dd70714afc4f1852f49045ada534367
refs/heads/master
2021-01-22T05:47:47.585110
2017-06-27T10:10:08
2017-06-27T10:10:08
92,497,771
0
0
null
null
null
null
UTF-8
Java
false
false
290
java
package com.example.lzw.myapp.Provider.services; import android.database.sqlite.SQLiteDatabase; /** * Created by Administrator on 2017/6/8. */ public class ReadDatabaseContext extends DatabaseContext { public ReadDatabaseContext(SQLiteDatabase db) { super(db); } }
[ "349249441@qq.com" ]
349249441@qq.com
b7edfc8faa14a9efc4f590629df229b8dbf41441
b6d62f834db18a212dd9bf4927ec1ff4eba81d30
/src/main/java/com/capovskyAlexandr/zonkytest/controller/CustomerController.java
10ffc4831354ff6589f20c23b9fca5898cc9b993
[]
no_license
AlexandrC/myP2PLendingMoneyProject
26b122ab23fee253e43c33a0780fee714e1c94d0
12c438df577affc9b0efff9f3fa2decbb1f7a0fc
refs/heads/master
2023-04-01T03:29:26.171099
2021-04-03T16:54:35
2021-04-03T16:54:35
347,704,931
0
0
null
null
null
null
UTF-8
Java
false
false
794
java
package com.capovskyAlexandr.zonkytest.controller; import com.capovskyAlexandr.zonkytest.entity.CustomerEntity; import com.capovskyAlexandr.zonkytest.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @CrossOrigin(origins = "*") @RequestMapping("/customer") public class CustomerController { @Autowired CustomerService customerService; @PostMapping(value = "/create") public ResponseEntity<CustomerEntity> createCustomer(@RequestBody CustomerEntity customer){ return new ResponseEntity<>(customerService.createCustomer(customer), HttpStatus.ACCEPTED); } }
[ "acapovsky@gmail.com" ]
acapovsky@gmail.com
a664f27230fbb5cf82124de2c504c23b7ac60d0d
20faf0364473d4a1376656e990788ce13bb5f3e3
/src/com/company/daysofcode/arrays/Input.java
0be4daaa7e87480eed4a36e814f8ded3dc97bedd
[]
no_license
Anushka-shukla/100DaysOfCode
e60003f5bb27a97c18e027daf375dbfd42b2a39e
4b9cdcc07fed3524c4bd963396c39eb6095b9b5c
refs/heads/main
2023-08-13T21:49:49.776609
2021-09-26T18:15:57
2021-09-26T18:15:57
393,102,170
1
0
null
null
null
null
UTF-8
Java
false
false
775
java
package com.company.daysofcode.arrays; import java.util.Arrays; import java.util.Scanner; public class Input { public static void main(String[] args) { Scanner input = new Scanner(System.in); // array of primitives int[] arr = new int[5]; //input using for loop for(int i=0; i<arr.length; i++){ arr[i] = input.nextInt(); } for(int i=0; i<arr.length; i++){ System.out.print(arr[i] + " "); //System.out.println(Arrays.toString(arr)); } // enhanced for loop // here j represents ele of the array //called for each loop for (int j : arr) { // for every ele in the array print the ele System.out.print(j + " "); } } }
[ "shuklaannushka@gmail.com" ]
shuklaannushka@gmail.com
91ae7e90f45c52d31c6badfc5d6679eeac363bb3
51170fae9718e9542270d5ac3683bb523ab2978c
/library/src/main/java/com/conglai/uikit/feature/base/BaseListView.java
d57ce80397fecd31b15a1c835e0615d8a401b89a
[]
no_license
cheerr/uikit_public
bbdd6d6d658aca8eab389a21edd5f493abff43d5
bca5952b1a0197e9f781791de80ca050af7aaf7c
refs/heads/master
2020-12-23T16:42:35.594161
2017-05-27T05:03:09
2017-05-27T05:03:09
92,571,890
0
0
null
null
null
null
UTF-8
Java
false
false
2,919
java
package com.conglai.uikit.feature.base; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import com.conglai.common.Debug; import com.conglai.uikit.feature.features.pullrefresh.builders.HeaderFooterBuilder; import java.util.ArrayList; import java.util.List; /** * Created by chenwei on 15/9/5. */ public class BaseListView extends ListView implements HeaderFooterBuilder { private final String debug = "BaseListView"; private List<View> headerList, footerList; public BaseListView(Context context) { this(context, null); } public BaseListView(Context context, AttributeSet attrs) { super(context, attrs); initSelf(); } public BaseListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initSelf(); } private void initSelf() { headerList = new ArrayList<>(); footerList = new ArrayList<>(); } @Override public void addHeaderView(View view) { if (!headerList.contains(view)) { super.addHeaderView(view); headerList.add(view); } else { Debug.print(debug, "headerView 已存在!!!不能重复添加"); } } @Override public void addFooterView(View view) { if (!footerList.contains(view)) { super.addFooterView(view); footerList.add(view); } else { Debug.print(debug, "footerView 已存在!!!不能重复添加"); } } @Override public boolean removeHeaderView(View view) { if (headerList.contains(view)) { headerList.remove(view); return super.removeHeaderView(view); } else { return false; } } @Override public boolean removeFooterView(View view) { if (footerList.contains(view)) { footerList.remove(view); return super.removeFooterView(view); } else { return false; } } @Override public View getFirstHeader() { return headerList.size() == 0 ? null : headerList.get(0); } @Override public View getLastFooter() { return footerList.size() == 0 ? null : footerList.get(footerList.size() - 1); } @Override public boolean arrivedTop() { return getFirstVisiblePosition() <= 0; } @Override public boolean arrivedBottom() { return getLastVisiblePosition() == getCount() - 1; } public void superDispatchTouchEvent(MotionEvent ev) { super.dispatchTouchEvent(ev); } public void superOnInterceptTouchEvent(MotionEvent ev) { super.onInterceptTouchEvent(ev); } public void superOnTouchEvent(MotionEvent ev) { super.onTouchEvent(ev); } }
[ "sangguo@weixinzhuyi.com" ]
sangguo@weixinzhuyi.com
c54da41d8cb96b0ab8aeca49a43913b5177266d5
9867afa266eb3ea4abfa091befcb227fbd3f6f96
/app/src/main/java/com/haier/ai/bluetoothspeaker1/util/SpeechJavaBeanUtils.java
b448b6cbf06c4eaaf72acb9003c478ba3c892b66
[]
no_license
eric123qu/yuyin
15010c121a37967207547213ef29bc9321b95d3d
034ebb0728c4f6ac7641aaac90b40a23bcde02bf
refs/heads/master
2021-01-18T18:42:24.867697
2017-04-05T10:05:22
2017-04-05T10:05:22
86,873,748
0
0
null
null
null
null
UTF-8
Java
false
false
988
java
/* * Copyright (C) 2016 Baidu, Inc. All Rights Reserved. */ package com.haier.ai.bluetoothspeaker1.util; import com.haier.ai.bluetoothspeaker1.Const; import com.haier.ai.bluetoothspeaker1.bean.speechtotext.ResponseS2TNew; /** * 文本转语音 工具类 * Created by Joyson on 2016/8/8. */ public class SpeechJavaBeanUtils { /** * 语音-->文本 所需要的内容,解析 * @param message 返回json内容 * @return */ public static String S2TgetText(String message){ ResponseS2TNew responseS2TNew=JsonUtil.parseJsonToBean(message,ResponseS2TNew.class); //需要得到文本信息 //判断返回码 if(responseS2TNew.getRetCode().equals(Const.RET_CODE_SUCESS)){ if(responseS2TNew.getData() == null){ return null; }else return responseS2TNew.getData().getAsrResult().get(0).getRecogniationText(); }else{ return null; } } }
[ "quxin3r@gmail.com" ]
quxin3r@gmail.com
7c8aa8a0c296936dcc956bde3d2b79df54b69a71
f7145608e0c57f36a9c6b8e35fa84da245c2d247
/Protótipo funcional/JAVA/src/CadastroFamilia.java
a285da98e1106813d7e845843b4da326e9ef6f46
[]
no_license
Harrisonlb/DHK-Sofware
82745eeb3544d26531ee1a6e5f998c5e96306058
9aecec12f2e7c43f3d2acf12e7370aa90f7bc9cd
refs/heads/master
2021-01-01T19:31:21.698578
2017-07-28T02:53:44
2017-07-28T02:53:44
98,600,178
0
0
null
null
null
null
UTF-8
Java
false
false
10,597
java
import java.util.*; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Dalvan */ public class CadastroFamilia extends javax.swing.JFrame { /** * Creates new form CadastroFamilia */ public CadastroFamilia() { initComponents(); setSize(550,750); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); nome = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); cpf = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); cep = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); cidade = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); nomePrincipal = new javax.swing.JTextField(); cpfPrincipal = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel12 = new javax.swing.JLabel(); estado = new javax.swing.JTextField(); doenca = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); fundo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N jLabel2.setText("Cadastro de família"); getContentPane().add(jLabel2); jLabel2.setBounds(180, 100, 173, 25); jLabel1.setText("Integrante Principal"); getContentPane().add(jLabel1); jLabel1.setBounds(90, 160, 130, 14); jLabel3.setText("Nome:"); getContentPane().add(jLabel3); jLabel3.setBounds(110, 420, 80, 14); nome.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N nome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nomeActionPerformed(evt); } }); getContentPane().add(nome); nome.setBounds(190, 420, 260, 19); jLabel4.setText("CPF:"); getContentPane().add(jLabel4); jLabel4.setBounds(110, 460, 60, 14); cpf.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N getContentPane().add(cpf); cpf.setBounds(190, 460, 150, 19); jLabel5.setText("Endereço:"); getContentPane().add(jLabel5); jLabel5.setBounds(90, 270, 70, 14); cep.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N getContentPane().add(cep); cep.setBounds(190, 290, 140, 19); jLabel6.setText("CEP:"); getContentPane().add(jLabel6); jLabel6.setBounds(110, 290, 60, 14); jLabel7.setText("Cidade:"); getContentPane().add(jLabel7); jLabel7.setBounds(110, 320, 70, 14); cidade.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N cidade.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cidadeActionPerformed(evt); } }); getContentPane().add(cidade); cidade.setBounds(190, 320, 140, 19); jLabel8.setText("Estado:"); getContentPane().add(jLabel8); jLabel8.setBounds(340, 320, 50, 14); jLabel9.setText("Integrantes da Família"); getContentPane().add(jLabel9); jLabel9.setBounds(90, 370, 130, 14); jLabel10.setText("Nome:"); getContentPane().add(jLabel10); jLabel10.setBounds(100, 180, 80, 14); nomePrincipal.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N nomePrincipal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { nomePrincipalActionPerformed(evt); } }); getContentPane().add(nomePrincipal); nomePrincipal.setBounds(190, 180, 260, 19); cpfPrincipal.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N getContentPane().add(cpfPrincipal); cpfPrincipal.setBounds(190, 210, 150, 19); jLabel11.setText("CPF:"); getContentPane().add(jLabel11); jLabel11.setBounds(100, 210, 60, 14); jButton1.setText("Cadastrar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(120, 570, 90, 23); jLabel12.setText("Doença:"); getContentPane().add(jLabel12); jLabel12.setBounds(110, 500, 50, 14); estado.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N getContentPane().add(estado); estado.setBounds(400, 320, 50, 19); doenca.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N getContentPane().add(doenca); doenca.setBounds(190, 500, 100, 19); jButton2.setText("Sair"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(350, 570, 73, 23); fundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/board.png"))); // NOI18N getContentPane().add(fundo); fundo.setBounds(0, 0, 540, 720); pack(); }// </editor-fold>//GEN-END:initComponents private void cidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cidadeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cidadeActionPerformed private void nomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nomeActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed MembroFamilia novo = new MembroFamilia(nome.getText(), cpf.getText(), doenca.getText(),true); Familia nova = new Familia(cidade.getText(),estado.getText(),cep.getText(), novo); Lista.adiciona(nova); new TelaAgente().setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed new TelaAgente().setVisible(true); this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void nomePrincipalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomePrincipalActionPerformed // TODO add your handling code here: }//GEN-LAST:event_nomePrincipalActionPerformed private void add(Familia nova){ } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CadastroFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastroFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastroFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastroFamilia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CadastroFamilia().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField cep; private javax.swing.JTextField cidade; private javax.swing.JTextField cpf; private javax.swing.JTextField cpfPrincipal; private javax.swing.JTextField doenca; private javax.swing.JTextField estado; private javax.swing.JLabel fundo; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField nome; private javax.swing.JTextField nomePrincipal; // End of variables declaration//GEN-END:variables }
[ "harrison_lopes@outlook.com" ]
harrison_lopes@outlook.com
7f3d36ed3ce66195c007e01f8ef7e6a83ae098c7
33fe6e2a113d18a063f68a0be83d74a98a15ff99
/test/com/jetbrains/ther/run/debug/mock/ExecutorServices.java
9dde8b6e710fbe8773dbd61e75e3ad585bf4cd6a
[ "MIT" ]
permissive
Avila-Diego/TheRPlugin
848240d35689006ab8496f274157683b3415ea44
be2593c26dee8f6287d5ec0a82aebbca9c74f657
refs/heads/master
2023-03-19T19:59:18.881548
2016-07-05T13:08:10
2016-07-05T13:08:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,046
java
package com.jetbrains.ther.run.debug.mock; import com.intellij.util.ConcurrencyUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import java.util.concurrent.*; public final class ExecutorServices { @NotNull public static final ExecutorService SINGLE_EXECUTOR = ConcurrencyUtil.newSingleThreadExecutor("TheRDebuggerTestBackground"); @NotNull public static final ExecutorService ILLEGAL_EXECUTOR = new ExecutorService() { @Override public void shutdown() { throw new IllegalStateException("Shutdown shouldn't be called"); } @NotNull @Override public List<Runnable> shutdownNow() { throw new IllegalStateException("ShutdownNow shouldn't be called"); } @Override public boolean isShutdown() { throw new IllegalStateException("IsShutdown shouldn't be called"); } @Override public boolean isTerminated() { throw new IllegalStateException("IsTerminated shouldn't be called"); } @Override public boolean awaitTermination(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException { throw new IllegalStateException("AwaitTermination shouldn't be called"); } @NotNull @Override public <T> Future<T> submit(@NotNull final Callable<T> task) { throw new IllegalStateException("Submit shouldn't be called"); } @NotNull @Override public <T> Future<T> submit(@NotNull final Runnable task, final T result) { throw new IllegalStateException("Submit shouldn't be called"); } @NotNull @Override public Future<?> submit(@NotNull final Runnable task) { throw new IllegalStateException("Submit shouldn't be called"); } @NotNull @Override public <T> List<Future<T>> invokeAll(@NotNull final Collection<? extends Callable<T>> tasks) throws InterruptedException { throw new IllegalStateException("InvokeAll shouldn't be called"); } @NotNull @Override public <T> List<Future<T>> invokeAll(@NotNull final Collection<? extends Callable<T>> tasks, final long timeout, @NotNull final TimeUnit unit) throws InterruptedException { throw new IllegalStateException("InvokeAll shouldn't be called"); } @NotNull @Override public <T> T invokeAny(@NotNull final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { throw new IllegalStateException("InvokeAny shouldn't be called"); } @Override public <T> T invokeAny(@NotNull final Collection<? extends Callable<T>> tasks, final long timeout, @NotNull final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new IllegalStateException("InvokeAny shouldn't be called"); } @Override public void execute(@NotNull final Runnable command) { throw new IllegalStateException("Execute shouldn't be called"); } }; }
[ "s-proshev@ya.ru" ]
s-proshev@ya.ru