blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
03d25f181bdb6ebb6503aff8af0cc8f8711697e5
5c286ccdfbd53da090dc3700de488a02bfe664ca
/jme3-examples/src/main/java/jme3test/material/TestParallaxPBR.java
15bf2588208c8fb87be813602a693b9c04a93a16
[ "BSD-3-Clause" ]
permissive
asmboom/jmonkeyengine
c74c13531b991d2f6bed4ee9e174b01bc86e1482
aeb4daf04f20d32aeb3400cd43addfd15c5a7455
refs/heads/master
2021-01-21T16:35:19.695001
2016-08-13T22:55:20
2016-08-13T22:56:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,026
java
/* * Copyright (c) 2009-2012 jMonkeyEngine * 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 'jMonkeyEngine' 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 jme3test.material; import com.jme3.app.SimpleApplication; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.*; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.jme3.util.SkyFactory; import com.jme3.util.TangentBinormalGenerator; public class TestParallaxPBR extends SimpleApplication { private Vector3f lightDir = new Vector3f(-1, -1, .5f).normalizeLocal(); public static void main(String[] args) { TestParallaxPBR app = new TestParallaxPBR(); app.start(); } public void setupSkyBox() { rootNode.attachChild(SkyFactory.createSky(assetManager, "Scenes/Beach/FullskiesSunset0068.dds", false)); } DirectionalLight dl; public void setupLighting() { dl = new DirectionalLight(); dl.setDirection(lightDir); dl.setColor(new ColorRGBA(.9f, .9f, .9f, 1)); rootNode.addLight(dl); } Material mat; public void setupFloor() { mat = assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWallPBR.j3m"); //mat = assetManager.loadMaterial("Textures/Terrain/BrickWall/BrickWallPBR2.j3m"); Node floorGeom = new Node("floorGeom"); Quad q = new Quad(100, 100); q.scaleTextureCoordinates(new Vector2f(10, 10)); Geometry g = new Geometry("geom", q); g.setLocalRotation(new Quaternion().fromAngleAxis(-FastMath.HALF_PI, Vector3f.UNIT_X)); floorGeom.attachChild(g); TangentBinormalGenerator.generate(floorGeom); floorGeom.setLocalTranslation(-50, 22, 60); //floorGeom.setLocalScale(100); floorGeom.setMaterial(mat); rootNode.attachChild(floorGeom); } public void setupSignpost() { Spatial signpost = assetManager.loadModel("Models/Sign Post/Sign Post.mesh.xml"); Material mat = assetManager.loadMaterial("Models/Sign Post/Sign Post.j3m"); TangentBinormalGenerator.generate(signpost); signpost.setMaterial(mat); signpost.rotate(0, FastMath.HALF_PI, 0); signpost.setLocalTranslation(12, 23.5f, 30); signpost.setLocalScale(4); signpost.setShadowMode(ShadowMode.CastAndReceive); rootNode.attachChild(signpost); } @Override public void simpleInitApp() { cam.setLocation(new Vector3f(-15.445636f, 30.162927f, 60.252777f)); cam.setRotation(new Quaternion(0.05173137f, 0.92363626f, -0.13454558f, 0.35513034f)); flyCam.setMoveSpeed(30); setupLighting(); setupSkyBox(); setupFloor(); setupSignpost(); inputManager.addListener(new AnalogListener() { public void onAnalog(String name, float value, float tpf) { if ("heightUP".equals(name)) { parallaxHeigh += 0.01; mat.setFloat("ParallaxHeight", parallaxHeigh); } if ("heightDown".equals(name)) { parallaxHeigh -= 0.01; parallaxHeigh = Math.max(parallaxHeigh, 0); mat.setFloat("ParallaxHeight", parallaxHeigh); } } }, "heightUP", "heightDown"); inputManager.addMapping("heightUP", new KeyTrigger(KeyInput.KEY_I)); inputManager.addMapping("heightDown", new KeyTrigger(KeyInput.KEY_K)); inputManager.addListener(new ActionListener() { public void onAction(String name, boolean isPressed, float tpf) { if (isPressed && "toggleSteep".equals(name)) { steep = !steep; mat.setBoolean("SteepParallax", steep); } } }, "toggleSteep"); inputManager.addMapping("toggleSteep", new KeyTrigger(KeyInput.KEY_SPACE)); } float parallaxHeigh = 0.05f; float time = 0; boolean steep = false; @Override public void simpleUpdate(float tpf) { // time+=tpf; // lightDir.set(FastMath.sin(time), -1, FastMath.cos(time)); // bsr.setDirection(lightDir); // dl.setDirection(lightDir); } }
33a17dab2782e8feff82eae7a3b3bc790859bc1f
7051d41edfbee034cc50e0d4dc2b294e0f9391d9
/src/codinginterviews/Solution33.java
104e7556150782ca6cac08d9fc1b72fadbad42a2
[]
no_license
Ryougi-Shiki0/Leetcode-Practice
5d073df139e4fefc7fce0a10dcd87c091849e0de
f2125a57210bbafc96874e76f368db349320f493
refs/heads/master
2022-07-15T11:20:05.353098
2022-06-06T17:17:12
2022-06-06T17:17:12
233,251,796
1
0
null
null
null
null
UTF-8
Java
false
false
2,853
java
package codinginterviews; public class Solution33 { /*public boolean verifyPostorder(int[] postorder) { //暴力方法 *//*if (postorder.length < 1) { return true; } int[] inorder=Arrays.copyOf(postorder,postorder.length); Arrays.sort(inorder); Stack<Integer> stack=new Stack<>(); int j=0; for (int value : inorder) { stack.push(value); while (j < inorder.length && !stack.isEmpty() && stack.peek() == postorder[j]) { stack.pop(); j++; } } return j==inorder.length;*//* // 单调栈使用,单调递增的单调栈 Stack<Integer> stack=new Stack<>(); int pre = Integer.MAX_VALUE; // 逆向遍历,就是翻转的先序遍历 for(int i=postorder.length-1;i>=0;i--){ // 左子树元素必须要小于递增栈被peek访问的元素,否则就不是二叉搜索树 if(postorder[i]>pre){ return false; } while(!stack.isEmpty() && postorder[i]<stack.peek()){ // 数组元素小于单调栈的元素了,表示往左子树走了,记录下上个根节点 // 找到这个左子树对应的根节点,之前右子树全部弹出,不再记录,因为不可能在往根节点的右子树走了 pre = stack.peek(); stack.pop(); } // 新元素入栈 stack.push(postorder[i]); } return true; }*/ public boolean verifyPostorder(int[] postorder) { if (postorder.length < 2) { return true; } return verify(postorder, 0, postorder.length - 1); } // 递归实现 private boolean verify(int[] postorder, int left, int right){ // 当前区域不合法的时候直接返回true就好 if (left >= right) { return true; } // 当前树的根节点的值 int rootValue = postorder[right]; int k = left; // 从当前区域找到第一个大于根节点的,说明后续区域数值都在右子树中 while (k < right && postorder[k] < rootValue) { k++; } // 进行判断后续的区域是否所有的值都是大于当前的根节点,如果出现小于的值就直接返回false for (int i = k; i < right; i++) { if (postorder[i] < rootValue) { return false; } } // 当前树没问题就检查左右子树 // 检查左子树 if (!verify(postorder, left, k - 1)) { return false; } // 检查右子树 if (!verify(postorder, k, right - 1)) { return false; } return true; } }
a16ba81658a54d2fd8c5cd7f9d1b58c2f64d2fa4
a3a06ca27ecad4b4674694387561d97d4920da47
/kie-wb-common-command-api/src/main/java/org/kie/workbench/common/command/client/exception/BadCommandArgumentsException.java
adb93ce7442da680de96268aa93a617e0a244f4d
[ "Apache-2.0" ]
permissive
danielzhe/kie-wb-common
71e777afc9c518c52f307f33230850bacfcb2013
e12a7deeb73befb765939e7185f95b2409715b41
refs/heads/main
2022-08-24T12:01:21.180766
2022-03-29T07:55:56
2022-03-29T07:55:56
136,397,477
1
0
Apache-2.0
2020-08-06T14:50:34
2018-06-06T23:43:53
Java
UTF-8
Java
false
false
1,459
java
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.command.client.exception; import org.kie.workbench.common.command.client.Command; /** * A command argument is not valid. * The command's executor should check the arguments on the context before calling the command. * For example if using a bad runtime execution context where element cannot be found in the index. */ public final class BadCommandArgumentsException extends CommandException { private final Object argument; public BadCommandArgumentsException(final Command<?, ?> command, final Object argument, final String message) { super("Bad argument: " + message, command); this.argument = argument; } public Object getArgument() { return argument; } }
f3502f076bbd8868565fe27bdf48930e7585e9be
12c1964c561c070b8f5f3233a8488bedecc6e3ab
/src/fxft/util/InstallUtils.java
910c39d257fe75a36e20c812c42fbe74d78761bf
[]
no_license
wcedla/DeployToolByJavaFx
3d733e2ced5dbc0fae894bda4cc07ccb8f1d4793
82eba446385373e4379720b4addf87c818ff1b6d
refs/heads/master
2021-03-17T08:29:18.484732
2020-03-13T03:11:33
2020-03-13T03:11:33
246,976,863
0
0
null
null
null
null
UTF-8
Java
false
false
10,348
java
package fxft.util; import fxft.data.ModuleData; import fxft.global.GlobalData; import java.io.*; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Set; public class InstallUtils { public static void installPackage(List<String> packageList, String installPath) { try { Class<InstallUtils> c = InstallUtils.class; Object o = c.newInstance(); for (String name : packageList) { Method method = c.getDeclaredMethod("install" + name, String.class); if (method != null) { method.invoke(o, installPath); } } } catch (Exception e) { e.printStackTrace(); } } private static void installweb(String path) { try { FileUtils.copyDir(GlobalData.PACKAGE_RESOURCE_PATH + File.separator + "web", path); String batFilePath = path + File.separator + "web.bat"; String cmd = "java -jar " + path + File.separator + "web-0.0.1-SNAPSHOT.jar ->" + System.getProperty("user.dir") + File.separator + "web.log"; FileUtils.writeBatFile(batFilePath, cmd); ServerUtils.installService("", "web", batFilePath, "", ""); System.out.println("安装web," + path); XmlUtils.writeXmlFile(new ModuleData("web", "web", path, "")); } catch (IOException e) { e.printStackTrace(); } } private static void installmysql(String path) { System.out.println("安装mysql," + path); } private static void installkafka(String path) { System.out.println("安装kafka," + path); } private static void installredis(String path) { System.out.println("安装redis," + path); } public static void installOnlinePackageForWindows(Set<String> installSet, InstallConfig installConfig, Path installPath, Path tmpRunJarPath, String userName, String password) { for (String moduleName : installSet) { try { Path moduleInstallPath = installPath.resolve(moduleName).toAbsolutePath(); if (Files.exists(moduleInstallPath)) { System.out.println("安装的服务的文件夹已经创建过了" + moduleInstallPath); } else { System.out.println("开始创建服务安装文件夹" + moduleInstallPath); Files.createDirectories(moduleInstallPath); Path logPath = moduleInstallPath.resolveSibling("logs").resolve(moduleName); if (!Files.exists(logPath)) { Files.createDirectories(logPath); System.out.println("新建logs目录:" + logPath.toString()); } Files.copy(tmpRunJarPath, moduleInstallPath.resolve("run.jar")); List<CharSequence> moduleConfigDataList = new ArrayList<>(); moduleConfigDataList.add("run.deployServer=" + installConfig.getInstallConfig("deployServerURL")); moduleConfigDataList.add("run.log.path=" + logPath.toAbsolutePath().toString()); StringBuilder vmArgs = new StringBuilder(); vmArgs.append(" -agentlib:libfxft-jardecoder"); for (String line : installConfig.getModuleContainerValue(moduleName)) { if (line.startsWith("-")) { vmArgs.append(" "); vmArgs.append(line); } else { moduleConfigDataList.add(line); } } if (vmArgs.indexOf("-Xmx") == -1) { vmArgs.append(" -Xmx256M"); } vmArgs.append(" -Drun.profiles=default"); Files.write(moduleInstallPath.resolve("moduleVersion.config"), moduleConfigDataList, StandardCharsets.UTF_8); createWindowService(moduleName, moduleInstallPath, vmArgs.toString(), userName, password); // afterCreateContainer(containerName, containerDir, vmops); } } catch (Exception e) { e.printStackTrace(); } } } private static void createWindowService(String moduleName, Path moduleInstallPath, String vmArgs, String userName, String password) { String batFilePath = moduleInstallPath.toAbsolutePath() + File.separator + moduleName + ".bat"; System.out.println("bat文件地址:" + batFilePath); String cmd = "cd /d " + moduleInstallPath.toAbsolutePath() + "\njava -jar" + vmArgs + " run.jar" + " > " + moduleInstallPath.toAbsolutePath() + File.separator + moduleName + ".log"; System.out.println("bat命令:" + cmd); FileUtils.writeBatFile(batFilePath, cmd); String serviceBatPath = moduleInstallPath.toAbsolutePath() + File.separator + moduleName + "Service.bat"; System.out.println("开始安装服务"); ServerUtils.installService(serviceBatPath, moduleName, batFilePath, userName, password); // System.out.println("安装web," + path); System.out.println("开始写入xml文件"); XmlUtils.writeXmlFile(new ModuleData(moduleName, moduleName, moduleInstallPath.toString(), moduleInstallPath + File.separator + moduleName + ".log")); } public static void installOnlinePackageForLinux(Set<String> installSet, InstallConfig installConfig, Path installPath, Path tmpRunJarPath, String userName, String password) { for (String moduleName : installSet) { try { Path moduleInstallPath = installPath.resolve(moduleName).toAbsolutePath(); if (Files.exists(moduleInstallPath)) { System.out.println("安装的服务的文件夹已经创建过了" + moduleInstallPath); } else { System.out.println("开始创建服务安装文件夹" + moduleInstallPath); Files.createDirectories(moduleInstallPath); Path logPath = moduleInstallPath.resolveSibling("logs").resolve(moduleName); if (!Files.exists(logPath)) { Files.createDirectories(logPath); System.out.println("新建logs目录:" + logPath.toString()); } Files.copy(tmpRunJarPath, moduleInstallPath.resolve("run.jar")); List<CharSequence> moduleConfigDataList = new ArrayList<>(); moduleConfigDataList.add("run.deployServer=" + installConfig.getInstallConfig("deployServerURL")); moduleConfigDataList.add("run.log.path=" + logPath.toAbsolutePath().toString()); StringBuilder vmArgs = new StringBuilder(); vmArgs.append(" -agentlib:libfxft-jardecoder"); for (String line : installConfig.getModuleContainerValue(moduleName)) { if (line.startsWith("-")) { vmArgs.append(" "); vmArgs.append(line); } else { moduleConfigDataList.add(line); } } if (vmArgs.indexOf("-Xmx") == -1) { vmArgs.append(" -Xmx256M"); } vmArgs.append(" -Drun.profiles=default"); Files.write(moduleInstallPath.resolve("moduleVersion.config"), moduleConfigDataList, StandardCharsets.UTF_8); createLinuxService(moduleName, moduleInstallPath.toAbsolutePath().toString(), vmArgs.toString()); // afterCreateContainer(containerName, containerDir, vmops); } } catch (Exception e) { e.printStackTrace(); } } } private static void createLinuxService(String moduleName, String moduleInstallPath, String vmArgs) { String systemPath = "/usr/lib/systemd/system"; String javaPath = System.getProperty("user.dir") + File.separator + "jre" + File.separator + "bin" + File.separator + "java"; String jarPath = moduleInstallPath + File.separator + "run.jar"; String serviceContent = buildServiceContent(moduleName, javaPath, jarPath, vmArgs); System.out.println("获取service内容:" + serviceContent); File serviceFile = new File(systemPath + moduleName + ".service"); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(serviceFile); fileOutputStream.write(serviceContent.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("写入service文件完成"); try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } System.out.println("开始写入xml文件"); XmlUtils.writeXmlFile(new ModuleData(moduleName, moduleName, moduleInstallPath.toString(), moduleInstallPath + File.separator + moduleName + ".log")); } private static String buildServiceContent(String moduleName, String javaPath, String jarPath, String vmArgs) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Unit]\nDescription="); stringBuilder.append(moduleName); stringBuilder.append("\nAfter=syslog.target network.target"); stringBuilder.append("\n[Service]\nType=simple"); stringBuilder.append("\nExecStart="); stringBuilder.append(javaPath); stringBuilder.append(" -jar "); stringBuilder.append(vmArgs); stringBuilder.append(" "); stringBuilder.append(jarPath); stringBuilder.append("\nExecStop=/bin/kill -15 $MAINPID"); stringBuilder.append("\nUser=root\nGroup=root\n[Install]\nWantedBy=multi-user.target"); return stringBuilder.toString(); } }
2846109ef910f80ab012b240a7935d6933a85035
dedaa35fa1887478fa2814458554ea97263a95ba
/app/src/main/java/com/example/thecoffeehouse/order/hightlight/IHighLightDrinks.java
2a6d4b8567dd78f5c48767fd4417d6a93ece3448
[]
no_license
longdratech/coffee
1787e4ba173af07772e442c8dec7a647a9912b57
e31c31632aae3df773f8fce890c2af7886dd8c95
refs/heads/master
2022-07-14T10:06:19.358034
2020-04-01T17:04:34
2020-04-01T17:04:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
118
java
package com.example.thecoffeehouse.order.hightlight; public interface IHighLightDrinks { void getProduct(); }
[ "" ]
ed1722a670147a7e778beb966714cd6b12cf7a9f
feb496b375d31a13691ffe9e53516f8e263e70c1
/ethereum/eth/src/test/java/tech/pegasys/pantheon/ethereum/eth/sync/fullsync/IncrementerTest.java
91b35ee0ba310bdc5c413cbb09351bbcd3f57ce9
[ "Apache-2.0" ]
permissive
jacobhackman/pantheon
a2f0c406893bef0ea45ccef6f370733b90752269
b577b36afdf77b852d4c0d77eb59552f7697e399
refs/heads/master
2020-05-17T19:17:08.431034
2019-04-28T02:28:26
2019-04-28T02:28:26
183,910,902
0
0
Apache-2.0
2019-04-28T13:19:36
2019-04-28T13:19:36
null
UTF-8
Java
false
false
6,633
java
/* * Copyright 2019 ConsenSys AG. * * 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 tech.pegasys.pantheon.ethereum.eth.sync.fullsync; import static org.assertj.core.api.Assertions.assertThat; import tech.pegasys.pantheon.ethereum.ProtocolContext; import tech.pegasys.pantheon.ethereum.chain.Blockchain; import tech.pegasys.pantheon.ethereum.chain.MutableBlockchain; import tech.pegasys.pantheon.ethereum.eth.manager.EthContext; import tech.pegasys.pantheon.ethereum.eth.manager.EthProtocolManager; import tech.pegasys.pantheon.ethereum.eth.manager.EthProtocolManagerTestUtil; import tech.pegasys.pantheon.ethereum.eth.manager.EthScheduler; import tech.pegasys.pantheon.ethereum.eth.manager.RespondingEthPeer; import tech.pegasys.pantheon.ethereum.eth.manager.ethtaskutils.BlockchainSetupUtil; import tech.pegasys.pantheon.ethereum.eth.sync.ChainDownloader; import tech.pegasys.pantheon.ethereum.eth.sync.SynchronizerConfiguration; import tech.pegasys.pantheon.ethereum.eth.sync.state.SyncState; import tech.pegasys.pantheon.ethereum.mainnet.ProtocolSchedule; import tech.pegasys.pantheon.metrics.MetricCategory; import tech.pegasys.pantheon.metrics.MetricsSystem; import tech.pegasys.pantheon.metrics.Observation; import tech.pegasys.pantheon.metrics.noop.NoOpMetricsSystem; import tech.pegasys.pantheon.metrics.prometheus.MetricsConfiguration; import tech.pegasys.pantheon.metrics.prometheus.PrometheusMetricsSystem; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.junit.Test; public class IncrementerTest { private final MetricsConfiguration metricsConfiguration = MetricsConfiguration.createDefault(); private ProtocolSchedule<Void> protocolSchedule; private EthContext ethContext; private ProtocolContext<Void> protocolContext; private SyncState syncState; private MutableBlockchain localBlockchain; private MetricsSystem metricsSystem; private EthProtocolManager ethProtocolManager; private Blockchain otherBlockchain; private long targetBlock; @Before public void setUp() { metricsConfiguration.setEnabled(true); metricsSystem = PrometheusMetricsSystem.init(metricsConfiguration); final BlockchainSetupUtil<Void> localBlockchainSetup = BlockchainSetupUtil.forTesting(); localBlockchain = localBlockchainSetup.getBlockchain(); final BlockchainSetupUtil<Void> otherBlockchainSetup = BlockchainSetupUtil.forTesting(); otherBlockchain = otherBlockchainSetup.getBlockchain(); protocolSchedule = localBlockchainSetup.getProtocolSchedule(); protocolContext = localBlockchainSetup.getProtocolContext(); ethProtocolManager = EthProtocolManagerTestUtil.create( localBlockchain, localBlockchainSetup.getWorldArchive(), new EthScheduler(1, 1, 1, new NoOpMetricsSystem())); ethContext = ethProtocolManager.ethContext(); syncState = new SyncState(protocolContext.getBlockchain(), ethContext.getEthPeers()); otherBlockchainSetup.importFirstBlocks(15); targetBlock = otherBlockchain.getChainHeadBlockNumber(); // Sanity check assertThat(targetBlock).isGreaterThan(localBlockchain.getChainHeadBlockNumber()); } @After public void tearDown() { ethProtocolManager.stop(); } @Test public void parallelDownloadPipelineCounterShouldIncrement() { final RespondingEthPeer peer = EthProtocolManagerTestUtil.createPeer(ethProtocolManager, otherBlockchain); final RespondingEthPeer.Responder responder = RespondingEthPeer.blockchainResponder(otherBlockchain); final SynchronizerConfiguration syncConfig = SynchronizerConfiguration.builder().downloaderChainSegmentSize(10).build(); final ChainDownloader downloader = downloader(syncConfig); downloader.start(); peer.respondWhileOtherThreadsWork(responder, () -> !syncState.syncTarget().isPresent()); assertThat(syncState.syncTarget()).isPresent(); assertThat(syncState.syncTarget().get().peer()).isEqualTo(peer.getEthPeer()); peer.respondWhileOtherThreadsWork( responder, () -> localBlockchain.getChainHeadBlockNumber() < targetBlock); assertThat(localBlockchain.getChainHeadBlockNumber()).isEqualTo(targetBlock); final List<Observation> metrics = metricsSystem.getMetrics(MetricCategory.SYNCHRONIZER).collect(Collectors.toList()); // the first iteration gets the genesis block, which results in no data // being passed downstream. So observed value is 2. final Observation headerInboundObservation = new Observation( MetricCategory.SYNCHRONIZER, "inboundQueueCounter", 2.0, Collections.singletonList("ParallelDownloadHeadersTask")); final Observation headerOutboundObservation = new Observation( MetricCategory.SYNCHRONIZER, "outboundQueueCounter", 1.0, Collections.singletonList("ParallelDownloadHeadersTask")); assertThat(metrics).contains(headerInboundObservation, headerOutboundObservation); for (final String label : Arrays.asList( "ParallelValidateHeadersTask", "ParallelDownloadBodiesTask", "ParallelExtractTxSignaturesTask", "ParallelValidateAndImportBodiesTask")) { final Observation inboundObservation = new Observation( MetricCategory.SYNCHRONIZER, "inboundQueueCounter", 1.0, Collections.singletonList(label)); final Observation outboundObservation = new Observation( MetricCategory.SYNCHRONIZER, "outboundQueueCounter", 1.0, Collections.singletonList(label)); assertThat(metrics).contains(inboundObservation, outboundObservation); } } private ChainDownloader downloader(final SynchronizerConfiguration syncConfig) { return FullSyncChainDownloader.create( syncConfig, protocolSchedule, protocolContext, ethContext, syncState, metricsSystem); } }
9e77a124a631a66f58737d715a7b0cf2b29c67f8
1c2c42d0d4b6b4ceb8c168cbf70850a6c9932c6c
/src/BazaDanych.java
9a2ccd74a8351f3b5c894ad992646d98ac56e561
[]
no_license
rafau300/BiuroPosrednictwaNieruchomosci
8d992fcc6f7da64fbb0df96d816783302465b407
c1585ef31b5e127eb30231480ffa69fc3fae6c77
refs/heads/master
2016-09-08T02:33:40.942509
2014-06-16T21:14:56
2014-06-16T21:14:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,069
java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; /** * Klasa pozwalajaca na edycje i wyswietlanie danych zawartych w bazie danych projektu, * wywolanie konstruktora tej klasy tworzy nowe polaczenie z baza danych * @author Rafal Bebenek */ public class BazaDanych { public static String polaczenie = new String(); static Connection con; static int liczbaKlientow; static int liczbaNieruchomosci; /** * Konstruktor klasy BazaDanych - laczy sie z baza danych. */ public BazaDanych() { //BazaDanych baza = new BazaDanych(); //Thread watekLaczacy = new Thread(new Runnable() {// tworzenie nowego watku // public void run() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe","hr","hr"); polaczenie = con.toString(); System.out.println("Polaczono z: " + con); //this.wyswietlKlientow("SELECT * FROM klient",new String[50],new String[50]); //this.wyswietlNieruchomosci("SELECT * FROM nieruchomosc", new String[50],new String[50],new int[50]); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // } //}); //watekLaczacy.start(); } /** * Ta metoda pozwala na wyswietlenie klientow za pomoca podanego skryptu * @param skrypt Skrypt SQL, np SELECT * FROM klient * @param imie tablica imion * @param nazwisko tablica nazwisk */ public void wyswietlKlientow(String skrypt, String[] imie, String[] nazwisko) { int i = 1; try { Statement stmt; stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(skrypt); while (rs.next()) { imie[i] = rs.getString("imie"); nazwisko[i] = rs.getString("nazwisko"); //System.out.println(imie[i] + " " + nazwisko[i]); i++; } liczbaKlientow = i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Metoda pozwalajaca na zwrocenie poprzez parametr szczegolowych danych klienta * @param id ID klienta * @param dane Szczegolowe dane * @param kolumny Nazwy kolumn, np. nazwisko */ public void wyswietlSzczegoloweDaneKlienta(int id, String[] dane, String[] kolumny) { int i; try { Statement stmt; stmt = con.createStatement(); String skrypt = "SELECT * FROM klient WHERE id=" + id; ResultSet rs = stmt.executeQuery(skrypt); rs.next(); for (i=1;i<10;i++) { dane[i] = rs.getString(i); ResultSetMetaData rsmd = rs.getMetaData(); kolumny[i] = rsmd.getColumnName(i); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Ta metoda pozwala na wybranie z bazy danych informacji na temat nieruchomosci * @param skrypt skrypt SQL, np. SELECT * FROM nieruchomosc WHERE miejscowosc='Kielce' * @param miejscowosc tablica miejscowosci * @param ulica tablica ulic * @param cena tablica cen */ public void wyswietlNieruchomosci(String skrypt, String[] miejscowosc, String[] ulica, int[] cena) { int i = 1; try { Statement stmt; stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(skrypt); while (rs.next()) { miejscowosc[i] = rs.getString("miejscowosc"); ulica[i] = rs.getString("ulica"); cena[i] = rs.getInt("cena"); //System.out.println(miejscowosc[i] + " " + ulica[i] + " - " + cena[i] + " zl"); i++; } liczbaNieruchomosci = i; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Metoda, ktora pozwala na zwrocenie poprzez parametry szczegolowych danych konkretnej nieruchomosci * @param id ID nieruchomosci * @param dane Dane nieruchomosci * @param kolumny Nazwy kolumn, np. cena */ public void wyswietlSzczegoloweDaneNieruchomosci(int id, String[] dane, String[] kolumny) { int i; try { Statement stmt; stmt = con.createStatement(); String skrypt = "SELECT * FROM nieruchomosc WHERE id=" + id; ResultSet rs = stmt.executeQuery(skrypt); rs.next(); for (i=1;i<11;i++) { dane[i] = rs.getString(i); ResultSetMetaData rsmd = rs.getMetaData(); kolumny[i] = rsmd.getColumnName(i); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Metoda, ktora pozwala na dodanie klienta lub nieruchomosci do bazy danych * @param skrypt Skrypt SQL, np. INSERT INTO klient VALUES ... */ public void insert(String skrypt) { try { Statement stmt; stmt = con.createStatement(); stmt.executeUpdate(skrypt); //System.out.println(">>Wykonano: " + skrypt); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Metoda, ktora pozwala na zakupienie nieruchomosci przez klienta. * Zmienia ID wlasciciela. * @param idKlienta ID klienta * @param idNieruchomosci ID nieruchomosci */ public void zakupNieruchomosci(int idKlienta, int idNieruchomosci) { try { Statement stmt; stmt = con.createStatement(); String skrypt = "UPDATE nieruchomosc SET id_wlasciciela=" + idKlienta + " WHERE id=" + idNieruchomosci; stmt.executeUpdate(skrypt); //System.out.println(">>Wykonano: " + skrypt); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Zamkniecie polaczenia z baza danych */ public void zamknijPolaczenie() { //try { // con.close(); //} catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); //} //System.out.println(">>>> Pomyslnie zamknieto polaczenie: " + polaczenie + " <<<<"); } }
a0b53fd85cb80ba47bedf9d7a1e35935391b83f9
0adcb787c2d7b3bbf81f066526b49653f9c8db40
/src/main/java/com/alipay/api/domain/AlipayOpenAuthTokenAppQueryModel.java
6c2be7d60d5a20e5ffb15b9a1555e8e34dfb42df
[ "Apache-2.0" ]
permissive
yikey/alipay-sdk-java-all
1cdca570c1184778c6f3cad16fe0bcb6e02d2484
91d84898512c5a4b29c707b0d8d0cd972610b79b
refs/heads/master
2020-05-22T13:40:11.064476
2019-04-11T14:11:02
2019-04-11T14:11:02
186,365,665
1
0
null
2019-05-13T07:16:09
2019-05-13T07:16:08
null
UTF-8
Java
false
false
728
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 查询某个ISV下的指定app_auth_token的授权信息:授权者、授权接口列表、状态、过期时间等 * * @author auto create * @since 1.0, 2016-07-18 13:35:47 */ public class AlipayOpenAuthTokenAppQueryModel extends AlipayObject { private static final long serialVersionUID = 7667141721743838837L; /** * 应用授权令牌 */ @ApiField("app_auth_token") private String appAuthToken; public String getAppAuthToken() { return this.appAuthToken; } public void setAppAuthToken(String appAuthToken) { this.appAuthToken = appAuthToken; } }
92ad1aa5114faba3f88275fe7b4d2d15846a154e
4ef431684e518b07288e8b8bdebbcfbe35f364e4
/BTMatcher/test-core/src/main/java/com/ca/apm/tests/role/WLSAgentAppDeployRole.java
c4d35a1dbbf0170991c5ad5e75431bfc012a079b
[]
no_license
Sarojkswain/APMAutomation
a37c59aade283b079284cb0a8d3cbbf79f3480e3
15659ce9a0030c2e9e5b992040e05311fff713be
refs/heads/master
2020-03-30T00:43:23.925740
2018-09-27T23:42:04
2018-09-27T23:42:04
150,540,177
0
0
null
null
null
null
UTF-8
Java
false
false
17,782
java
package com.ca.apm.tests.role; import java.net.Socket; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.eclipse.aether.artifact.DefaultArtifact; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ca.apm.automation.action.flow.commandline.RunCommandFlowContext; import com.ca.apm.automation.action.flow.utility.FileCreatorFlow; import com.ca.apm.automation.action.flow.utility.FileCreatorFlowContext; import com.ca.apm.automation.action.flow.utility.FileModifierFlow; import com.ca.apm.automation.action.flow.utility.FileModifierFlowContext; import com.ca.apm.automation.action.flow.utility.GenericFlow; import com.ca.apm.automation.action.flow.utility.GenericFlowContext; import com.ca.tas.builder.BuilderBase; import com.ca.tas.client.IAutomationAgentClient; import com.ca.tas.resolver.ITasResolver; import com.ca.tas.role.AbstractRole; import com.ca.tas.role.EmRole; import com.ca.tas.role.webapp.JavaRole; public class WLSAgentAppDeployRole extends AbstractRole { private static final Logger LOGGER = LoggerFactory.getLogger(WLSAgentAppDeployRole.class); private ITasResolver tasResolver; private String roleId; private String wlsRole; private boolean isLegacyMode; private boolean isJassEnabled; private String classifier; private String serverPort; private JavaRole javaRole; private String agentVersion; private String emHost; public static final String WLS_START_ENV_KEY = "wlsstart"; public static final String WLS_STOP_ENV_KEY = "wlsstop"; private static final String SEPARATOR = "\\\\"; private static final String DEPLOY_BASE = "C:" + SEPARATOR + "automation" + SEPARATOR + "deployed" + SEPARATOR; private static final String WLS12C_INSTALL_HOME = DEPLOY_BASE + "Oracle" + SEPARATOR + "Middleware12.1.3"; private static final String PO_DOMAIN_HOME = DEPLOY_BASE + "webapp" + SEPARATOR + "pipeorgandomain"; private static final String ALT_START_SCRIPT = "startWebLogicInWindow.cmd"; private static final String DATABASE_JDBC_URL = "jdbc:oracle:thin:@jass6:1521:AUTO"; private static final String DATABASE_DRIVER_NAME = "oracle.jdbc.xa.client.OracleXADataSource"; private static final String DATABASE_USER_NAME = "AUTOMATION"; private static final String DATABASE_JDBC_NAME = "jdbc:oracle:thin:@jass6:1521:AUTO"; private static final String DATABASE_ENCRYPTED_USER_PASSWORD = "AUTOMATION"; private static final String DATABASE_KEEPALIVE_QUERY = "SQL SELECT 1 FROM dual"; private static final String START_MATCH_TEXT = "WLS started"; protected WLSAgentAppDeployRole(Builder builder) { super(builder.roleId); this.roleId = builder.roleId; this.wlsRole = builder.wlsRole; this.tasResolver = builder.tasResolver; this.classifier = builder.classifier; this.serverPort = builder.serverPort; this.isLegacyMode = builder.isLegacyMode; this.isJassEnabled = builder.isJassEnabled; this.javaRole = builder.javaRole; this.agentVersion = builder.agentVersion; this.emHost=builder.emHost; } @Override public void deploy(IAutomationAgentClient aaClient) { deployArtifacts(aaClient); updatePODomainConfig(aaClient); updatePODomainJDBC(aaClient); updatePODomainstartRootWLSCMD(aaClient); updatePODomainsetDomainEnv(aaClient); updatePODomainStartWLSCMD(aaClient); updatePODomainStopWLSCMD(aaClient); updateCrossJVMTracing(aaClient); startPODomain(aaClient); } private void startPODomain(IAutomationAgentClient aaClient) { RunCommandFlowContext ctx = new RunCommandFlowContext.Builder(ALT_START_SCRIPT) .workDir(PO_DOMAIN_HOME).doNotPrependWorkingDirectory() .terminateOnMatch(START_MATCH_TEXT) .build(); runCommandFlow(aaClient, ctx); synchronized (this) { // FIXME - startWebLogic.cmd does not write any output that we can monitor // rewrite the start scripts to not redirect output. For now, just wait // up to 10 minutes for the server to have time to start. When it connects // on the configured port, consider the server as started waitForWebLogicStart(); } } private void waitForWebLogicStart() { String wlsHost = tasResolver.getHostnameById(roleId); long timeout = System.currentTimeMillis() + 600000L; boolean started = false; while (!started && System.currentTimeMillis() < timeout) { try { Socket s = new Socket(wlsHost, Integer.parseInt(serverPort)); s.close(); break; } catch (Exception e) { // if no connection is made to WLS, an exception is thrown, which we don't care about } try { synchronized (this) { wait(10000L); } } catch (Exception e) { // do nothing } } } private void deployArtifacts(IAutomationAgentClient aaClient) { GenericFlowContext context = null; LOGGER.info("Deploying Artifacts..."); //get po domain file context = new GenericFlowContext.Builder() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.binaries.weblogic", "pipeorgandomain", "zip", "10.3"))) .destination(codifyPath(PO_DOMAIN_HOME)) .build(); runFlow(aaClient, GenericFlow.class, context); //get po ejb3 jar file context = new GenericFlowContext.Builder() .notArchive() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.coda-projects.test-tools.pipeorgan", "pipeorgan_ear_ejb3", "ear", tasResolver.getDefaultVersion()))) .destination(codifyPath(PO_DOMAIN_HOME + "/applications/pipeorgan.wls.ejb3.ear")) .build(); runFlow(aaClient, GenericFlow.class, context); //get po jar file context = new GenericFlowContext.Builder() .notArchive() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.coda-projects.test-tools.pipeorgan", "pipeorgan", "jar", tasResolver.getDefaultVersion()))) .destination(codifyPath(PO_DOMAIN_HOME + "/pipeorgan/pipeorgan.jar")) .build(); runFlow(aaClient, GenericFlow.class, context); //get qatestapp ear context = new GenericFlowContext.Builder() .notArchive() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.coda-projects.test-tools", "qatestapp", classifier, "ear", tasResolver.getDefaultVersion()))) .destination(codifyPath(PO_DOMAIN_HOME + "/applications/QATestApp.ear")) .build(); runFlow(aaClient, GenericFlow.class, context); LOGGER.info("Deploying Weblogic Agent."); String artifact = "agent-noinstaller-weblogic-windows"; if(isLegacyMode) { artifact = "agent-legacy-noinstaller-weblogic-windows"; } //get weblogic agent context = new GenericFlowContext.Builder() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.delivery", artifact, "zip", agentVersion))) .destination(codifyPath(PO_DOMAIN_HOME)) .build(); runFlow(aaClient, GenericFlow.class, context); if (isJassEnabled){ //get DITestAppJass agent context = new GenericFlowContext.Builder() .notArchive() .artifactUrl(tasResolver.getArtifactUrl(new DefaultArtifact("com.ca.apm.coda-projects.test-tools", "ditestappjass", "dist", "war", tasResolver.getDefaultVersion()))) .destination(codifyPath(PO_DOMAIN_HOME + "/autodeploy/DITestAppJass.war")) .build(); runFlow(aaClient, GenericFlow.class, context); } } private void updatePODomainConfig(IAutomationAgentClient aaClient) { FileModifierFlowContext context = null; Map<String,String> replacePairs = new HashMap<String,String>(); replacePairs.put("\\[WEBLOGIC.SERVER.PORT\\]", serverPort); replacePairs.put("\\[WEBLOGIC.SERVER.HOST\\]", tasResolver.getHostnameById(wlsRole)); String fileName = PO_DOMAIN_HOME + "/config/config.xml"; // replacing values context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } private void updatePODomainJDBC(IAutomationAgentClient aaClient) { FileModifierFlowContext context = null; Map<String, String> replacePairs = new HashMap<String,String>(); replacePairs.put("\\[DATABASE.JDBC.URL\\]", DATABASE_JDBC_URL); replacePairs.put("\\[DATABASE.DRIVER.NAME\\]", DATABASE_DRIVER_NAME); replacePairs.put("\\[DATABASE.USER.NAME\\]",DATABASE_USER_NAME); replacePairs.put("\\[DATABASE.JDBC.NAME\\]", DATABASE_JDBC_NAME); replacePairs.put("\\[DATABASE.ENCRYPTED.USER.PASSWORD\\]", DATABASE_ENCRYPTED_USER_PASSWORD); replacePairs.put("\\[DATABASE.KEEPALIVE.QUERY\\]", DATABASE_KEEPALIVE_QUERY); String fileName = PO_DOMAIN_HOME + "/config/jdbc/pipeorgan-jdbc.xml"; // replacing values context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } private void updatePODomainstartRootWLSCMD(IAutomationAgentClient aaClient) { Map<String, String> replacePairs = new HashMap<>(1); replacePairs.put("\\[DOMAIN.HOME.DIR\\]", PO_DOMAIN_HOME ); String fileName = PO_DOMAIN_HOME + "/startWebLogic.cmd"; FileModifierFlowContext context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } private void updatePODomainsetDomainEnv(IAutomationAgentClient aaClient) { Map<String, String> replacePairs = new HashMap<>(10); replacePairs.put("\\[WLS.HOME\\]", WLS12C_INSTALL_HOME + "/wlserver"); replacePairs.put("\\[JAVA.HOME\\]", codifyPath(javaRole.getInstallDir())); replacePairs.put("\\[DOMAIN.HOME.DIR\\]", PO_DOMAIN_HOME ); replacePairs.put("-Xms\\[MIN.HEAP.SIZE\\]m -Xmx\\[MAX.HEAP.SIZE\\]m","-Xms512m -Xmx752m"); replacePairs.put("\\[PERM.SPACE.SIZE\\]","50"); replacePairs.put("\\[MAX.PERM.SPACE.SIZE\\]","200"); replacePairs.put("\\[RESULTS.OUTPUT.DIR\\]",PO_DOMAIN_HOME); replacePairs.put("set WLS_STDOUT_LOG", "REM Disable redirection to avoid filling disks with useless drivel.\n" + "REM set WLS_STDOUT_LOG"); replacePairs.put("set WLS_STDERR_LOG", "REM Disable redirection to avoid filling disks with useless drivel.\n" + "REM set WLS_STDERR_LOG"); String fileName = PO_DOMAIN_HOME + "/bin/setDomainEnv.cmd"; FileModifierFlowContext context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } private void updatePODomainStartWLSCMD(IAutomationAgentClient aaClient) { FileModifierFlowContext context = null; Map<String, String> replacePairs = new HashMap<String,String>(); replacePairs.put("\\[DOMAIN.HOME.DIR\\]", PO_DOMAIN_HOME ); replacePairs.put("WILY_AGENT_ENABLED=false", "WILY_AGENT_ENABLED=true"); replacePairs.put("\\[AGENT.JAVA.OPTIONS\\]","-Dweblogic.TracingEnabled=true -javaagent\\:" + PO_DOMAIN_HOME + "/wily/Agent.jar" + " -Dcom.wily.introscope.agentProfile=" + PO_DOMAIN_HOME + "/wily/core/config/IntroscopeAgent.profile" ); replacePairs.put("\\[AGENT.JAVA.CLASSPATH\\]", PO_DOMAIN_HOME + "/wily/common/WebAppSupport.jar"); replacePairs.put("\\[WLS.LOG.OUTPUT\\]", PO_DOMAIN_HOME + "/WebLogicConsole.log"); replacePairs.put("\\[OTHER.JAVA.OPTIONS\\]",""); replacePairs.put("\\[HEAPMONITOR.JAR\\]",""); String fileName = PO_DOMAIN_HOME + "/bin/startWebLogic.cmd"; context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); List<String> appendLines = Arrays.asList(new String[] { "START \"WLS Rulez\" startWebLogic.cmd", "echo " + START_MATCH_TEXT }); FileCreatorFlowContext createContext = new FileCreatorFlowContext.Builder() .destinationFilename(ALT_START_SCRIPT) .destinationDir(PO_DOMAIN_HOME) .fromData(appendLines) .build(); runFlow(aaClient, FileCreatorFlow.class, createContext); } private void updatePODomainStopWLSCMD(IAutomationAgentClient aaClient) { FileModifierFlowContext context = null; Map<String, String> replacePairs = new HashMap<String,String>(); replacePairs.put("\\[DOMAIN.HOME.DIR\\]", PO_DOMAIN_HOME ); replacePairs.put("\\[WEBLOGIC.SERVER.HOST\\]", tasResolver.getHostnameById(wlsRole)); replacePairs.put("\\[WEBLOGIC.SERVER.PORT\\]", serverPort); replacePairs.put("'%SERVER_NAME%','Server'", "'%SERVER_NAME%','Server',ignoreSessions='true',force='true'"); String fileName = PO_DOMAIN_HOME + "/bin/stopWebLogic.cmd"; context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } private void updateCrossJVMTracing(IAutomationAgentClient aaClient) { FileModifierFlowContext context = null; Map<String, String> replacePairs = new HashMap<String,String>(); String prop="agentManager.url.1="+emHost+":5001"; replacePairs.put("#introscope.agent.weblogic.crossjvm=true", "introscope.agent.weblogic.crossjvm=true" ); replacePairs.put("agentManager.url.1=localhost:5001", prop); String fileName = PO_DOMAIN_HOME + "/wily/core/config/IntroscopeAgent.profile"; context = new FileModifierFlowContext.Builder() .replace(fileName, replacePairs) .build(); runFlow(aaClient, FileModifierFlow.class, context); } @NotNull protected String codifyPath(String path) { return FilenameUtils.separatorsToUnix(path); } public static class Builder extends BuilderBase<Builder, WLSAgentAppDeployRole> { private final String roleId; private final ITasResolver tasResolver; protected String appserverDir; protected String wlsRole; protected String serverName; protected String classifier; protected String serverPort; protected boolean isLegacyMode; protected boolean isJassEnabled; protected JavaRole javaRole; protected String agentVersion; protected String emHost; public Builder(String roleId, ITasResolver tasResolver) { this.roleId = roleId; this.tasResolver = tasResolver; } @Override public WLSAgentAppDeployRole build() { return getInstance(); } @Override protected WLSAgentAppDeployRole getInstance() { return new WLSAgentAppDeployRole(this); } @Override protected Builder builder() { return this; } public Builder appserverDir(String appserverDir) { this.appserverDir = appserverDir; return builder(); } public Builder wlsRole(String wlsRole) { this.wlsRole = wlsRole; return builder(); } public Builder serverName(String serverName) { this.serverName = serverName; return builder(); } public Builder classifier(String classifier) { this.classifier = classifier; return builder(); } public Builder serverPort(String serverPort) { this.serverPort = serverPort; return builder(); } public Builder isLegacyMode(boolean isLegacyMode) { this.isLegacyMode = isLegacyMode; return builder(); } public Builder isJassEnabled(boolean isJassEnabled) { this.isJassEnabled = isJassEnabled; return builder(); } public Builder javaRole(JavaRole javaRole) { this.javaRole = javaRole; return builder(); } public Builder emHost(String emHost2) { this.emHost = emHost2; return builder(); } public Builder agentVersion(String agentVersion) { this.agentVersion = agentVersion; return builder(); } } }
af6805a48bd9dd65941c79825bee455e8c5a4c36
5256450a88b151bf855360470a7f77148f89edf8
/app-gateway/src/main/java/com/babeeta/hudee/gateway/app/service/SubscriptionService.java
79b8aad3f9b67ea64787643245527e489aba60ac
[]
no_license
zhaom/broadcast-simple
cc57054e0c396d4a50807a7acaa99b12f8512604
f2a3c58ccab9db5db88df1a87c27b0f3de252906
refs/heads/master
2021-01-10T01:45:59.823368
2016-03-25T06:52:16
2016-03-25T06:52:16
54,538,358
0
0
null
null
null
null
UTF-8
Java
false
false
5,974
java
package com.babeeta.hudee.gateway.app.service; import java.util.Date; import java.util.List; import net.sf.json.JSONArray; import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * implement the interface of authenticate service */ public class SubscriptionService extends AbstractHttpRPCService { private static final Logger logger = LoggerFactory .getLogger(SubscriptionService.class); private final String domain; private static String queryPattern = "/1/api/subscription/query/%s/%s"; private static String createGroupTaskPattern = "/1/api/subscription/tags/list?aid=%s&stamp=%s&life=0"; private static String checkTaskPattern = "/1/api/subscription/tags/count?key=%s"; private static String getResultPattern = "/1/api/subscription/tags/result?key=%s&pageSize=%d&pageIndex=%d"; /** * Constructor * * @param maxConnection * max connection limit * * @param domain * subscription service domain */ public SubscriptionService(int maxConnection, String domain) { super(maxConnection); this.domain = domain; } private interface Callback { String doIt(); } private String execute(Callback callback) { return callback.doIt(); } private interface CallbackLong { long doIt(); } private long execute(CallbackLong callback) { return callback.doIt(); } /** * Query did by aid and cid * * @param aid * application id * @param cid * client id * @return return device id if subscription of aid and cid exists, otherwise * return null */ public String getDeviceId(final String aid, final String cid) { String ret = execute(new Callback() { @Override public String doIt() { return queryDeviceId(aid, cid); } }); return ret; } /** * Create a query task for a group described by tag expression * * @param aid * application id * @param tagExpression * tag expression * @return key of task or null */ public String createGroupTask(final String aid, final String tagExpression) { String ret = execute(new Callback() { @Override public String doIt() { return createGroup(aid, tagExpression, new Date().getTime()); } }); return ret; } /** * @param key * task key * @return count of group if task finished */ public long checkGroupTask(final String key) { long ret = execute(new CallbackLong() { @Override public long doIt() { return checkTask(key); } }); return ret; } /** * Get query task result * * @param key * task key * @param pageSize * page size * @param pageIndex * page index * @return a list of device key or null */ public List<String> getTaskResult(final String key, final int pageSize, final int pageIndex) { String ret = execute(new Callback() { @Override public String doIt() { return queryTaskResult(key, pageIndex, pageSize); } }); if (ret != null) { JSONArray obj = JSONArray.fromObject(ret); @SuppressWarnings("unchecked") List<String> list = (List<String>) JSONArray.toCollection(obj, String.class); return list; } return null; } private String queryDeviceId(final String aid, final String cid) { HttpRPCResult result = invokeGet( composeURI(domain, String.format(queryPattern, aid, cid)), HttpStatus.SC_OK); String retResult = null; if (result.getStatusCode() == HttpStatus.SC_OK) { String returnStr = new String(result.getPayload()); if (returnStr != null && returnStr.length() > 0 && returnStr.length() == 32) { retResult = returnStr; } else { logger.error("[RPC-queryDid] Fatal error! Remote return null."); } } else { logger.error( "[RPC-queryDid] failed! statusCode: {}; message: {}", result.getStatusCode(), result.getMessage()); } return retResult; } private String createGroup(final String aid, final String tagExpression, final long stamp) { HttpRPCResult result = invokePost(composeURI(domain, String.format(createGroupTaskPattern, aid, stamp)), null, tagExpression.getBytes(), HttpStatus.SC_OK); String retResult = null; if (result.getStatusCode() == HttpStatus.SC_OK) { String returnStr = new String(result.getPayload()); if (returnStr != null && returnStr.length() > 0 && returnStr.length() == 32) { retResult = returnStr; } else { logger.error("[RPC-createGroup] Fatal error! Remote return null."); } } else { logger.error( "[RPC-createGroup] failed! statusCode: {}; message: {}", result.getStatusCode(), result.getMessage()); } return retResult; } private long checkTask(final String key) { HttpRPCResult result = invokeGet(composeURI(domain, String.format(checkTaskPattern, key)), HttpStatus.SC_OK); if (result.getStatusCode() == HttpStatus.SC_OK) { String returnStr = new String(result.getPayload()); return Long.parseLong(returnStr); } else if (result.getStatusCode() == HttpStatus.SC_NOT_FOUND) { return Long.MIN_VALUE; } else { logger.error( "[RPC-checkTask] failed! statusCode: {}; message: {}", result.getStatusCode(), result.getMessage()); } return -1; } private String queryTaskResult(final String key, final int pageIndex, final int pageSize) { HttpRPCResult result = invokeGet( composeURI(domain, String.format(getResultPattern, key, pageSize, pageIndex)), HttpStatus.SC_OK); String retResult = null; if (result.getStatusCode() == HttpStatus.SC_OK) { retResult = new String(result.getPayload()); } else { logger.error( "[RPC-queryDid] failed! statusCode: {}; message: {}", result.getStatusCode(), result.getMessage()); } return retResult; } }
ec1293f5c2f45823c3cbcfc6a38b322dc09701aa
012818837fdd1094e9394c9174f6eea75b028726
/JavaSE_workspace/day13_StringBuffer/src/cn/laoliu_01/StringBufferDemo.java
d8f4f08ecdd7aca01e2123671ed7f471f5d77ca4
[]
no_license
mimicao/Java_Learning
6ba2d31b12120111500900ba7fd43fbec4da1c72
7e259e1bb3515afd6ba095096ec4a26b3c2e7035
refs/heads/master
2021-08-24T18:14:45.938831
2017-11-21T10:53:16
2017-11-21T10:53:16
107,426,448
0
0
null
null
null
null
GB18030
Java
false
false
1,481
java
package cn.laoliu_01; /* * 线程安全 * 安全-- 同步-- 数据是安全的 * 不安全-- 不同步-- 效率高一些 * 安全和效率永远困扰我们的。 * 安全:医院的网站,银行的网站之类的 * 效率:新闻性的网站,论坛之类的 * * StringBuffer: * 线程安全的可变字串 * * StringBuffer和String的区别? * 前者长度和内容可变,后者不变 * 如果使用前者做字符串拼接,不会浪费太多的资源 * * StringBuffer的构造方法 * public StringBuffer(): 无参构造方法 * public StringBuffer(int capacity):指定容量的字符串缓冲区对象 * public StringBuffer(String str):指定字符串内容的字符串缓冲区对象 */ public class StringBufferDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); System.out.println("sb:" + sb); System.out.println("sb capacity:" + sb.capacity()); System.out.println("sb length:" + sb.length()); System.out.println("--------------------------"); StringBuffer sb1 = new StringBuffer(50); System.out.println("sb1:" + sb1); System.out.println("sb1 capacity:" + sb1.capacity()); System.out.println("sb1 length:" + sb1.length()); System.out.println("--------------------------"); StringBuffer sb2 = new StringBuffer("hello"); System.out.println("sb2:" + sb2); System.out.println("sb2 capacity:" + sb2.capacity()); System.out.println("sb2 length:" + sb2.length()); } }
456958f57ab89d9cc8b6bb05b2a12250288471cc
76225194ccdc6b134c0aec1f920edc37b7701681
/src/entities/Task_Prio.java
dcbc4bbc46ed44543d11854efaa4826df31e867f
[]
no_license
DomiBosselmann/Camping
7ad990c4c9b5f23ab20cd216cda21aec8f6982f8
89aa47bb6a5ec5b2ce3be7f9efc436fe13960ace
refs/heads/master
2021-01-01T19:55:05.337469
2013-08-29T14:29:10
2013-08-29T14:29:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
244
java
package entities; public enum Task_Prio { low("Niedrig"), normal("Normal"), high("Hoch"); private final String value; Task_Prio(String value) { this.value = value; } public String toString() { return value; } }
c391152dfced6f379134137200c0d30f12a02dfc
c57fa150c992d5db6f2604ace387eed49549b740
/jesustec-proj1/src/main/java/br/com/jesustec/model/dao/HibernateDAO.java
3aefe4563dbaa0b7f8c8708612f153c7c9a80020
[]
no_license
jesustecprosperity/jesustec-proj1
d414a17a038b6ddd6a7c76d8f2f7637cfaa3ff0e
d1de48075d3ae0067395179014863e5330baaed8
refs/heads/master
2016-09-14T05:22:37.266300
2016-05-16T21:36:13
2016-05-16T21:36:13
57,471,230
0
0
null
null
null
null
UTF-8
Java
false
false
1,556
java
package br.com.jesustec.model.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.DetachedCriteria; public class HibernateDAO<T> implements InterfaceDAO<T>, Serializable { private static final long serialVersionUID = 1L; private Class<T> classe; private Session session; public HibernateDAO(Class<T> classe, Session session) { super(); this.classe = classe; this.session = session; } @Override public void save(T entity) { session.save(entity); } @Override public void update(T entity) { session.update(entity); } @Override public void remove(T entity) { session.delete(entity); } @Override public void merge(T entity) { session.merge(entity); } @Override public T getEntity(Serializable id) { T entity = (T) session.get(classe, id); return entity; } @Override public T getEntityByDetachedCriteria(DetachedCriteria criteria) { T entity = (T) criteria.getExecutableCriteria(session).uniqueResult(); return entity; } @Override public List<T> getListByDetachedCriteria(DetachedCriteria criteria) { return criteria.getExecutableCriteria(session).list(); } @Override public List<T> getEntities() { List<T> enties = (List<T>) session.createCriteria(classe).list(); return enties; } }
38af9571ce66931352e66016bdc55278d20497fa
118ce23763ad3c7e8d4c2f419688505fff0d1e23
/src/main/java/com/amihaiemil/charles/aws/requests/AwsDelete.java
d15db63f58a190940e0296049adfe98eaaf8953c
[]
no_license
mlatagas/charles-rest
bf868db1d41197eaa28a988b4887afe05359ed8c
15520b4aeb1ae5c14dc3c2ebc7ee5cdc8b43050a
refs/heads/master
2021-04-17T14:16:28.998964
2019-11-14T10:37:48
2019-11-14T10:37:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,329
java
/** * Copyright (c) 2016-2017, Mihai Emil Andronache * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1)Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2)Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3)Neither the name of charles-rest nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.amihaiemil.charles.aws.requests; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; /** * Http DELETE request sent to AWS. * @author Mihai Andronache ([email protected]) * @version $Id$ * @since 1.0.0 * */ public final class AwsDelete<T> extends AwsHttpRequest<T> { /** * Base request. */ private AwsHttpRequest<T> base; /** * Ctor. * @param req Base AwsHttpRequest. */ public AwsDelete(AwsHttpRequest<T> req) { this.base = req; this.base.request().setHttpMethod(HttpMethodName.DELETE); } @Override public T perform() { return this.base.perform(); } @Override Request<Void> request() { return this.base.request(); } }
3e7f59effad079347a3022bf4cda1aaffa2e4925
850ebe39040e58d0a47b52f332a3a6b94d307905
/app/src/main/java/com/techuva/iot/model/AccountListInfoObject.java
f233d679ae641e8e91e45cd440aa171b6ca4f6bc
[]
no_license
nikks-tu/IT_TECHUVAIOT_MOBILE
38384a6d5cc1303febdcc82aff81587dc364a636
a52fa495b15bbfec7306340fd0068107176249cf
refs/heads/master
2022-05-25T08:21:34.928384
2020-04-20T14:05:38
2020-04-20T14:05:38
257,299,666
0
0
null
null
null
null
UTF-8
Java
false
false
2,158
java
package com.techuva.iot.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class AccountListInfoObject { @SerializedName("ListCount") @Expose private Integer listCount; @SerializedName("ErrorCode") @Expose private Integer errorCode; @SerializedName("ErrorMessage") @Expose private String errorMessage; @SerializedName("PageNumber") @Expose private Object pageNumber; @SerializedName("PagePerCount") @Expose private Object pagePerCount; @SerializedName("FromRecords") @Expose private Integer fromRecords; @SerializedName("ToRecords") @Expose private Integer toRecords; @SerializedName("TotalRecords") @Expose private Integer totalRecords; public Integer getListCount() { return listCount; } public void setListCount(Integer listCount) { this.listCount = listCount; } public Integer getErrorCode() { return errorCode; } public void setErrorCode(Integer errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public Object getPageNumber() { return pageNumber; } public void setPageNumber(Object pageNumber) { this.pageNumber = pageNumber; } public Object getPagePerCount() { return pagePerCount; } public void setPagePerCount(Object pagePerCount) { this.pagePerCount = pagePerCount; } public Integer getFromRecords() { return fromRecords; } public void setFromRecords(Integer fromRecords) { this.fromRecords = fromRecords; } public Integer getToRecords() { return toRecords; } public void setToRecords(Integer toRecords) { this.toRecords = toRecords; } public Integer getTotalRecords() { return totalRecords; } public void setTotalRecords(Integer totalRecords) { this.totalRecords = totalRecords; } }
[ "nikita@[email protected]" ]
b4e05229f441333849a32686dcb24536f1018707
39338dde50351383050b65a3629d05126906605f
/src/com/soustitres/servlets/EditSubtitle.java
20ee88a70a55a3aaa82649d07d515caa025d0719
[]
no_license
Frenchy31/SousTitres
c342084f6ad4edaaa7c8b518875100fb439151c4
dc4b0ec5500f4b87f0ceac0eedbe45f6afe3174e
refs/heads/master
2020-11-24T21:51:05.953586
2019-12-16T10:06:10
2019-12-16T10:06:10
228,354,839
0
0
null
null
null
null
UTF-8
Java
false
false
6,149
java
package com.soustitres.servlets; import com.soustitres.beans.Paragraphe; import com.soustitres.beans.SousTitre; import com.soustitres.beans.Video; import com.soustitres.dao.*; import com.soustitres.utilities.Utils; import javax.servlet.ServletContext; 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.util.ArrayList; import java.util.HashMap; import java.util.Locale; @WebServlet("/EditSubtitle") public class EditSubtitle extends HttpServlet { private static final long serialVersionUID = 1L; private SousTitreDao sousTitreDao; private DaoFactory daoFactory; private ParagrapheDao paragrapheDao; private VideoDao videoDao; public void init(){ this.daoFactory = DaoFactory.getInstance(); this.videoDao = this.daoFactory.getVideoDao(); this.sousTitreDao = this.daoFactory.getSousTitreDao(); this.paragrapheDao = this.daoFactory.getParagrapheDao(); Locale.setDefault(new Locale("FR")); } //Récupère et gère les données obligatoirement affichées par la page private void affichageParDefaut(HttpServletRequest request) { Video video; SousTitre sousTitre; SousTitre sousTitreTraduit; try { //new SubtitlesHandler(context.getRealPath("/resources/password_presentation.srt"),1, new Locale("FR"), sousTitreDao, paragrapheDao); video = videoDao.getOne(Integer.valueOf(request.getParameter("idVideo"))); sousTitre = sousTitreDao.getOne(Integer.valueOf(request.getParameter("idVideo")), new Locale(request.getParameter("langue"))); request.setAttribute("idVideo", video.getId()); request.setAttribute("titreVideo", video.getNom()); request.setAttribute("langue", sousTitre.getLocale()); request.setAttribute("paragraphes", paragrapheDao.lister(sousTitre.getId())); if(request.getParameter("langueTrad") != null ) { sousTitreTraduit = sousTitreDao.getOne(Integer.valueOf(request.getParameter("idVideo")), new Locale(request.getParameter("langueTrad"))); if(sousTitreTraduit != null) { request.setAttribute("langueTraduction", sousTitre.getLocale().getDisplayLanguage().toLowerCase()); ArrayList<Paragraphe> paragraphesTraduits = paragrapheDao.lister(sousTitreTraduit.getId()); request.setAttribute("paragraphesTraduits", paragraphesTraduits); } } request.setAttribute("locales", Utils.listCountries()); } catch (DaoException e) { request.setAttribute("erreur", e.getMessage()); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ServletContext context = getServletContext(); affichageParDefaut(request); // try { // subtitles = new SubtitlesHandler(context.getRealPath(),1, new Locale("FR"), sousTitreDao, paragrapheDao); // } catch (DaoException e) { // request.setAttribute("erreur", e.getMessage()); // } this.getServletContext().getRequestDispatcher("/WEB-INF/edit_subtitle.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // On récupère et on traite les paramètres envoyés pas le formulaire HashMap<String, String[]> parameters = new HashMap<>(request.getParameterMap()); // On vérifie qu'un sous-titre dans la même langue n'existe pas déjà SousTitre sousTitre = sousTitreDao.getOne(Integer.parseInt(request.getParameter("idVideo")), new Locale(request.getParameter("langueTrad"))); // On retire les champs inutiles des paramètres parameters.remove("idVideo"); parameters.remove("langueTrad"); //Si le sous-titre n'existe, on va gérer la création des nouveaux paragraphes associés if(sousTitre == null){ sousTitre = new SousTitre(Integer.parseInt(request.getParameter("idVideo")), new Locale(request.getParameter("langueTrad"))); Integer newSousTitreId = sousTitreDao.ajouter(sousTitre); traiteAjoutParagraphes(parameters, newSousTitreId); } else{ //Sinon on ne s'occupe que de la mise à jour. ArrayList<Paragraphe> paragraphes = paragrapheDao.lister(sousTitre.getId()) ; traiteUpdateParagraphes(paragraphes, parameters); } } catch (DaoException e) { request.setAttribute("erreur", e.getMessage()); } Video video = null; try { video = videoDao.getOne(Integer.valueOf(request.getParameter("idVideo"))); } catch (DaoException e) { request.setAttribute("erreur", e.getMessage()); } affichageParDefaut(request); this.getServletContext().getRequestDispatcher("/WEB-INF/edit_subtitle.jsp").forward(request, response); } /** * Compare les textes pour gérer ou non la mise à jour de la base * @param paragraphes * @param parameters * @throws DaoException */ private void traiteUpdateParagraphes(ArrayList<Paragraphe> paragraphes, HashMap<String, String[]> parameters) throws DaoException { for(int line = 1 ; line<=paragraphes.size() ; line++){ String keyTexte = "line"+line; if(!String.valueOf(paragraphes.get(line-1).getTexteAffiche()).equals(String.valueOf(parameters.get(keyTexte)[0]))) paragrapheDao.updateTexte(paragraphes.get(line-1), String.valueOf(parameters.get(keyTexte)[0])); } } /** * Créé les nouveaux paragraphes et gère les ajouts dans la base * @param parameters * @param newSousTitreId * @throws DaoException */ private void traiteAjoutParagraphes(HashMap<String, String[]> parameters, Integer newSousTitreId) throws DaoException { for (int line = 1 ; line<=parameters.size()/3 ; line++) { String keyTpsDebut = "tpsDebut"+line; String keyTpsFin = "tpsFin"+line; String keyTexte = "line"+line; Paragraphe paragraphe = new Paragraphe(); paragraphe.setIdSousTitre(newSousTitreId); paragraphe.setNumParagraphe(line); paragraphe.setTempsDebut(parameters.get(keyTpsDebut)[0]); paragraphe.setTempsFin(parameters.get(keyTpsFin)[0]); paragraphe.setTexteAffiche(parameters.get(keyTexte)[0]); paragrapheDao.ajouter(paragraphe); } } }
4c574ac5640e76007ec8114f5a62967e05965fea
01975c626f07f3fd1371ddfae48efc52108dfe9a
/src/org/fernwood/jbasic/JBasicMain.java
1433f8073dde689fb51395d236c03bdd974fb632
[]
no_license
tucats/JBasic
3d1285162430c314c3dffabdf95e8b9afcca90dc
d2bf0b3b06410dbaf2b41a4abee41c9faa3dffb9
refs/heads/master
2022-09-29T08:34:40.827317
2022-09-03T16:33:22
2022-09-03T16:33:22
16,550,357
0
0
null
null
null
null
UTF-8
Java
false
false
10,559
java
/* * THIS SOURCE FILE IS PART OF JBASIC, AN OPEN SOURCE PUBLICLY AVAILABLE * JAVA SOFTWARE PACKAGE HOSTED BY SOURCEFORGE.NET * * THIS SOFTWARE IS PROVIDED VIA THE GNU PUBLIC LICENSE AND IS FREELY * AVAILABLE FOR ANY PURPOSE COMMERCIAL OR OTHERWISE AS LONG AS THE AUTHORSHIP * AND COPYRIGHT INFORMATION IS RETAINED INTACT AND APPROPRIATELY VISIBLE * TO THE END USER. * * SEE THE PROJECT FILE AT HTTP://WWW.SOURCEFORGE.NET/PROJECTS/JBASIC FOR * MORE INFORMATION. * * COPYRIGHT 2003-2011 BY TOM COLE, [email protected] * */ package org.fernwood.jbasic; import org.fernwood.jbasic.runtime.JBasicException; import org.fernwood.jbasic.runtime.SymbolTable; import org.fernwood.jbasic.value.ObjectValue; import org.fernwood.jbasic.value.Value; /** * The main JBasic command line program object. * <p> * This class exists to host an * instance of the main() method, used by the jar load-and-go function of Java. * This performs the following basic tasks: * <p> * <list> * <li>Create and initialize a single instance of a JBasic * <li>Process any command line arguments and store them in the global symbol * table. * <li>Running the MAIN program in the built-in library if it exists. * <li>If the MAIN program didn't execute a command from the command line, run * a console-input loop to read lines and execute them as statements. <list> * <p> * This was factored out of the JBasic object to allow the creation of multiple * JBasic session objects when used within another program in July 2006. * <p> * * @author Tom Cole * @version version 1.0 Jul 4, 2006 * */ public class JBasicMain { /** * Main entry point for JBasic. This is run when JBasic is invoked with the * java invocation for a jar. This sets up the environment for running * JBasic and runs a loop accepting commands from the user and executing * them (to run programs or invoke immediate commands). * * @param args * Standard java argument list for a main program. Contains * statements to be executed by JBasic. */ public static void main(final String args[]) { final JBasic session = new JBasic("JBasic Console"); JBasic.firstSession = session; JBasic.rootTable.session = session; Status status; boolean fWorkspace = true; boolean fInterruptHandler = true; boolean fPreferences = true; boolean fMain = true; boolean fShell = true; boolean fCommand = false; boolean fJavaSession = false; String initialCommand = ""; /* * Set the mode of the JBasic session to reflect that are we * (currently) in single-user mode. This is a readonly * value in the global table after session initialization, * so we cheat and just set the string value directly. */ Value mode = session.globals().localReference("SYS$MODE"); mode.setString("SINGLEUSER"); /* * Create the system arrayValue variable that holds all the program * arguments. */ final Value argArray = new Value(Value.ARRAY, "SYS$ARGS"); /* * If there are arguments to the invocation, then go ahead and store * them away in the SYS$ARGS arrayValue so the MAIN program can process * them if it wishes. Options start with a "-" and are processed here * as well. */ if (args.length > 0) { int i; for (i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { String opt = args[i].substring(1).toLowerCase(); if (opt.equals("sandbox")) session.enableSandbox(true); else if (opt.equals("version")) { fCommand = true; fShell = false; initialCommand = "PRINT $VERSION"; } else if (opt.equals("javasession")) fJavaSession = true; else if(opt.equals("help") || opt.equals("?")) { fCommand = true; fShell = false; initialCommand = "HELP COMMAND LINE"; } else if( opt.equals("server")) { fCommand = true; fShell = true; initialCommand = "SERVER START DETACHED"; } else if (opt.equals("noworkspace") || opt.equals("nows")) fWorkspace = false; else if (opt.equals("nointerrupt") || opt.equals("noint")) fInterruptHandler = false; else if (opt.equals("nopreferences") || opt.equals("noprefs")) fPreferences = false; else if (opt.equals("nomain")) fMain = false; else if (opt.equals("shell")) fShell = true; else if (opt.equals("noshell")) fShell = false; else if (opt.equals("sandbox")) session.enableSandbox(true); else if (opt.equals("command") || opt.equals("cmd") || opt.equals("exec") || opt.equals("e")) { fCommand = true; fShell = false; StringBuffer cmdParts = new StringBuffer(); if( initialCommand.length() > 0 ) cmdParts.append(initialCommand + " : "); for( ++i; i<args.length;i++) { cmdParts.append(' '); cmdParts.append(args[i]); } initialCommand = cmdParts.toString(); break; } else System.out.println(session.getMessage(Status._UNKOPT) + opt); } else argArray.setElement(new Value(args[i]), i + 1); } } session.addEvent("+Command line arguments processed"); /* * After we've collected up the initial command from the command * line parsing operation, store it away as system global for * use by the $MAIN program later. */ try { session.globals().insert("SYS$INITCMD", initialCommand); } catch (JBasicException e1) { e1.print(session); } /* * Save the argument list for user consumption, and mark readonly. */ try { session.globals().insertReadOnly("SYS$ARGS", argArray); } catch (JBasicException e1) { new Status(Status.FAULT, "unable to initialize arguments").print(session); } /* * Create the ABOUT program explicitly. */ final Program aboutProgram = session.initializeAboutProgram(); session.addEvent("+ABOUT initalized"); /* * Load the default workspace, if it exists. */ Status wsts = new Status(); if (fWorkspace) wsts = Loader.loadFile(session, session.getWorkspaceName()); session.addEvent("+Workspace loaded"); /* * Now that we're about to start executing JBasic language statements * let's be sure the user can interrupt them if they go badly... */ if (fInterruptHandler) InterruptHandler.install("INT"); /* * Since this is the "main" program, it has all the permissions on * by default. */ session.setPermission("ALL", true); //session.getUserIdentity().setPermissionMask(); /* * See if we have a program named "$MAIN" at this point. If so, then run * it as the default initialization action. */ if (fMain) try { Value initState = new Value("INIT"); initState.fReadonly = true; final Program mainProgram = session.programs.find(JBasic.PROGRAM + "$MAIN"); if (mainProgram != null) { session.programs.setCurrent(mainProgram); final SymbolTable mainSymbols = new SymbolTable(session, "Local to MAIN", session.globals()); mainSymbols.insertReadOnly("$MODE", initState); mainSymbols.markReadOnly("$MODE"); status = mainProgram.run(mainSymbols, 0, null); session.addEvent("+MAIN completed"); if (status.equals(Status.QUIT)) session.running(false); } else { /* * No main program ever given, so we just run the ABOUT program * we know exists because we created it explicitly. */ final SymbolTable aboutSymbols = new SymbolTable(session, "Local to ABOUT", session.globals()); aboutSymbols.insertReadOnly("$MODE", initState); aboutProgram.run(aboutSymbols, 0, null); session.stdout.println(session.getMessage(Status._NOMAIN)); session.addEvent("+ABOUT completed"); } } catch (JBasicException e) { new Status(Status.FAULT, e.getStatus()).print(session); } /* * If there is a $PREFERENCES program (usually loaded from the default * user work space file) then run that as well. */ try { Program preferencesProgram = null; Value initState = new Value("INIT"); initState.fReadonly = true; if (fPreferences) preferencesProgram = session.programs.find(JBasic.PROGRAM + "$PREFERENCES"); if (preferencesProgram != null) { session.programs.setCurrent(preferencesProgram); final SymbolTable mainSymbols = new SymbolTable(session, "Local to PREFERENCES", session.globals()); mainSymbols.insertReadOnly("$MODE", initState); status = preferencesProgram.run(mainSymbols, 0, null); session.addEvent("+Preferences processed"); if (status.equals(Status.QUIT)) session.running(false); } } catch (JBasicException e) { new Status(Status.FAULT, "error loading preferences").print(session); e.getStatus().print(session); } /* * If we had a successful workspace load, then print * that information now that we're done with the main * program. We don't print this if we are executing * a direct command from the command line. */ if (session.isRunning() & fWorkspace & !fCommand) if (wsts.success()) { System.out.println(session.getMessage(Status._LOADEDWS) + session.getWorkspaceName()); System.out.println(); } /* * Start with no active program, and see what the user wants to do. */ session.programs.setCurrent(null); session.setCurrentProgramName(""); /* * Create a symbol table scope for console commands. This is where * "local" variables created in immediate mode live, for example. */ final SymbolTable consoleSymbols = new SymbolTable(session, "Local to Console", session.globals()); try{ consoleSymbols.insert("$THIS", "Console"); consoleSymbols.insert("$PARENT", "None"); if( fJavaSession ) consoleSymbols.insert("$SESSION", new ObjectValue( session )); } catch (JBasicException e2) { e2.print(session); } /* * If there was an initial command given, use it. If it * results in an error, print the error message to the * console. */ if (fCommand) { status = session.run(initialCommand); session.addEvent("+Initial command completed"); status.printError(session); } /* * Run a command line shell until we grow tired and quit. */ if (fShell) { String prompt = consoleSymbols.getString("SYS$PROMPT"); if( prompt == null) prompt = "SHELL> "; status = session.shell(consoleSymbols, prompt); } /* * If we got into multiuser mode we must tear it down now. */ if (JBasic.telnetDaemon != null) JBasic.telnetDaemon.stop(); } }
ced25eb2a22776ab1ef4534ddd3d5be534e1d3b0
28dd65fcf7ad5a3e51be59039b0046c53b72c0ce
/src/test/java/com/foxminded/university/controllers/rest/ClassRoomsRestControllerSystemTest.java
bbdd01f240bcc4c093b3ce4916f8d35579dcede3
[]
no_license
Alex15265/University
5184759c7f4f4d0800e5662b26fd16f3ae7f18af
467b005b41368cd8584e74feb13f3d262dbc1368
refs/heads/master
2023-02-12T07:07:33.986963
2021-01-10T13:00:27
2021-01-10T13:00:27
328,382,522
0
0
null
null
null
null
UTF-8
Java
false
false
5,690
java
package com.foxminded.university.controllers.rest; import com.fasterxml.jackson.databind.ObjectMapper; import com.foxminded.university.dto.classRoom.ClassRoomDTORequest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest @Sql(value = "/create_tables_for_classrooms.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) public class ClassRoomsRestControllerSystemTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; @Before public void init() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void showAllClassRooms_shouldRetrieveAllClassRoomsFromDB() throws Exception { mockMvc.perform(get("/api/classrooms/")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(jsonPath("$.size()", is(3))) .andExpect(jsonPath("$[0].roomId", is(1))) .andExpect(jsonPath("$[0].roomNumber", is(101))) .andExpect(jsonPath("$[1].roomId", is(2))) .andExpect(jsonPath("$[1].roomNumber", is(102))) .andExpect(jsonPath("$[2].roomId", is(3))) .andExpect(jsonPath("$[2].roomNumber", is(103))); } @Test public void showClassRooms_shouldThrowExceptionOnBadRequest() throws Exception { mockMvc.perform(get("/api/classroo") .contentType(APPLICATION_JSON)) .andExpect(status().is4xxClientError()); } @Test public void showClassRoomByID_shouldRetrieveClassRoomFromDBByID() throws Exception { mockMvc.perform(get("/api/classrooms/2")) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(jsonPath("$.roomId", is(2))) .andExpect(jsonPath("$.roomNumber", is(102))); } @Test public void showClassRoomByID_shouldThrowExceptionOnBadRequest() throws Exception { mockMvc.perform(get("/api/classrooms/{room_id}", "bad_request") .contentType(APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test public void saveClassRoom_shouldAddNewClassRoomToDBAndReturnIt() throws Exception { ClassRoomDTORequest classRoomDTORequest = new ClassRoomDTORequest(); classRoomDTORequest.setRoomNumber(777); mockMvc.perform(post("/api/classrooms/") .content(objectMapper.writeValueAsString(classRoomDTORequest)) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(jsonPath("$.roomId", is(4))) .andExpect(jsonPath("$.roomNumber", is(777))); } @Test public void saveClassRoom_shouldThrowExceptionWhenRequestedWithInvalidParameters() throws Exception { ClassRoomDTORequest classRoomDTORequest = new ClassRoomDTORequest(); classRoomDTORequest.setRoomNumber(-5); mockMvc.perform(post("/api/classrooms/") .content(objectMapper.writeValueAsString(classRoomDTORequest)) .contentType(APPLICATION_JSON)) .andExpect(status().is4xxClientError()); } @Test public void updateClassRoom_shouldUpdateClassRoomByIDInDBAndReturnIt() throws Exception { ClassRoomDTORequest classRoomDTORequest = new ClassRoomDTORequest(); classRoomDTORequest.setRoomNumber(777); mockMvc.perform(patch("/api/classrooms/1") .content(objectMapper.writeValueAsString(classRoomDTORequest)) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON)) .andExpect(jsonPath("$.roomId", is(1))) .andExpect(jsonPath("$.roomNumber", is(777))); } @Test public void updateClassRoom_shouldThrowExceptionWhenRequestedWithInvalidParameters() throws Exception { ClassRoomDTORequest classRoomDTORequest = new ClassRoomDTORequest(); classRoomDTORequest.setRoomNumber(-5); mockMvc.perform(patch("/api/classrooms/2") .content(objectMapper.writeValueAsString(classRoomDTORequest)) .contentType(APPLICATION_JSON)) .andExpect(status().is4xxClientError()); } @Test public void deleteClassRoom_shouldDeleteClassRoomFromDB() throws Exception { mockMvc.perform(delete("/api/classrooms/3")) .andExpect(status().isOk()); } @Test public void deleteClassRoom_shouldThrowExceptionOnBadRequest() throws Exception { mockMvc.perform(delete("/api/classrooms/roomNumber")) .andExpect(status().isBadRequest()); } }
2cf3f51445676d52880ffa813c46061b854abe65
03535fcc9da635b100ffd6b302af724b2ec0e0c5
/target/classes/com/sapientarrow/gwtapp/client/view/widgets/UploadedComponents/UploadedBindingClass.java
658af4a4aea4477aab7260dc7c3e02348255dd03
[]
no_license
junaidp/gwtapplication
87c5726777ff23aef17e68ddee0abb1768ff1173
07dc6e3d97d54f2da0dff0dc7035fb22f4a69af2
refs/heads/master
2021-01-20T20:56:48.725356
2018-07-25T10:31:20
2018-07-25T10:31:20
43,594,471
0
0
null
null
null
null
UTF-8
Java
false
false
5,649
java
/******************************************************************************* * Copyright (c) 2017 * Copyright (c) 2015 Sapient Arrow Technologies. * All rights reserved. This program and the accompanying materials * * are made available under the terms of the Affero GNU Public License * which accompanies this distribution, and is available at * https://en.wikipedia.org/wiki/Affero_General_Public_License * * Copyright: * Sapient Arrow Technologies llc * * This file is part of the Business Suite software of Sapient Arrowpro.net. * Copyright (C) 2012-2020 Sapient Arrowpro.net * * The primary contact email is support@Sapient Arrowpro.net * * Version: AGPL * * Sapient Arrow Technologies, Sapient Arrow Information Systems, Sapient Arrow along with their domain names, * etc and the names Acuity, Ingenuity, Derivo, Colander etc are copyright of * Sapient Arrow llc and usage of these without prior permission of the owner is strictly prohibited * * The contents of this file may be used under the terms of * the Affero GNU General Public License Version (the "AGPL"), * A copy of the AGPL v2.1 can be obtained from https://en.wikipedia.org/wiki/Affero_General_Public_License * * AGPL, in essence, means that this software requires a commercial license for use in or as a commercial application *******************************************************************************/ package com.sapientarrow.gwtapp.client.view.widgets.UploadedComponents; import java.util.Date; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.datepicker.client.DateBox; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; // This class is Dynamically generated class which becomes available here from Download, // which user download for Editing Bean public class UploadedBindingClass extends ApplicationBean{ private static UploadedBindingClassUiBinder uiBinder = GWT .create(UploadedBindingClassUiBinder.class); interface UploadedBindingClassUiBinder extends UiBinder<Widget, UploadedBindingClass> { } @UiField //test ListBox listIds; @UiField TextBox textBoxName; @UiField TextBox textBoxUser_Name; @UiField RadioButton checkM; @UiField RadioButton checkF; @UiField CheckBox checkReceiveNotifications; @UiField TextBox textBoxUser_Id; @UiField TextBox textBoxUser_password; @UiField TextBox user_MyAccountEntity_myAccountId; @UiField DateBox user_MyAccountEntity_lastEdited; @UiField TextBox txtAddress; public UploadedBindingClass() { initWidget(uiBinder.createAndBindUi(this)); listIds.addItem("0"); listIds.addItem("1"); listIds.addItem("2"); listIds.addChangeHandler(new ChangeHandler(){ @Override public void onChange(ChangeEvent event) { pcs.firePropertyChange(listIds.getName(), "", Integer.parseInt(listIds.getItemText(listIds.getSelectedIndex()))); }}); checkM.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if(event.getValue() == true){ pcs.firePropertyChange(checkM.getName(), "", "M"); } } }); checkF.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if(event.getValue() == true){ pcs.firePropertyChange(checkF.getName(), "", "F"); } } }); checkReceiveNotifications.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { pcs.firePropertyChange(checkReceiveNotifications.getName(), "", event.getValue()); } }); user_MyAccountEntity_lastEdited.addValueChangeHandler(new ValueChangeHandler<Date>() { @Override public void onValueChange(ValueChangeEvent<Date> event) { pcs.firePropertyChange("userEntity_MyAccountEntity_lastEdited", "", event.getValue()); } }); } @UiHandler("textBoxName") void onTextBoxBlur(BlurEvent event) { pcs.firePropertyChange(textBoxName.getName(), "", textBoxName.getText()); } @UiHandler("txtAddress") void onTextBoxAddBlur(BlurEvent event) { pcs.firePropertyChange(txtAddress.getName(), "", txtAddress.getText()); } @UiHandler("textBoxUser_Name") void onTextBoxUserBlur(BlurEvent event) { pcs.firePropertyChange(textBoxUser_Name.getName(), "", textBoxUser_Name.getText()); } @UiHandler("textBoxUser_Id") void onTextBoxUserIdBlur(BlurEvent event) { pcs.firePropertyChange(textBoxUser_Id.getName(), "", Integer.parseInt(textBoxUser_Id.getText())); } @UiHandler("textBoxUser_password") void onTextBoxUserPasswordBlur(BlurEvent event) { pcs.firePropertyChange(textBoxUser_password.getName(), "", textBoxUser_password.getText()); } @UiHandler("user_MyAccountEntity_myAccountId") void onTextBoxUserMyAcIdBlur(BlurEvent event) { pcs.firePropertyChange(user_MyAccountEntity_myAccountId.getName(), "", Integer.parseInt(user_MyAccountEntity_myAccountId.getText())); } }
9a6b7312e9c1a73929b8e05007ab3f2cc8cc73bb
dd01522057d622e942cc7c9058cbca61377679aa
/hybris/bin/ext-accelerator/b2bacceleratorfacades/gensrc/de/hybris/platform/b2bacceleratorfacades/constants/GeneratedB2BAcceleratorFacadesConstants.java
ee9541afca4575ff4503f5b1146553da6ef9f9e1
[]
no_license
grunya404/bp-core-6.3
7d73db4db81015e4ae69eeffd43730f564e17679
9bc11bc514bd0c35d7757a9e949af89b84be634f
refs/heads/master
2021-05-19T11:32:39.663520
2017-09-01T11:36:21
2017-09-01T11:36:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,055
java
/* * ---------------------------------------------------------------- * --- WARNING: THIS FILE IS GENERATED AND WILL BE OVERWRITTEN! --- * --- Generated at 10 Aug 2017 10:54:06 AM --- * ---------------------------------------------------------------- * * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with the * terms of the license agreement you entered into with SAP Hybris. * */ package de.hybris.platform.b2bacceleratorfacades.constants; /** * @deprecated use constants in Model classes instead */ @Deprecated @SuppressWarnings({"unused","cast","PMD"}) public class GeneratedB2BAcceleratorFacadesConstants { public static final String EXTENSIONNAME = "b2bacceleratorfacades"; protected GeneratedB2BAcceleratorFacadesConstants() { // private constructor } }
44c74b1df856566c563384c9c32a375f8e385a6a
73749486e20ccc951f100b65ea4d2901898be3d0
/notification-service/src/test/java/ba/unsa/etf/nwt/notificationservice/controller/SubscriptionConfigControllerTest.java
82561fd0c354a5c6dda96a13d59227f5605fe7b9
[]
no_license
SoftTech-Course/ProjectHub
e07ee9ca518914c599b05baef9f5bfe67c851425
6fec2b515691d0212807785d99452d3b6782f540
refs/heads/master
2023-05-10T16:24:20.531436
2021-06-07T20:05:47
2021-06-07T20:05:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,400
java
package ba.unsa.etf.nwt.notificationservice.controller; import ba.unsa.etf.nwt.notificationservice.client.service.TaskService; import ba.unsa.etf.nwt.notificationservice.config.token.ResourceOwnerInjector; import ba.unsa.etf.nwt.notificationservice.config.token.TokenGenerator; import ba.unsa.etf.nwt.notificationservice.model.SubscriptionConfig; import ba.unsa.etf.nwt.notificationservice.repository.SubscriptionConfigRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import java.util.UUID; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") public class SubscriptionConfigControllerTest { @Autowired private MockMvc mockMvc; @Autowired private TokenGenerator tokenGenerator; @Autowired private SubscriptionConfigRepository subscriptionConfigRepository; @MockBean private TaskService taskService; private String token; @BeforeEach public void setUp() { subscriptionConfigRepository.deleteAll(); token = "Bearer " + tokenGenerator.createAccessToken( ResourceOwnerInjector.clientId, ResourceOwnerInjector.id, ResourceOwnerInjector.clientId ).getValue(); } @Test public void createConfigBlankEmail() throws Exception { mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "user_id": "%s", "email": "" }""", UUID.randomUUID()))) .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.errors.email").value(hasItem("Email can't be blank"))); } @Test public void createConfigNoEmail() throws Exception { mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "user_id": "%s" }""", UUID.randomUUID()))) .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.errors.email").value(hasItem("Email can't be blank"))); } @Test public void createConfigNoUserId() throws Exception { mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "email": "%s" }""", ResourceOwnerInjector.email))) .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.errors.user_id").value(hasItem("User id can't be null"))); } @Test public void createConfigSuccess() throws Exception { mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "user_id": "%s", "email": "%s" }""", ResourceOwnerInjector.id, ResourceOwnerInjector.email))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.user_id").value(is(ResourceOwnerInjector.id.toString()))) .andExpect(jsonPath("$.data.email").value(is(ResourceOwnerInjector.email))); } @Test public void createConfigEmailInUse() throws Exception { createSubscriptionConfigInDb(UUID.randomUUID(), ResourceOwnerInjector.email); mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "user_id": "%s", "email": "%s" }""", UUID.randomUUID(), ResourceOwnerInjector.email))) .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.errors.message").value(hasItem("Config with this email or user id already exists"))); } @Test public void createConfigUserIdInUse() throws Exception { createSubscriptionConfigInDb(ResourceOwnerInjector.id, "[email protected]"); mockMvc.perform(post("/api/v1/subscription-config") .header(HttpHeaders.AUTHORIZATION, token) .contentType(MediaType.APPLICATION_JSON) .content(String.format(""" { "user_id": "%s", "email": "%s" }""", ResourceOwnerInjector.id, ResourceOwnerInjector.email))) .andExpect(status().isUnprocessableEntity()) .andExpect(jsonPath("$.errors.message").value(hasItem("Config with this email or user id already exists"))); } private SubscriptionConfig createSubscriptionConfigInDb(UUID userId, String email) { SubscriptionConfig subscriptionConfig = new SubscriptionConfig(); subscriptionConfig.setUserId(userId); subscriptionConfig.setEmail(email); return subscriptionConfigRepository.save(subscriptionConfig); } }
9a1cfdfe0db6b05fadc9bd2766b96bacd52602d3
8f4030b307bdb8f5fcdca5e050fb20e7d6bd61a8
/src/main/java/com/listaequipos/models/Roster.java
91a53ae22989da6429a24409379463d6626ac7fe
[]
no_license
jeanmunoz/ListaEquipos
0ce1206e76411c4a538034d99eca146c2b511179
149c5ecd66b2b45d6b29e1e4d78d467908ad848f
refs/heads/master
2023-07-07T05:50:37.455727
2021-08-11T01:22:13
2021-08-11T01:22:13
394,823,977
0
0
null
null
null
null
UTF-8
Java
false
false
787
java
package com.listaequipos.models; import java.util.ArrayList; import java.util.List; public class Roster { private List<Team> teamsList = new ArrayList<>(); private int numberOfTeams = 0; public Roster() { } public List<Team> getTeamsList() { return teamsList; } public void setTeamsList(List<Team> teamsList) { this.teamsList = teamsList; } public void addTeam(String teamName) { teamsList.add(new Team(teamName)); numberOfTeams++; } public int getNumberOfTeams() { return numberOfTeams; } public void setNumberOfTeams(int numberOfTeams) { this.numberOfTeams = numberOfTeams; } public void removeTeam(int id) { teamsList.remove(id); if(numberOfTeams > 0) numberOfTeams--; } public Team getTeam(int id) { return teamsList.get(id); } }
763872ff2f33a734c6574988fa9ad3d9607a37a6
a9999c6995aac2328f40ac179c21f47f5183b26b
/src/main/java/com/hxzy/springboot/service/impl/ResumeServiceImpl.java
dc653aa5ec0c0ea25aa3f51e3bf46fc8d1af6718
[]
no_license
Duringyoung/OAOA
9c9e6ac7187c41fcb9cc8c77d099d4c35c6209b8
afd35b7e88298d926c1f3fca9c75076a5206aab2
refs/heads/master
2020-06-19T02:45:58.510533
2019-07-18T01:44:25
2019-07-18T01:44:25
196,537,276
0
0
null
null
null
null
UTF-8
Java
false
false
1,417
java
package com.hxzy.springboot.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Component; import com.hxzy.springboot.dao.ResumeDao; import com.hxzy.springboot.entity.Resume; import com.hxzy.springboot.service.ResumeService; @Component("resumeServiceImpl") public class ResumeServiceImpl implements ResumeService{ ResumeDao resumeDao; @Resource public void setResumeDao(ResumeDao resumeDao) { this.resumeDao = resumeDao; } @Override public void addResume(Resume resume) { // TODO Auto-generated method stub resumeDao.save(resume); } @Override public void deleteResumeById(Integer id) { // TODO Auto-generated method stub resumeDao.deleteById(id); } @Override public void updateResume(Resume resume) { // TODO Auto-generated method stub resumeDao.save(resume); } @Override public List<Resume> getResumeList() { // TODO Auto-generated method stub return resumeDao.findAll(); } @Override public Page<Resume> getPageList(int pageNum, int pageSize) { // TODO Auto-generated method stub Pageable pageable=new PageRequest(pageNum,pageSize); Page<Resume> pages=resumeDao.findAll(pageable); return pages; } }
f00fe3b2f2dcf7c916b64f4ff2aefc01bea5c12c
fe573dc3abb82783a066bf8625b97886be9a7f84
/as7.ws/src/test/java/com/ivankoi/jee6/test/MemberRegistrationTestIT.java
de09d9b269d415d88cd62f11401352cd396debf0
[]
no_license
ivankoi/playground
48442682cb301c3032a1ad224de640d86d0762d5
ec8f824cef9527ed556eb7a727aff1470e86976c
refs/heads/master
2016-09-05T23:17:10.174884
2016-01-31T21:24:54
2016-01-31T21:24:54
33,117,510
0
0
null
null
null
null
UTF-8
Java
false
false
1,641
java
package com.ivankoi.jee6.test; import static org.junit.Assert.assertNotNull; import java.util.logging.Logger; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import com.ivankoi.jee6.controller.MemberRegistration; import com.ivankoi.jee6.model.Member; import com.ivankoi.jee6.util.Resources; @Ignore @RunWith(Arquillian.class) public class MemberRegistrationTestIT { @Deployment public static Archive<?> createTestArchive() { return ShrinkWrap.create(WebArchive.class, "test.war") .addClasses(Member.class, MemberRegistration.class, Resources.class) .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } @Inject MemberRegistration memberRegistration; @Inject Logger log; @Test public void testRegister() throws Exception { Member newMember = memberRegistration.getNewMember(); newMember.setName("Jane Doe"); newMember.setEmail("[email protected]"); newMember.setPhoneNumber("2125551234"); memberRegistration.register(); assertNotNull(newMember.getId()); log.info(newMember.getName() + " was persisted with id " + newMember.getId()); } }
0f3dde01e314e435b994bf421f35906d05a016a4
87baf29a0a6a67863230a4adf2b9aaca70db46fe
/src/crsjk/Auth.java
60fcf51ba79efcab65527bb57e3a370e44cb546e
[]
no_license
319zhouhaiwen/zaluandaima
f3db71e68a120d6efa791e7350eba1fdc0b9f000
48f61ec96894308898f0a5c0e9ef328a108ca533
refs/heads/master
2020-07-12T22:12:43.801768
2019-08-28T11:45:02
2019-08-28T11:45:02
204,918,359
0
0
null
null
null
null
GB18030
Java
false
false
2,256
java
package crsjk; import java.util.Date; public class Auth { private Integer id;// id private String name;// 名称 private String code;// 编码 private String url;// url private String pCode;// 父级菜单的code private String isButton;// 0是功能按钮,1是菜单 private String isDel;// 是否删除 0未删除,1删除 private String creator;//创建人 private String create_time;//创建时间 private String modifier;//修改人 private String modify_time;//修改时间 public Integer getId() { return id; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public String getModify_time() { return modify_time; } public void setModify_time(String modify_time) { this.modify_time = modify_time; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getpCode() { return pCode; } public void setpCode(String pCode) { this.pCode = pCode; } public String getIsDel() { return isDel; } public String getIsButton() { return isButton; } public void setIsButton(String isButton) { this.isButton = isButton; } public void setIsDel(String isDel) { this.isDel = isDel; } @Override public String toString() { return "Auth [id=" + id + ", name=" + name + ", code=" + code + ", url=" + url + ", pCode=" + pCode + ", isButton=" + isButton + ", isDel=" + isDel + ", creator=" + creator + ", create_time=" + create_time + ", modifier=" + modifier + ", modify_time=" + modify_time + "]"; } }
216415d0f51a1db8bc6569298a7f952dc3096640
c15589ea8ee77b671d6f3f8a1dfc2e5a7066c361
/src/main/java/kafka/api/RequestOrResponse.java
0b8575f98197647117e73c677356e4bb3c211cc2
[]
no_license
IMJIU/Jkafka
8143432c82978ec6b291a6aaf1f5437c9fe7952b
3986526b7759d41c2ec8a1fea63027f8c3a7de08
refs/heads/master
2021-01-18T03:24:17.324877
2018-07-23T10:41:24
2018-07-23T10:41:24
85,821,821
4
2
null
null
null
null
UTF-8
Java
false
false
1,161
java
package kafka.api; import kafka.network.RequestChannel; import kafka.utils.Logging; import java.nio.ByteBuffer; import java.util.Optional; /** * Created by Administrator on 2017/4/21. */ public abstract class RequestOrResponse extends Logging { public Optional<Short> requestId = Optional.empty(); public RequestOrResponse() { this.requestId = Optional.empty(); } public RequestOrResponse(Optional<Short> requestId) { this.requestId = requestId; } public abstract Integer sizeInBytes(); public abstract void writeTo(ByteBuffer buffer); public void handleError(Throwable e, RequestChannel requestChannel, RequestChannel.Request request) { } /* The purpose of this API is to return a string description of the Request mainly for the purpose of request logging. * This API has no meaning for a Response object. * @param details If this is false, omit the parts of the request description that are proportional to the number of * topics or partitions. This is mainly to control the amount of request logging. */ public abstract String describe(Boolean details); }
6eeddae4bbc3b8ee46b624b986dc99311051c417
5e1c245e43fe82f6b544941625dc506d4896d146
/src/app/start/gui/NodeTable.java
3c84ac25c04cc96b5b269a3bde8f0bf65e8d907f
[]
no_license
painpunisher/switchtradecoin
70412f8e9f9fcbc213b5786d2c581ae5301320b1
812d321de50666b2d7b10b5a76af09493131ac96
refs/heads/master
2020-03-18T00:19:57.409592
2018-05-22T22:51:57
2018-05-22T22:51:57
134,088,650
0
0
null
null
null
null
UTF-8
Java
false
false
5,478
java
package app.start.gui; import java.net.URL; import java.util.ResourceBundle; import app.config.Config; import app.net.Node; import app.net.NodeRegister; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; public class NodeTable implements Initializable { @FXML private TableView<Node> tablenodes; @FXML private TableColumn<Node, String> colip; @FXML private TableColumn<Node, String> colport; @FXML private Button addnode; @FXML private Button deletenode; @FXML private TextField nodeip; @FXML private TextField nodeport; @FXML private Button configsave; @FXML private Button configcancel; @FXML private CheckBox miningconfig; @FXML private CheckBox debugconfig; @FXML private CheckBox nodediscoveryconfig; @FXML private TextField receiverport; @Override public void initialize(URL location, ResourceBundle resources) { receiverport.setText(Integer.parseInt(Config.INSTANCE.getProperty("RECEIVERPORT"))+""); debugconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("DEBUGMODE"))); miningconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("MININGMODE"))); nodediscoveryconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("NODEDISCOVERY"))); // loadConfig(); colip.setCellValueFactory(new PropertyValueFactory<Node, String>("IP")); colport.setCellValueFactory(new PropertyValueFactory<Node, String>("Port")); // coldate.setSortable(false); colip.setSortable(false); colport.setSortable(false); Platform.runLater(new Runnable() { public void run() { tablenodes.getItems().setAll(NodeRegister.getInstance().getNodes()); } }); } @FXML public void addnodemethod(){ NodeRegister.getInstance().addNode(nodeip.getText(), Integer.parseInt(nodeport.getText())); refreshNodes(); } @FXML public void deletenodemethod(){ Node remove = null; for(Node cur : NodeRegister.getInstance().getNodes()){ if(cur.getIP().equals(nodeip.getText())){ if(cur.getPort() == (Integer.parseInt(nodeport.getText()))){ remove = cur; break; } } } NodeRegister.getInstance().getNodes().remove(remove); refreshNodes(); } @FXML public void selectedNode(){ Node node = tablenodes.getSelectionModel().getSelectedItem(); Platform.runLater(new Runnable() { public void run() { nodeip.setText(node.getIP()); nodeport.setText(node.getPort()+""); } }); } @FXML public void configsave(){ Config.INSTANCE.setProperty("RECEIVERPORT", (receiverport.getText())); Config.INSTANCE.setProperty("MININGMODE", miningconfig.isSelected() + ""); Config.INSTANCE.setProperty("DEBUGMODE", debugconfig.isSelected() + ""); Config.INSTANCE.setProperty("NODEDISCOVERY", nodediscoveryconfig.isSelected() + ""); Config.saveProperties(); NodeRegister.getInstance().saveNodes(); GUI.secondStage.close(); } @FXML public void configcancel(){ GUI.secondStage.close(); } @FXML private void loadConfig(){ receiverport.setText(Integer.parseInt(Config.INSTANCE.getProperty("RECEIVERPORT"))+""); debugconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("DEBUGMODE"))); miningconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("MININGMODE"))); nodediscoveryconfig.setSelected(Boolean.parseBoolean(Config.INSTANCE.getProperty("NODEDISCOVERY"))); } private void refreshNodes(){ Platform.runLater(new Runnable() { public void run() { tablenodes.getItems().setAll(NodeRegister.getInstance().getNodes()); } }); } // public static List<Transaction> getTransactionHistory() { // LinkedList<Transaction> history = new LinkedList<>(); // for (Block curr : GO.BLOCKCHAIN) { // if (curr.transactions.size() > 0) { // for (Transaction tx : curr.transactions) { // if (tx.sender == null) { // OUT.DEBUG("stahp"); // return null; // } // if (tx.sender.equals(GO.clientWalletLocal.publicKey)) { // history.add(tx); // } // if (tx.reciepient.equals(GO.clientWalletLocal.publicKey)) { // history.add(tx); // } // } // // } // } // // if(history.size()>26){ // return history.subList(history.size() - 25, history.size()); // } else { // return history; // } // } // @FXML // private void sendTransaction() { // if(StringUtil.getKey(transactionreceiver.getText()) == null){ // return; // } // Alert alert = new Alert(AlertType.CONFIRMATION, "Are you sure you want to Send?", ButtonType.YES, ButtonType.NO, // ButtonType.CANCEL); // alert.showAndWait(); // if (alert.getResult() == ButtonType.YES) { // Transaction txnew = GO.clientWalletLocal.sendFunds(StringUtil.getKey(transactionreceiver.getText()), // new BigInteger(transactionamount.getText())); // GO.mempool.add(txnew); // } // } // void addObservableDataToTableView(TableView<Transaction> table, // ArrayList<Transaction> transaction){ // private final ObservableList<Transaction> data = // FXCollections.observableArrayList(transactions); // table.setData(data); // } }
02df7726a4d81ce518ba5aff6c2485e082a95f3a
adf58f5567cc81189f8780a54f41f70f41c17a30
/src/sample/Main.java
0b9e8f4c86e8dba5f0bd1e38108e4eb83628ea97
[]
no_license
paco-portada/EjemploJavaFX
104556d5652082c9446ece63239daa2098f6604b
b97f14aa403ff2b93c5e9723a5a0e16265bf91de
refs/heads/master
2022-06-29T08:10:36.877760
2020-05-11T09:35:56
2020-05-11T09:35:56
257,255,464
0
0
null
null
null
null
UTF-8
Java
false
false
667
java
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author JJBH */ public class Main extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.setTitle("Ejemplo JavaFX"); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
d86d81177fe680f8e53fdb72313d2efcc21e3c3c
5940df890849cacd1fb7be11ad7617434b3e23b3
/biopids/src/br/com/biopids/domain/Imagem.java
68d279cca871ebe167c28b72fed4fd0d08d2f7c9
[]
no_license
deftnesssolutions/portal-virtual
43f0b7d009dd2bd56af581c6d7deb184d9f3000e
438ca2eb949175b6a067437cdb22c028437c39a6
refs/heads/master
2021-01-18T22:10:19.617149
2011-12-06T00:43:54
2011-12-06T00:43:54
36,197,660
0
0
null
null
null
null
UTF-8
Java
false
false
883
java
package br.com.biopids.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.Table; @Entity @Table(name="imagem") public class Imagem extends EntityPersist { @Lob @Column(columnDefinition="bytea") private byte[] imagem; private String nome; private int ordem; private String descricao; public byte[] getImagem() { return imagem; } public void setImagem(byte[] imagem) { this.imagem = imagem; } public int getOrdem() { return ordem; } public void setOrdem(int ordem) { this.ordem = ordem; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
[ "[email protected]@ebcab346-02a9-eae8-fbf5-f4d2a0660fd7" ]
[email protected]@ebcab346-02a9-eae8-fbf5-f4d2a0660fd7
d79b794eb3a8de8af6ea9e1e2744849403dd5724
eb69f189cf7916c33e5738a4a8961971244c9848
/Folders/ParallelStreams/src/main/resources/works/LiveLessons/Loom/ex3/src/main/java/utils/FuturesCollector.java
1743f2af66a0bdab2df7dd75fb180b3b350692c1
[]
no_license
douglascraigschmidt/LiveLessons
59e06ade1d0786eac665d3fe369426cde36ff199
b685afc62b469b17e3e9323a814e220d5315df55
refs/heads/master
2023-08-18T01:21:04.022903
2023-08-02T00:52:16
2023-08-02T00:52:16
21,949,817
587
712
null
2023-02-18T04:18:02
2014-07-17T16:46:47
Java
UTF-8
Java
false
false
4,296
java
package utils; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; /** * Implements a custom collector that converts a stream of * CompletableFuture objects into a single CompletableFuture that is * triggered when all the futures in the stream complete. * <p> * See * http://www.nurkiewicz.com/2013/05/java-8-completablefuture-in-action.html * for more info. */ public class FuturesCollector<T> implements Collector<CompletableFuture<T>, List<CompletableFuture<T>>, CompletableFuture<List<T>>> { /** * A function that creates and returns a new mutable result * container that will hold all the CompletableFutures in the * stream. * * @return a function which returns a new, mutable result container */ @Override public Supplier<List<CompletableFuture<T>>> supplier() { return ArrayList::new; } /** * A function that folds a CompletableFuture into the mutable * result container. * * @return a function which folds a value into a mutable result container */ @Override public BiConsumer<List<CompletableFuture<T>>, CompletableFuture<T>> accumulator() { return List::add; } /** * A function that accepts two partial results and merges them. * The combiner function may fold state from one argument into the * other and return that, or may return a new result container. * * @return a function which combines two partial results into a combined * result */ @Override public BinaryOperator<List<CompletableFuture<T>>> combiner() { return (List<CompletableFuture<T>> one, List<CompletableFuture<T>> another) -> { one.addAll(another); return one; }; } /** * Perform the final transformation from the intermediate * accumulation type {@code A} to the final result type {@code R}. * * @return a function which transforms the intermediate result to * the final result */ @Override public Function<List<CompletableFuture<T>>, CompletableFuture<List<T>>> finisher() { return futures -> CompletableFuture // Use CompletableFuture.allOf() to obtain a // CompletableFuture that will itself complete when all // CompletableFutures in futures have completed. .allOf(futures.toArray(CompletableFuture[]::new)) // When all futures have completed get a CompletableFuture // to an array of joined elements of type T. .thenApply(v -> futures // Convert futures into a stream of completable // futures. .stream() // Use map() to join() all completable futures // and yield objects of type T. Note that // join() should never block. .map(CompletableFuture::join) // Collect the results of type T into an array. .collect(toList())); } /** * Returns a {@code Set} of {@code Collector.Characteristics} * indicating the characteristics of this Collector. This set * should be immutable. * * @return An immutable set of collector characteristics, which in * this case is simply UNORDERED */ @SuppressWarnings("unchecked") @Override public Set characteristics() { return Collections.singleton(Characteristics.UNORDERED); } /** * This static factory method creates a new FuturesCollector. * * @return A new FuturesCollector() */ public static <T> Collector<CompletableFuture<T>, ?, CompletableFuture<List<T>>> toFuture() { return new FuturesCollector<>(); } }
8d7e4531aa80daf3516786d57ee2d96463e9b119
b5747f50d2124462aac7b54c5546d8fc809b1440
/src/main/java/cn/com/ut/cache/serializer/FastJsonRedisSerializer.java
152afebcf9e3506d9e253abd8197f58ef40848ab
[ "Apache-2.0" ]
permissive
hubgitchina/spring-cache-redis
7e18d807ed0421f062f2bdabff9ea2c944344254
eb3b2184bf5433e3827c0fb340a618f2e22c9b67
refs/heads/master
2020-04-23T01:43:48.623873
2019-02-27T06:23:21
2019-02-27T06:23:21
170,822,522
0
0
null
null
null
null
UTF-8
Java
false
false
1,101
java
package cn.com.ut.cache.serializer; import java.nio.charset.Charset; import org.springframework.cache.support.NullValue; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T> clazz; public FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null || t instanceof NullValue) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return (T) JSON.parseObject(str, clazz); } }
1898570e6e867184366bfc2efd5f9aa61cc3c8e4
8fb8a6390de1a50f3503c6c8792205f0bd046709
/CompteurJSF/src/fr/ipst/cnam/entities/Utilisateur.java
84ef6925426da87efa2fbbf8d16dd1e15ccdbd82
[]
no_license
big73/NFE114
b8fa37afb6dfc153f499d98c557c175272dc0712
70fe77bfa37978c4d4899ddb151c1a00c4aba35c
refs/heads/master
2021-01-10T14:15:07.508904
2016-04-20T18:46:38
2016-04-20T18:46:38
47,507,410
0
0
null
null
null
null
UTF-8
Java
false
false
534
java
package fr.ipst.cnam.entities; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class Utilisateur { private int age; public void setAge(int age) { this.age = age; } public int getAge() { return age; } public String checkAge() { System.out.println("méthode de checkage"); if(this.age >= 18) { System.out.println("l'age est majeure"); return "majeur"; } else { System.out.println("l'age est mineur"); return "mineur"; } } }
46a9976e25513b41dc6be01364555bf44960063f
d1d71f0e68b340de9030eed047c1168f36b1fe67
/MPChartExample/src/main/java/com/xxmassdeveloper/mpchartexample/custom/BarChatXAxisValueFormatter.java
a90d99301f375ea7824a74fe9b04bd2bc433917e
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
octopusy/MPAndroidChart
0f28964ece47905d1380f150daa7ba50f90b33ad
5a8559303c7d938e6603b6166037b21a829b4692
refs/heads/master
2022-11-16T17:58:05.588128
2020-07-17T07:21:08
2020-07-17T07:21:08
280,355,392
2
0
null
null
null
null
UTF-8
Java
false
false
2,240
java
package com.xxmassdeveloper.mpchartexample.custom; import android.util.Log; import com.github.mikephil.charting.formatter.ValueFormatter; import java.util.ArrayList; /** * Created by philipp on 02/06/16. */ public class BarChatXAxisValueFormatter extends ValueFormatter{ public BarChatXAxisValueFormatter() {} @Override public String getFormattedValue(float value) { if(value < 0 || value == 0.5) return ""; int position = 0; /*if(value > 1) { position = (int)value -1; } else {*/ position = (int)value; // } try { if(getXList().isEmpty() || position >= getXList().size()) { return ""; } else { return getXList().get(position); } } catch (Exception exception) { exception.printStackTrace(); Log.e("value:" , exception.getMessage()); return ""; } //Log.e("value:" , "value:" + position); //return getXList().get(position) + "月"; } /** * X轴数据 * * @return */ private ArrayList<String> getXList(){ ArrayList<String> xList = new ArrayList<>(); xList.add("2020-04-01"); xList.add("2020-04-02"); xList.add("2020-04-03"); xList.add("2020-04-04"); xList.add("2020-04-05"); xList.add("2020-04-06"); xList.add("2020-04-07"); xList.add("2020-04-08"); xList.add("2020-04-09"); xList.add("2020-04-10"); /*xList.add("2020-04-12"); xList.add("2020-04-13"); xList.add("2020-04-14"); xList.add("2020-04-15"); xList.add("2020-04-16"); xList.add("2020-04-17"); xList.add("2020-04-18"); xList.add("2020-04-19"); xList.add("2020-04-20"); xList.add("2020-04-21"); xList.add("2020-04-22"); xList.add("2020-04-23"); xList.add("2020-04-24"); xList.add("2020-04-25"); xList.add("2020-04-26"); xList.add("2020-04-27"); xList.add("2020-04-28"); xList.add("2020-04-29"); xList.add("2020-04-30"); xList.add("2020-04-31");*/ return xList; } }
[ "zhanghuan1991" ]
zhanghuan1991
ddb46bba3f896bbc2f6d2b900ec886c78f96a03e
67934dd3dfa02e8aac0b76c1043b1935a68ef678
/src/main/java/com/github/lindenb/jvarkit/tools/mem/FindMyVirus.java
91d6748449392b2d0778b69232c765e6474b08ad
[ "MIT" ]
permissive
lindenb/jvarkit
5dbb37a1eda66b76c4ba495f1f52e9ec023fc37f
3d336e522b2862e7f9490bbdfc80b219e68532e2
refs/heads/master
2023-08-22T13:27:44.758256
2023-05-05T15:32:15
2023-05-05T15:32:15
9,889,013
423
150
NOASSERTION
2023-01-27T14:39:22
2013-05-06T14:49:08
Java
UTF-8
Java
false
false
13,801
java
/* The MIT License (MIT) Copyright (c) 2023 Pierre Lindenbaum Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.lindenb.jvarkit.tools.mem; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMFlag; import htsjdk.samtools.SAMProgramRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMRecordIterator; import htsjdk.samtools.SAMSequenceRecord; import htsjdk.samtools.SAMUtils; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.util.CloserUtil; import htsjdk.samtools.util.FileExtensions; import htsjdk.samtools.util.ProgressLoggerInterface; import htsjdk.samtools.SAMFileWriter; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParametersDelegate; import com.github.lindenb.jvarkit.io.IOUtils; import com.github.lindenb.jvarkit.lang.StringUtils; import com.github.lindenb.jvarkit.util.Counter; import com.github.lindenb.jvarkit.util.JVarkitVersion; import com.github.lindenb.jvarkit.util.bio.SequenceDictionaryUtils; import com.github.lindenb.jvarkit.util.jcommander.Launcher; import com.github.lindenb.jvarkit.util.jcommander.Program; import com.github.lindenb.jvarkit.util.log.Logger; import com.github.lindenb.jvarkit.util.log.ProgressFactory; /** ## Example ```bash $ java -jar dist/findmyvirus.jar -V virus_chr -o category in.bam ``` */ @Program(name="findmyvirus", description="Find my Virus. Created for @AdrienLeger2. Proportion of reads mapped on HOST/VIRUS.", keywords={"bam","virus"}, modificationDate="20200416" ) public class FindMyVirus extends Launcher { private static final Logger LOG= Logger.build(FindMyVirus.class).make(); /* how to split the bam, witch categories */ private enum CAT{ both_ref() { @Override public String getDescription() { return "Both reads map the HOST reference"; } } , both_virus() { @Override public String getDescription() { return "Both reads map the VIRUS reference"; } }, ref_orphan() { @Override public String getDescription() { return "In a pair: the read is mapped on the HOST Reference, the mate is unmapped. No spliced read mapped on VIRUS."; } }, virus_orphan() { @Override public String getDescription() { return "In a pair: the read is mapped on the VIRUS Reference, the mate is unmapped. No spliced read mapped on HOST."; } }, ref_and_virus() { @Override public String getDescription() { return "In a pair: a read is mapped on the VIRUS Reference, the other is mapped on HOST. No spliced read mapped on the other genome."; } }, ref_and_virus_spliced() { @Override public String getDescription() { return "In a pair: a read is mapped on the VIRUS Reference, the other is mapped on HOST. A spliced read is mapped on the other genome."; } }, unpaired() { @Override public String getDescription() { return "read is not paired."; } }, undetermined() { @Override public String getDescription() { return "Unknown category/case"; } }, unmapped() { @Override public String getDescription() { return "Read is unmapped"; } }, duplicate() { @Override public String getDescription() { return "Read is duplicate"; } }, secondary { @Override public String getDescription() { return "Secondary alignment"; } }, failsqual{ @Override public String getDescription() { return "Fails mapper quality-control"; } }; public String getDescription() { return name(); } }; @Parameter(names={"-o","--out"},description="Ouptut base name",required=true) private Path outputFile=null; @Parameter(names={"-V"},description=" virus chrom/contig names. comma,space,tab,semicolon separated",required=true) private String virusNamesStr= null; @Parameter(names={"-R","--reference"},description="For Reading CRAM. " + INDEXED_FASTA_REFERENCE_DESCRIPTION) private Path faidxPath = null; @ParametersDelegate private WritingBamArgs writingBamArgs=new WritingBamArgs(); @Override public int doWork(final List<String> args) { final Set<String> virusNames = Arrays.stream(this.virusNamesStr.split(" \n;,")). filter(S->!StringUtils.isBlank(S)). collect(Collectors.toSet()); if(virusNames.isEmpty()) { LOG.error("no virus name"); return -1; } SamReader sfr=null; final SAMFileWriter sfwArray[]=new SAMFileWriter[CAT.values().length]; try { final SamReaderFactory srfact = super.createSamReaderFactory().referenceSequence(this.faidxPath); final String input = oneFileOrNull(args); if(input==null) { sfr = srfact.open(SamInputResource.of(stdin())); } else { sfr = srfact.open(SamInputResource.of(input)); } final SAMFileHeader header=sfr.getFileHeader(); for(CAT category:CAT.values()) { final SAMFileHeader header2=header.clone(); JVarkitVersion.getInstance().addMetaData(this, header2); header2.addComment("Category:"+category.name()); header2.addComment("Description:"+category.getDescription()); final SAMProgramRecord rec=header2.createProgramRecord(); rec.setCommandLine(this.getProgramCommandLine()); rec.setProgramName(getProgramName()); rec.setProgramVersion(getVersion()); rec.setAttribute("CAT", category.name()); final Path outputFile= this.outputFile.getParent().resolve(IOUtils.getFilenameWithoutCommonSuffixes(this.outputFile)+"."+category.name()+FileExtensions.BAM); LOG.info("Opening "+outputFile); final Path countFile=this.outputFile.getParent().resolve(IOUtils.getFilenameWithoutCommonSuffixes(this.outputFile)+"."+category.name()+".count.txt"); @SuppressWarnings("resource") SAMFileWriter sfw= writingBamArgs.openSamWriter(outputFile, header2, true); sfw=new SAMFileWriterCount(sfw, countFile,category); sfwArray[category.ordinal()]=sfw; } final ProgressFactory.Watcher<SAMRecord> progress=ProgressFactory.newInstance().dictionary(header).logger(LOG).build(); final SAMRecordIterator iter=sfr.iterator(); while(iter.hasNext()) { final SAMRecord rec=progress.apply(iter.next()); CAT category=null; if(category==null && !rec.getReadPairedFlag()) { category=CAT.unpaired; } if(category==null && rec.isSecondaryOrSupplementary()) { category=CAT.secondary; } if(category==null && rec.getReadFailsVendorQualityCheckFlag()) { category=CAT.failsqual; } if(category==null && rec.getDuplicateReadFlag()) { category=CAT.duplicate; } if(category==null && rec.getReadUnmappedFlag()) { category=CAT.unmapped; } final List<SAMRecord> xpList= category==null? SAMUtils.getOtherCanonicalAlignments(rec) :Collections.emptyList(); boolean xp_containsVirus=false; boolean xp_containsChrom=false; for(final SAMRecord xpa:xpList) { if(virusNames.contains(xpa.getReferenceName())) { xp_containsVirus=true; } else { xp_containsChrom=true; } } /* both reads mapped on ref */ if(category==null && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && !virusNames.contains(rec.getReferenceName()) && !virusNames.contains(rec.getMateReferenceName()) ) { if(!xp_containsVirus) { category=CAT.both_ref; } else { category=CAT.ref_and_virus_spliced; } } /* pair(unmapped,mapped on reference) */ if(category==null && ( (!rec.getReadUnmappedFlag() && rec.getMateUnmappedFlag() && !virusNames.contains(rec.getReferenceName())) || (rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && !virusNames.contains(rec.getMateReferenceName())) )) { if(!xp_containsVirus) { category=CAT.ref_orphan; } else { category=CAT.ref_and_virus_spliced; } } /* both reads mapped on virus */ if(category==null && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && virusNames.contains(rec.getReferenceName()) && virusNames.contains(rec.getMateReferenceName()) ) { if(!xp_containsChrom) { category=CAT.both_virus; } else { category=CAT.ref_and_virus_spliced; } } if(category==null && ( (!rec.getReadUnmappedFlag() && rec.getMateUnmappedFlag() && virusNames.contains(rec.getReferenceName())) || (rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && virusNames.contains(rec.getMateReferenceName())) )) { if(!xp_containsChrom) { category=CAT.virus_orphan; } else { category=CAT.ref_and_virus_spliced; } } if(category==null && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && ( (virusNames.contains(rec.getReferenceName()) && !virusNames.contains(rec.getMateReferenceName())) || (!virusNames.contains(rec.getReferenceName()) && virusNames.contains(rec.getMateReferenceName())) ) ) { category=CAT.ref_and_virus; } /*dispatch */ if(category==null) { LOG.warning("Not handled: "+rec); category=CAT.undetermined; } sfwArray[category.ordinal()].addAlignment(rec); } progress.close(); iter.close(); for(final SAMFileWriter sfw:sfwArray) { LOG.info("Closing "+sfw); sfw.close(); } return 0; } catch(final Throwable err) { LOG.error(err); return -1; } finally { LOG.info("Closing"); CloserUtil.close(sfr); CloserUtil.close(sfwArray); } } public static void main(String[] args) { new FindMyVirus().instanceMainWithExit(args); } /** wrapper of SAMFileWriter to get some statistics about a BAM. write data on close() */ private class SAMFileWriterCount implements SAMFileWriter { private final CAT category; private final SAMFileWriter delegate; private final Path countFile; private final Counter<String> chrom=new Counter<>(); private final Counter<Integer> flags=new Counter<>(); @SuppressWarnings("unused") private ProgressLoggerInterface progressLogger; SAMFileWriterCount( final SAMFileWriter delegate, final Path countFile, final CAT category) { this.category=category; this.countFile=countFile; this.delegate=delegate; for(final SAMSequenceRecord rec:SequenceDictionaryUtils.extractRequired(delegate.getFileHeader()).getSequences()) { this.chrom.initializeIfNotExists(rec.getSequenceName()); } this.chrom.initializeIfNotExists(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME); } @Override public void setProgressLogger(final ProgressLoggerInterface progressLogger) { this.progressLogger=progressLogger; } @Override public void addAlignment(final SAMRecord alignment) { this.delegate.addAlignment(alignment); this.flags.incr(alignment.getFlags()); if(!alignment.getReadUnmappedFlag()) { chrom.incr(alignment.getReferenceName()); } else { chrom.incr(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME); } } @Override public SAMFileHeader getFileHeader() { return this.delegate.getFileHeader(); } @Override public void close() { LOG.info("Closing SAMFileWriterCount"); PrintWriter fw=null; try { LOG.info("Writing "+countFile); fw=new PrintWriter(Files.newBufferedWriter(countFile)); fw.println(this.category.name()); fw.println(this.category.getDescription()); fw.println("#CHROMOSOME\tCOUNT"); for(final String c:this.chrom.keySetDecreasing()) { fw.println(c+"\t"+this.chrom.count(c)); } fw.println("Total\t"+this.chrom.getTotal()); fw.println("#FLAG\tCOUNT\texplain"); for(final Integer c:this.flags.keySetDecreasing()) { fw.print(c+"\t"+this.flags.count(c)+"\t"); for(final SAMFlag flg:SAMFlag.values()) { if(flg.isSet(c)) { fw.write(flg.name()+" "); } } fw.println(); } fw.flush(); } catch(final Throwable err) { LOG.error(err); throw new RuntimeException("Boum:"+countFile,err); } finally { CloserUtil.close(fw); } this.delegate.close(); } @Override public String toString() { return "SAMFileWriterCount "+countFile; } } }
8c48b3bbba22dc497dcfa2ad56dc79659f4fae15
2109d34ecbc228b103645ff3b259a80d15af3abe
/app/src/main/java/pinkstar/com/demo/MainActivity.java
a1e598ecd7cd81a7f34e906107cf0d11b4f37ec3
[]
no_license
mysolution4u/Demo
c1607ed901f87a5c640a6890614b880bcb16e6e2
9f47b23d25ffc7d1851c60ea9d13099db286cfd1
refs/heads/master
2021-01-10T06:58:24.760930
2016-03-31T06:16:15
2016-03-31T06:16:15
55,126,685
0
0
null
null
null
null
UTF-8
Java
false
false
10,844
java
package pinkstar.com.demo; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; public class MainActivity extends Activity implements LocationListener, View.OnClickListener { private static final String TAG = MainActivity.class.getSimpleName(); protected LocationManager locationManager; protected Context context; private double latitude = 0, longitude = 0; private TextView lat, lng, adres, tcity, tstate, tpincode, tcountry; private Button submit_latlng, refresh; private EditText form_id; private ProgressDialog dialog; Geocoder geocoder; private List<Address> addresses; private String address, city, state, country, postalCode, get_form_id, token; private ProgressDialog pDialog; PrefManager session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pDialog = new ProgressDialog(this); pDialog.setCancelable(false); session = new PrefManager(MainActivity.this); HashMap<String, String> user = session.getUserDetails(); // name token = user.get(PrefManager.KEY_IS_LOGGEDIN); Log.d("TOKENID", "" + token); lat = (TextView) findViewById(R.id.lat); lng = (TextView) findViewById(R.id.lng); adres = (TextView) findViewById(R.id.address); tcity = (TextView) findViewById(R.id.city); tcountry = (TextView) findViewById(R.id.country); tstate = (TextView) findViewById(R.id.state); tpincode = (TextView) findViewById(R.id.pincode); geocoder = new Geocoder(this, Locale.getDefault()); refresh = (Button) findViewById(R.id.refresh); submit_latlng = (Button) findViewById(R.id.submit_latlng); submit_latlng.setOnClickListener(this); form_id = (EditText) findViewById(R.id.form); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub refresh(); } }); dialog = new ProgressDialog(MainActivity.this); dialog.show(); dialog.setMessage("Getting Coordinates"); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER)) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10000, 1, this); } else if (locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 10000, 1, this); } else { dialog.dismiss(); Toast.makeText(getApplicationContext(), "Enable Location", Toast.LENGTH_LONG).show(); } } protected void refresh() { super.onResume(); this.onCreate(null); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub dialog.show(); latitude = location.getLatitude(); longitude = location.getLongitude(); if (latitude != 0 && longitude != 0) { lat.setText("Latitude is :" + location.getLatitude()); lng.setText("Longitude is :" + location.getLongitude()); try { addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5 } catch (IOException e) { e.printStackTrace(); } // address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex() city = addresses.get(0).getLocality(); state = addresses.get(0).getAdminArea(); country = addresses.get(0).getCountryName(); postalCode = addresses.get(0).getPostalCode(); adres.setText("Address is :" + address); tcity.setText("City is :" + city); tstate.setText("State is :" + state); tcountry.setText("Country is :" + country); tpincode.setText("Postal code is :" + postalCode); dialog.dismiss(); } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onClick(View v) { if (v == submit_latlng) { if (AppConfig.isNetworkAvailable(MainActivity.this)) { get_form_id = form_id.getText().toString(); if (!get_form_id.isEmpty()) { checkLogin(latitude, longitude, country, city, state, postalCode, get_form_id); } else { // Prompt user to enter credentials Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG) .show(); } } else { Toast toast = Toast.makeText(getApplicationContext(), "No internet", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } } private void checkLogin(final double latitude, final double longitude, final String country, final String city, final String state, final String postalCode, final String get_form_id) { // Tag used to cancel the request String tag_string_req = "req_login"; pDialog.setMessage("Submitting in ..."); showDialog(); StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_FORM_SUBMIT, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, "Login Response: " + response.toString()); hideDialog(); try { JSONObject jObj = new JSONObject(response); int udata = jObj.getInt("udata"); if (udata == 0) { Toast toast = Toast.makeText(getApplicationContext(), "Unsuccessful", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } if (udata == 1) { Toast toast = Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); startActivity(new Intent(MainActivity.this, ThankYou.class)); } // Check for error node in json // session.setLogin(true); } catch (JSONException e) { // JSON error e.printStackTrace(); Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Login Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); hideDialog(); } }) { @Override protected Map<String, String> getParams() { // Posting parameters to login url Map<String, String> params = new HashMap<String, String>(); params.put("token_id", token); params.put("form_id", get_form_id); params.put("latitude", String.valueOf(latitude)); params.put("longitude", String.valueOf(longitude)); params.put("city", city); params.put("state", state); params.put("country", country); params.put("pincode", " " + postalCode); return params; } }; // Adding request to request queue MyApp.getInstance().addToRequestQueue(strReq, tag_string_req); } private void showDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
[ "Radhey Shyam" ]
Radhey Shyam
aa8d3d1ab6228344fa6960473fb54f3808e6f9bc
e927ab4eda0f68fbdd9929c4474a6cc9c37d73d9
/src/com/geariot/platform/freelycar_wechat/wxutils/WechatTemplateMessage.java
cd07447b3d2bd01d2edb400eaf9fb61b6531868b
[]
no_license
tangtang233/freelycar_wechat_xuzhuang
5d4e13f16a7eae57de1e35b4b938d705a0924120
f9c789601e4a75613075444e0eff65d47ff1e93b
refs/heads/master
2020-04-06T13:23:19.957205
2019-01-07T01:44:41
2019-01-07T01:44:41
157,497,730
2
0
null
null
null
null
UTF-8
Java
false
false
9,857
java
package com.geariot.platform.freelycar_wechat.wxutils; import com.geariot.platform.freelycar_wechat.entities.ConsumOrder; import com.geariot.platform.freelycar_wechat.entities.ProjectInfo; import com.geariot.platform.freelycar_wechat.entities.Staff; import com.geariot.platform.freelycar_wechat.entities.WXPayOrder; import com.geariot.platform.freelycar_wechat.utils.Constants; import org.apache.commons.lang.StringUtils; import org.apache.http.entity.StringEntity; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.text.SimpleDateFormat; public class WechatTemplateMessage { private static final String PAY_SUCCESS_TEMPLATE_ID = "F5CyYJ5u9_1wRcapK1ECOYRrjxcLcL3rjB0xUg_VQn0"; private static final String PAY_FAIL_ID = "o0TOjg7KkxoL4CtQ91j--TVVmxYDSNk-dLWqoUVd8mw"; private static final String ORDER_CHANGED_ID = "Au2k3CSXdYZu7ujvagXT6GxTzjDGUmQTkI8xutL30Fc"; private static final Logger log = LogManager.getLogger(WechatTemplateMessage.class); private static final String PAY_ERROR_DATABASE_FAIL = "服务异常"; private static String invokeTemplateMessage(JSONObject params) { //解决中文乱码问题 StringEntity entity = new StringEntity(params.toString(), "utf-8"); String result = HttpRequest.postCall(WechatConfig.WECHAT_TEMPLATE_MESSAGE_URL + WechatConfig.getAccessTokenForInteface().getString("access_token"), entity, null); log.debug("微信模版消息结果:" + result); return result; } //{{first.DATA}} //类型:{{keyword1.DATA}} //金额:{{keyword2.DATA}} //状态:{{keyword3.DATA}} //时间:{{keyword4.DATA}} //备注:{{keyword5.DATA}} //{{remark.DATA}} public static void paySuccess(WXPayOrder wxPayOrder) { log.debug("准备支付成功模版消息。。。"); SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); JSONObject params = new JSONObject(); JSONObject data = new JSONObject(); params.put("touser", wxPayOrder.getOpenId()); params.put("template_id", PAY_SUCCESS_TEMPLATE_ID); // params.put("url", "http://www.geariot.com/fitness/class.html"); data.put("first", keywordFactory("支付成功", "#173177")); data.put("keyword1", keywordFactory(wxPayOrder.getProductName(), "#173177")); data.put("keyword2", keywordFactory((float) (Math.round(wxPayOrder.getTotalPrice() * 100)) / 100 + "元", "#173177")); data.put("keyword3", keywordFactory("成功", "#173177")); data.put("keyword4", keywordFactory(df.format(wxPayOrder.getFinishDate()), "#173177")); data.put("keyword5", keywordFactory("")); data.put("remark", keywordFactory("")); params.put("data", data); String result = invokeTemplateMessage(params); log.debug("微信支付成功模版消息结果:" + result); // return result; } public static void paySuccess(ConsumOrder consumOrder, String openId) { log.debug("准备支付成功模版消息。。。"); SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); JSONObject params = new JSONObject(); JSONObject data = new JSONObject(); params.put("touser", openId); params.put("template_id", PAY_SUCCESS_TEMPLATE_ID); // params.put("url", "http://www.geariot.com/fitness/class.html"); data.put("first", keywordFactory("支付成功", "#173177")); data.put("keyword1", keywordFactory(getConsumOrderProductName(consumOrder), "#173177")); data.put("keyword2", keywordFactory((float) (Math.round(consumOrder.getTotalPrice() * 100)) / 100 + "元", "#173177")); data.put("keyword3", keywordFactory("成功", "#173177")); data.put("keyword4", keywordFactory(df.format(consumOrder.getFinishTime()), "#173177")); data.put("keyword5", keywordFactory("")); data.put("remark", keywordFactory("")); params.put("data", data); String result = invokeTemplateMessage(params); log.debug("微信支付成功模版消息结果:" + result); // return result; } // {{first.DATA}} // 支付金额:{{keyword1.DATA}} // 商品信息:{{keyword2.DATA}} // 失败原因:{{keyword3.DATA}} // {{remark.DATA}} public static void errorCancel(WXPayOrder wxPayOrder) { log.debug("支付成功,数据库更新失败!"); JSONObject params = new JSONObject(); JSONObject data = new JSONObject(); params.put("touser", wxPayOrder.getId()); params.put("template_id", PAY_FAIL_ID); data.put("first", keywordFactory("支付失败", "#173177")); data.put("keyword1", keywordFactory((float) (Math.round(wxPayOrder.getTotalPrice() * 100)) / 100 + "元", "#173177")); data.put("keyword2", keywordFactory(wxPayOrder.getProductName(), "#173177")); data.put("keyword3", keywordFactory("服务异常", "#173177")); data.put("remark", keywordFactory("请妥善保存单号,联系客服人员")); params.put("data", data); String result = invokeTemplateMessage(params); log.debug("微信支付失败结果:" + result); } public static void errorWXCancel(ConsumOrder consumOrder, String openId) { log.debug("支付成功,数据库更新失败!"); JSONObject params = new JSONObject(); JSONObject data = new JSONObject(); params.put("touser", openId); params.put("template_id", PAY_FAIL_ID); data.put("first", keywordFactory("支付失败", "#173177")); data.put("keyword1", keywordFactory((float) (Math.round(consumOrder.getTotalPrice() * 100)) / 100 + "元", "#173177")); data.put("keyword2", keywordFactory(getConsumOrderProductName(consumOrder), "#173177")); data.put("keyword3", keywordFactory("服务异常", "#173177")); data.put("remark", keywordFactory("请妥善保存单号,联系客服人员")); params.put("data", data); String result = invokeTemplateMessage(params); log.debug("微信支付失败结果:" + result); } private static String getConsumOrderProductName(ConsumOrder consumOrder) { String productName = ""; for (ProjectInfo projectInfo : consumOrder.getProjects()) productName += projectInfo.getName(); return productName; } private static JSONObject keywordFactory(String value) { JSONObject keyword = new JSONObject(); keyword.put("value", value); return keyword; } private static JSONObject keywordFactory(String value, String color) { JSONObject keyword = keywordFactory(value); keyword.put("color", color); return keyword; } /** * {{first.DATA}} * 订单编号: {{OrderSn.DATA}} * 订单状态: {{OrderStatus.DATA}} * {{remark.DATA}} */ public static void orderChanged(ConsumOrder consumOrder, String openId) { log.info("准备订单更新模版消息。。。"); Staff staff = consumOrder.getPickCarStaff(); String staffName = null; if (null != staff) { staffName = staff.getName(); } int state = consumOrder.getState(); String first; String stateString; String parkingLocation = consumOrder.getParkingLocation(); String remark = ""; String remarkSuffix = "小易爱车竭诚为您服务!"; switch (String.valueOf(state)) { case Constants.CAR_SERVICE_START: stateString = "已接车"; first = "已接到您的爱车" + consumOrder.getLicensePlate() + ",我们将马上为您服务。"; if (StringUtils.isNotEmpty(staffName)) { remark += "服务人员:" + staffName + "\\/r\\/n"; } break; case Constants.CAR_SERVICE_COMPLETE: stateString = "已完工"; first = "您的爱车" + consumOrder.getLicensePlate() + "已服务完成,等待您的取回。"; if (StringUtils.isNotEmpty(staffName)) { remark += "服务人员:" + staffName + "\\/r\\/n"; } if (StringUtils.isNotEmpty(parkingLocation)) { remark += "停车位置:" + parkingLocation + "\\/r\\/n"; } break; case Constants.CAR_SERVICE_FINISH: stateString = "已交车"; first = "您的爱车" + consumOrder.getLicensePlate() + "已交车,评价领积分。"; break; default: stateString = "已交车"; first = "您的爱车" + consumOrder.getLicensePlate() + "已交车,评价领积分。"; } JSONObject params = new JSONObject(); JSONObject data = new JSONObject(); params.put("touser", openId); params.put("template_id", ORDER_CHANGED_ID); params.put("url", "http://" + WechatConfig.APP_DOMAIN + "/index.html#/ordertrack?orderId=" + consumOrder.getId()); data.put("first", keywordFactory(first, "#173177")); data.put("OrderSn", keywordFactory(consumOrder.getId(), "#173177")); data.put("OrderStatus", keywordFactory(stateString, "#173177")); data.put("remark", keywordFactory(remark + remarkSuffix)); params.put("data", data); String result = invokeTemplateMessage(params); log.info("微信订单更新模版消息结果:" + result); } }
b66f9b8933563ca3e5137d5aee9fceb5c9d01e64
7c9ae23615dd8cb2da757a95939c9d8a96673e90
/app/src/main/java/com/yxld/xzs/view/AutoHorizontalScrollView.java
57da226b0c55aa503fcb8d3eefab2dd0fd775242
[]
no_license
StoneXL/xzs_app
9c2b034ffa8b9427b0c59d8ef1ef7019fedc94d8
b2ada4145d8f391dfa3bc93fb44b780e600ec325
refs/heads/master
2021-07-03T19:31:59.166183
2019-04-15T05:38:12
2019-04-15T05:38:12
135,100,953
0
0
null
null
null
null
UTF-8
Java
false
false
1,199
java
package com.yxld.xzs.view; import android.content.Context; import android.util.AttributeSet; import android.widget.HorizontalScrollView; import com.zhy.autolayout.AutoFrameLayout; import com.zhy.autolayout.AutoLinearLayout; import com.zhy.autolayout.utils.AutoLayoutHelper; /** * Yuan.Y.Q * Date 2017/7/24. */ public class AutoHorizontalScrollView extends HorizontalScrollView { private final AutoLayoutHelper mHelper = new AutoLayoutHelper(this); public AutoHorizontalScrollView(Context context) { super(context); } public AutoHorizontalScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public AutoHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (!isInEditMode()) { mHelper.adjustChildren(); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new AutoFrameLayout.LayoutParams(getContext(), attrs); } }
7cdc02d6556d20fff47f953445491754123f2834
2a49717024daa3f84997f5b320121c6cf868d8e7
/docker-web-embeded-jpa/src/main/java/com/jdc/locations/model/service/LocationService.java
2b7af606d2808e7bbd5a3154d259bc519fd1f585
[ "MIT" ]
permissive
minlwin/docker4j
be1a7926fce7b4ab6acd16cd1776f47b364b3eae
56274eb582fc685cc80c7e8912c9aa6aff0365b8
refs/heads/master
2023-02-08T22:45:50.099604
2020-12-26T14:34:40
2020-12-26T14:34:40
285,887,640
3
0
null
null
null
null
UTF-8
Java
false
false
853
java
package com.jdc.locations.model.service; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import com.jdc.locations.model.entity.Division; import com.jdc.locations.model.entity.Township; public class LocationService implements Serializable { private static final long serialVersionUID = 1L; private EntityManager em; public LocationService(EntityManager em) { super(); this.em = em; } public List<Division> getDevisions() { return em.createQuery("select d from Division d", Division.class).getResultList(); } public List<Township> findByDivision(int id) { return em.createQuery("select t from Township t where t.division.id = :id", Township.class) .setParameter("id", id).getResultList(); } public Division findDivisionById(int id) { return em.find(Division.class, id); } }
4b981fd8f4891792f08fcffab8b70f81a84534a3
3aa636d00d298a2ffe407e40502588a88cbd0371
/src/main/java/com/troyner/cursomc/domain/ItemPedidoPK.java
d2b83d2cec3f21c983dcc102f17a1ac963dcfcb2
[]
no_license
Troyner/cursomc
38182b4e84ca64db194ccd2ea2a33c2ab5f948c0
5ad6bb7045a2426b826c7f9ffa86baa4fd12b483
refs/heads/master
2020-06-26T16:02:39.127097
2019-08-07T15:51:50
2019-08-07T15:51:50
199,680,283
0
0
null
null
null
null
UTF-8
Java
false
false
1,435
java
package com.troyner.cursomc.domain; import java.io.Serializable; import javax.persistence.Embeddable; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Embeddable public class ItemPedidoPK implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "pedido_id") private Pedido pedido; @ManyToOne @JoinColumn(name = "produto_id") private Produto produto; public Pedido getPedido() { return pedido; } public void setPedido(Pedido pedido) { this.pedido = pedido; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((pedido == null) ? 0 : pedido.hashCode()); result = prime * result + ((produto == null) ? 0 : produto.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ItemPedidoPK other = (ItemPedidoPK) obj; if (pedido == null) { if (other.pedido != null) return false; } else if (!pedido.equals(other.pedido)) return false; if (produto == null) { if (other.produto != null) return false; } else if (!produto.equals(other.produto)) return false; return true; } }
e1aa276f34e7d2ad38ff0168e3ee8a1150b57fb3
eab9053351d6b659231d2578d9350c94c0f7a55a
/Football_Players_Transfer_System/src/main/java/com/fifa/controller/Test.java
1249b239bb5859caf94548e627dac93fb048564a
[]
no_license
pranesh14/NEU_Projects
438ab33afdd6e043386090becde2d4ebde993fb1
b637172c1c6973eb82bdd6b8a9c000806badccf6
refs/heads/master
2020-09-12T08:26:36.098815
2018-09-14T21:05:02
2018-09-14T21:05:02
94,459,637
2
0
null
null
null
null
UTF-8
Java
false
false
398
java
package com.fifa.controller; import com.fifa.dao.UserDAO; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub try { System.out.println("***** EXECUTING *****"); UserDAO userDao = new UserDAO(); System.out.println("***** DONE *****"); } catch (Exception e) { System.out.println("***** EXCEPTION: " + e.getMessage()); } } }
d12c422a221b94093ad69e27ce1dbfda87649d6c
61f8ca0d40a83127e4c06f704f20c3b0ee89bf52
/app/src/main/java/com/rodilon/unittesting/persistence/NoteDao.java
87e567c52cd2429a4b62d7151f49c096462696b1
[]
no_license
rodilon/testing
17ad6b1a22b22cb5f2bdbaf4388623c917d83e89
ca4f931296bf0735026aaeba8a399e4558aa3954
refs/heads/master
2022-12-09T03:04:02.356935
2020-09-07T18:31:13
2020-09-07T18:31:13
292,565,306
0
0
null
null
null
null
UTF-8
Java
false
false
645
java
package com.rodilon.unittesting.persistence; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.rodilon.unittesting.models.Note; import java.util.List; import io.reactivex.Single; @Dao public interface NoteDao { @Insert Single<Long> insertNote(Note note) throws Exception; @Query("SELECT * FROM notes") LiveData<List<Note>> getNotes(); @Delete Single<Integer> deleteNotes(Note note) throws Exception; @Update Single<Integer> updateNote(Note note) throws Exception; }
4df098e1b446927ba6be3789b22bdd7c43e0e698
8c69107210f40ef01ede02fce90ec8a0472142d1
/app/src/main/java/com/example/hninor/pruebahenry/features/topartist/domain/usecase/GetArtist.java
2c21a486302fe9c8bcf216264b2e1cac5c0e6dfa
[]
no_license
yoelbrinez/PruebaHenryValid
8ac476f91d3299a33228d03247af1eba63b7d9dc
ef8c58bf01ff22042d37df5aeacc6d73111b34c7
refs/heads/master
2021-09-25T05:54:39.210655
2018-10-18T22:05:06
2018-10-18T22:05:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,763
java
package com.example.hninor.pruebahenry.features.topartist.domain.usecase; import com.example.hninor.pruebahenry.core.Constants; import com.example.hninor.pruebahenry.core.communication.GEOService; import com.example.hninor.pruebahenry.core.communication.entities.Artist; import com.example.hninor.pruebahenry.core.communication.entities.TopArtistResponse; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class GetArtist { private GetArtistContract mCallback; public GetArtist() { } public void run(boolean forceUpdate, int page) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); GEOService service = retrofit.create(GEOService.class); final Call<TopArtistResponse> topArtist = service.listTopArtist(page); topArtist.enqueue(new Callback<TopArtistResponse>() { @Override public void onResponse(Call<TopArtistResponse> call, Response<TopArtistResponse> response) { if (response.isSuccessful()) { TopArtistResponse topArtistResponse = response.body(); List<Artist> artistList = topArtistResponse.getTopartists().getArtist(); mCallback.processTopArtist(artistList); } } @Override public void onFailure(Call<TopArtistResponse> call, Throwable t) { } }); } public void setmCallback(GetArtistContract mCallback) { this.mCallback = mCallback; } }
c0a3a7423219bdb0864a030a1c17cebb092c1540
315fffd337e156c64c8e7febedbb32bb9601dad3
/builtInFunctions.java
06a7a23fa44b15e2a25f12cd89a9800b3a0f37fa
[]
no_license
pravin-asp/Learning-Java
ec0d9aafda3b4094ad5842a0464c9378855a0427
0b1c482a032c3e01d9633e86fa7a64b18973b6a5
refs/heads/master
2023-06-28T02:40:09.258204
2021-08-01T06:00:39
2021-08-01T06:00:39
390,285,097
0
0
null
null
null
null
UTF-8
Java
false
false
167
java
import java.util.Scanner; public class builtInFunctions{ public static void main(String[] args){ double result = Math.pow(2, 5); System.out.println(result); } }
51da3a2402a3531287e078f04952617bb356640e
84e064c973c0cc0d23ce7d491d5b047314fa53e5
/latest9.1/bj/net/sf/saxon/regex/RegexData.java
375be84a45df14d7caecd174e78de6c1ba80f671
[]
no_license
orbeon/saxon-he
83fedc08151405b5226839115df609375a183446
250c5839e31eec97c90c5c942ee2753117d5aa02
refs/heads/master
2022-12-30T03:30:31.383330
2020-10-16T15:21:05
2020-10-16T15:21:05
304,712,257
1
1
null
null
null
null
UTF-8
Java
false
false
12,390
java
package net.sf.saxon.regex; /** * Non-instantiable class containing constant data definitions used by the various Regular Expression translators */ public class RegexData { public static final String categories = "LMNPZSC"; public static final String subCategories = "LuLlLtLmLoMnMcMeNdNlNoPcPdPsPePiPfPoZsZlZpSmScSkSoCcCfCoCn"; public static final char EOS = '\0'; public static final String[] blockNames = { "BasicLatin", "Latin-1Supplement", "LatinExtended-A", "LatinExtended-B", "IPAExtensions", "SpacingModifierLetters", "CombiningDiacriticalMarks", "Greek", "Cyrillic", "Armenian", "Hebrew", "Arabic", "Syriac", "Thaana", "Devanagari", "Bengali", "Gurmukhi", "Gujarati", "Oriya", "Tamil", "Telugu", "Kannada", "Malayalam", "Sinhala", "Thai", "Lao", "Tibetan", "Myanmar", "Georgian", "HangulJamo", "Ethiopic", "Cherokee", "UnifiedCanadianAboriginalSyllabics", "Ogham", "Runic", "Khmer", "Mongolian", "LatinExtendedAdditional", "GreekExtended", "GeneralPunctuation", "SuperscriptsandSubscripts", "CurrencySymbols", "CombiningMarksforSymbols", "LetterlikeSymbols", "NumberForms", "Arrows", "MathematicalOperators", "MiscellaneousTechnical", "ControlPictures", "OpticalCharacterRecognition", "EnclosedAlphanumerics", "BoxDrawing", "BlockElements", "GeometricShapes", "MiscellaneousSymbols", "Dingbats", "BraillePatterns", "CJKRadicalsSupplement", "KangxiRadicals", "IdeographicDescriptionCharacters", "CJKSymbolsandPunctuation", "Hiragana", "Katakana", "Bopomofo", "HangulCompatibilityJamo", "Kanbun", "BopomofoExtended", "EnclosedCJKLettersandMonths", "CJKCompatibility", "CJKUnifiedIdeographsExtensionA", "CJKUnifiedIdeographs", "YiSyllables", "YiRadicals", "HangulSyllables", // surrogates excluded because there are never any *characters* with codes in surrogate range // "PrivateUse", excluded because 3.1 adds non-BMP ranges "CJKCompatibilityIdeographs", "AlphabeticPresentationForms", "ArabicPresentationForms-A", "CombiningHalfMarks", "CJKCompatibilityForms", "SmallFormVariants", "ArabicPresentationForms-B", "Specials", "HalfwidthandFullwidthForms", "Specials" }; /** * Names of blocks including ranges outside the BMP. */ public static final String[] specialBlockNames = { "OldItalic", // TODO: these have disappeared from Schema 1.0 2nd edition, but are largely back in 1.1 "Gothic", "Deseret", "ByzantineMusicalSymbols", "MusicalSymbols", "MathematicalAlphanumericSymbols", "CJKUnifiedIdeographsExtensionB", "CJKCompatibilityIdeographsSupplement", "Tags", "PrivateUse", "HighSurrogates", "HighPrivateUseSurrogates", "LowSurrogates", }; // This file was automatically generated by CategoriesGen public static final String CATEGORY_NAMES = "NoLoMnCfLlNlPoLuMcNdSoSmCo"; public static final int[][] CATEGORY_RANGES = { { // No 0x10107, 0x10133, 0x10320, 0x10323 }, { // Lo 0x10000, 0x1000b, 0x1000d, 0x10026, 0x10028, 0x1003a, 0x1003c, 0x1003d, 0x1003f, 0x1004d, 0x10050, 0x1005d, 0x10080, 0x100fa, 0x10300, 0x1031e, 0x10330, 0x10349, 0x10380, 0x1039d, 0x10450, 0x1049d, 0x10800, 0x10805, 0x10808, 0x10808, 0x1080a, 0x10835, 0x10837, 0x10838, 0x1083c, 0x1083c, 0x1083f, 0x1083f, 0x20000, 0x2a6d6, 0x2f800, 0x2fa1d }, { // Mn 0x1d167, 0x1d169, 0x1d17b, 0x1d182, 0x1d185, 0x1d18b, 0x1d1aa, 0x1d1ad, 0xe0100, 0xe01ef }, { // Cf 0x1d173, 0x1d17a, 0xe0001, 0xe0001, 0xe0020, 0xe007f }, { // Ll 0x10428, 0x1044f, 0x1d41a, 0x1d433, 0x1d44e, 0x1d454, 0x1d456, 0x1d467, 0x1d482, 0x1d49b, 0x1d4b6, 0x1d4b9, 0x1d4bb, 0x1d4bb, 0x1d4bd, 0x1d4c3, 0x1d4c5, 0x1d4cf, 0x1d4ea, 0x1d503, 0x1d51e, 0x1d537, 0x1d552, 0x1d56b, 0x1d586, 0x1d59f, 0x1d5ba, 0x1d5d3, 0x1d5ee, 0x1d607, 0x1d622, 0x1d63b, 0x1d656, 0x1d66f, 0x1d68a, 0x1d6a3, 0x1d6c2, 0x1d6da, 0x1d6dc, 0x1d6e1, 0x1d6fc, 0x1d714, 0x1d716, 0x1d71b, 0x1d736, 0x1d74e, 0x1d750, 0x1d755, 0x1d770, 0x1d788, 0x1d78a, 0x1d78f, 0x1d7aa, 0x1d7c2, 0x1d7c4, 0x1d7c9 }, { // Nl 0x1034a, 0x1034a }, { // Po 0x10100, 0x10101, 0x1039f, 0x1039f }, { // Lu 0x10400, 0x10427, 0x1d400, 0x1d419, 0x1d434, 0x1d44d, 0x1d468, 0x1d481, 0x1d49c, 0x1d49c, 0x1d49e, 0x1d49f, 0x1d4a2, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d4a9, 0x1d4ac, 0x1d4ae, 0x1d4b5, 0x1d4d0, 0x1d4e9, 0x1d504, 0x1d505, 0x1d507, 0x1d50a, 0x1d50d, 0x1d514, 0x1d516, 0x1d51c, 0x1d538, 0x1d539, 0x1d53b, 0x1d53e, 0x1d540, 0x1d544, 0x1d546, 0x1d546, 0x1d54a, 0x1d550, 0x1d56c, 0x1d585, 0x1d5a0, 0x1d5b9, 0x1d5d4, 0x1d5ed, 0x1d608, 0x1d621, 0x1d63c, 0x1d655, 0x1d670, 0x1d689, 0x1d6a8, 0x1d6c0, 0x1d6e2, 0x1d6fa, 0x1d71c, 0x1d734, 0x1d756, 0x1d76e, 0x1d790, 0x1d7a8 }, { // Mc 0x1d165, 0x1d166, 0x1d16d, 0x1d172 }, { // Nd 0x104a0, 0x104a9, 0x1d7ce, 0x1d7ff }, { // So 0x10102, 0x10102, 0x10137, 0x1013f, 0x1d000, 0x1d0f5, 0x1d100, 0x1d126, 0x1d12a, 0x1d164, 0x1d16a, 0x1d16c, 0x1d183, 0x1d184, 0x1d18c, 0x1d1a9, 0x1d1ae, 0x1d1dd, 0x1d300, 0x1d356 }, { // Sm 0x1d6c1, 0x1d6c1, 0x1d6db, 0x1d6db, 0x1d6fb, 0x1d6fb, 0x1d715, 0x1d715, 0x1d735, 0x1d735, 0x1d74f, 0x1d74f, 0x1d76f, 0x1d76f, 0x1d789, 0x1d789, 0x1d7a9, 0x1d7a9, 0x1d7c3, 0x1d7c3 }, { // Co 0xf0000, 0xffffd, 0x100000, 0x10fffd } }; // end of generated code // This file was automatically generated by NamingExceptionsGen // class NamingExceptions { // public static final String NMSTRT_INCLUDES = // "\u003A\u005F\u02BB\u02BC\u02BD\u02BE\u02BF\u02C0\u02C1\u0559" + // "\u06E5\u06E6\u212E"; // public static final String NMSTRT_EXCLUDE_RANGES = // "\u00AA\u00BA\u0132\u0133\u013F\u0140\u0149\u0149\u017F\u017F" + // "\u01C4\u01CC\u01F1\u01F3\u01F6\u01F9\u0218\u0233\u02A9\u02AD" + // "\u03D7\u03D7\u03DB\u03DB\u03DD\u03DD\u03DF\u03DF\u03E1\u03E1" + // "\u0400\u0400\u040D\u040D\u0450\u0450\u045D\u045D\u048C\u048F" + // "\u04EC\u04ED\u0587\u0587\u06B8\u06B9\u06BF\u06BF\u06CF\u06CF" + // "\u06FA\u07A5\u0950\u0950\u0AD0\u0AD0\u0D85\u0DC6\u0E2F\u0E2F" + // "\u0EAF\u0EAF\u0EDC\u0F00\u0F6A\u1055\u1101\u1101\u1104\u1104" + // "\u1108\u1108\u110A\u110A\u110D\u110D\u1113\u113B\u113D\u113D" + // "\u113F\u113F\u1141\u114B\u114D\u114D\u114F\u114F\u1151\u1153" + // "\u1156\u1158\u1162\u1162\u1164\u1164\u1166\u1166\u1168\u1168" + // "\u116A\u116C\u116F\u1171\u1174\u1174\u1176\u119D\u119F\u11A2" + // "\u11A9\u11AA\u11AC\u11AD\u11B0\u11B6\u11B9\u11B9\u11BB\u11BB" + // "\u11C3\u11EA\u11EC\u11EF\u11F1\u11F8\u1200\u18A8\u207F\u2124" + // "\u2128\u2128\u212C\u212D\u212F\u217F\u2183\u3006\u3038\u303A" + // "\u3131\u4DB5\uA000\uA48C\uF900\uFFDC"; // public static final String NMSTRT_CATEGORIES = "LlLuLoLtNl"; // public static final String NMCHAR_INCLUDES = // "\u002D\u002E\u003A\u005F\u00B7\u0387\u06dd\u212E"; // MHK: added 06dd // public static final String NMCHAR_EXCLUDE_RANGES = // "\u00AA\u00B5\u00BA\u00BA\u0132\u0133\u013F\u0140\u0149\u0149" + // "\u017F\u017F\u01C4\u01CC\u01F1\u01F3\u01F6\u01F9\u0218\u0233" + // "\u02A9\u02B8\u02E0\u02EE\u0346\u034E\u0362\u037A\u03D7\u03D7" + // "\u03DB\u03DB\u03DD\u03DD\u03DF\u03DF\u03E1\u03E1\u0400\u0400" + // "\u040D\u040D\u0450\u0450\u045D\u045D\u0488\u048F\u04EC\u04ED" + // "\u0587\u0587\u0653\u0655\u06B8\u06B9\u06BF\u06BF\u06CF\u06CF" + // "\u06FA\u07B0\u0950\u0950\u0AD0\u0AD0\u0D82\u0DF3\u0E2F\u0E2F" + // "\u0EAF\u0EAF\u0EDC\u0F00\u0F6A\u0F6A\u0F96\u0F96\u0FAE\u0FB0" + // "\u0FB8\u0FB8\u0FBA\u1059\u1101\u1101\u1104\u1104\u1108\u1108" + // "\u110A\u110A\u110D\u110D\u1113\u113B\u113D\u113D\u113F\u113F" + // "\u1141\u114B\u114D\u114D\u114F\u114F\u1151\u1153\u1156\u1158" + // "\u1162\u1162\u1164\u1164\u1166\u1166\u1168\u1168\u116A\u116C" + // "\u116F\u1171\u1174\u1174\u1176\u119D\u119F\u11A2\u11A9\u11AA" + // "\u11AC\u11AD\u11B0\u11B6\u11B9\u11B9\u11BB\u11BB\u11C3\u11EA" + // "\u11EC\u11EF\u11F1\u11F8\u1200\u18A9\u207F\u207F\u20DD\u20E0" + // "\u20E2\u2124\u2128\u2128\u212C\u212D\u212F\u217F\u2183\u2183" + // "\u3006\u3006\u3038\u303A\u3131\u4DB5\uA000\uA48C\uF900\uFFDC"; // public static final String NMCHAR_CATEGORIES = "LlLuLoLtNlMcMeMnLmNd"; // end of generated code public static final char UNICODE_3_1_ADD_Lu = '\u03F4'; // added in 3.1 public static final char UNICODE_3_1_ADD_Ll = '\u03F5'; // added in 3.1 // 3 characters changed from No to Nl between 3.0 and 3.1 public static final char UNICODE_3_1_CHANGE_No_to_Nl_MIN = '\u16EE'; public static final char UNICODE_3_1_CHANGE_No_to_Nl_MAX = '\u16F0'; public static final String CATEGORY_Pi = "\u00AB\u2018\u201B\u201C\u201F\u2039"; // Java doesn't know about category Pi public static final String CATEGORY_Pf = "\u00BB\u2019\u201D\u203A"; // Java doesn't know about category Pf } // // The contents of this file are subject to the Mozilla Public License Version 1.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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is: all this file // // The Initial Developer of the Original Code is Michael H. Kay. // // Contributor(s): //
8026e805421b54a1bdc32b1af4cebde25faece7c
4e7f049d258e43df879cde81f15d1e5e4de27197
/cart-service/src/main/java/com/example/demo/cart/CartController.java
ba26c28be3a1566d7b3f01eef9a4008c07803fad
[]
no_license
mdSafdarKhan/e-commerce-poc
fbcd430b65ef67e029497cc8344acfebb5122981
0b424c33b155615fbcee4088bd9638043de6d5d5
refs/heads/master
2022-06-10T09:24:42.282706
2020-05-05T17:39:31
2020-05-05T17:39:31
261,107,509
0
0
null
null
null
null
UTF-8
Java
false
false
1,671
java
package com.example.demo.cart; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/cart") public class CartController { //@Autowired RedisTemplate<String, Cart> redisTemplate; @Autowired CartRepository cartRepository; @GetMapping("/{id}") public Cart getCart(@PathVariable(name = "id") String id) { System.out.println("id: " + id + " ---> " + new Date().toString()); return cartRepository.findById(id).get(); } @PostMapping public Cart createCart(@RequestBody Cart cart) { String cartId = "" + new Date().getTime(); Cart c = new Cart(); c.setCartId(cartId); c.setCurrency(cart.getCurrency()); c.setTotal(cart.getTotal()); List<CartItem> cItems = new ArrayList<>(); for(CartItem cartItem: cart.getCartItems()) { CartItem cItem = new CartItem(); cItem.setCartItemId("" + new Date().getTime()); cItem.setName(cartItem.getName()); cItem.setPrice(cartItem.getPrice()); cItem.setCurrency(cartItem.getCurrency()); cItems.add(cItem); } c.setCartItems(cItems); c = cartRepository.save(c); return c; } }
2799cdcd7e1cf7a3e62f613abcc5fd5d96778425
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/jdbi/learning/3664/BridgeMethodHandlerFactory.java
19b4b9199a884963571a7d4014c2448364492c40
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,342
java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jdbi.v3.sqlobject; import java.lang.invoke.MethodHandle; import java.lang.reflect.Method; import java.util.Objects; import java.util.Optional; import java.util.stream.IntStream; import java.util.stream.Stream; import org.jdbi.v3.core.internal.Throwables; class BridgeMethodHandlerFactory implements HandlerFactory { @Override public Optional<Handler> buildHandler(Class<?> sqlObjectType, Method method) { if (!method.isBridge()) { return Optional.empty(); } return Stream.of(sqlObjectType.getMethods()) .filter(candidate -> !candidate.isBridge() && Objects.equals(candidate.getName(), method.getName()) && candidate.getParameterCount() == method.getParameterCount()) .filter(candidate -> { Class<?>[] candidateParamTypes = candidate.getParameterTypes(); Class<?>[] methodParamTypes = method.getParameterTypes(); return IntStream.range(0, method.getParameterCount()) .allMatch(i -> methodParamTypes[i].isAssignableFrom(candidateParamTypes[i])); }) .<Handler>map(m -> { final MethodHandle mh = unreflect(sqlObjectType, m); return (target, args, handle) -> Throwables.throwingOnlyUnchecked(() -> mh.bindTo(target).invokeWithArguments(args)); }) .findFirst(); } private static MethodHandle unreflect(Class<?> sqlObjectType, Method m) { try { return DefaultMethodHandler.lookupFor(sqlObjectType).unreflect(m); } catch (IllegalAccessException e) { throw new UnableToCreateSqlObjectException("Bridge handler couldn't unreflect " + sqlObjectType + " " + m, e); } } }
1ce3bdac1d81a21b0f269e756b91720002a192db
0c1b67ef108ea4f221038293859f06679492e002
/FourthLecturePolimorphism/OverloadOperations/Main.java
e5432213a21cbff9338ae8828d82609e71e6e0b5
[]
no_license
krasimirvasilev1/Java-8-OOPBasic
7417452a16ba34cff8cad8b82cf8335115a20c49
d15298b8d205b07eab65e7efce89fe1e6c7e7a0a
refs/heads/master
2021-05-07T01:31:20.408533
2018-01-06T17:29:37
2018-01-06T17:29:37
110,358,140
0
0
null
null
null
null
UTF-8
Java
false
false
349
java
package FourthLecturePolimorphism.OverloadOperations; public class Main { public static void main(String[] args) { MathOperation mathOperation = new MathOperation(); System.out.println(mathOperation.add(2,2)); System.out.println(mathOperation.add(2,3,4)); System.out.println(mathOperation.add(2,3,4,5)); } }
9f9075f972e3667141fb2ff17775d4079c824779
0e97f143d4d2d48ef203fd00c822d059df949f19
/app/src/androidTest/java/com/zqj/roundview/ExampleInstrumentedTest.java
1819aabab781a90d3bae2e6f165ce8f48a59145a
[]
no_license
zqjhoney/RoundView
79cf8259b840f8d36b7607e4f682e78695608061
fcd1831fe575c53c674c82b308595e7b66b96a1e
refs/heads/master
2021-08-19T19:24:48.350726
2017-11-27T07:52:57
2017-11-27T07:52:57
112,165,038
0
0
null
null
null
null
UTF-8
Java
false
false
735
java
package com.zqj.roundview; 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() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.zqj.roundview", appContext.getPackageName()); } }
8a40176b183205acd1995b25752a74bcb9690878
bfb80cec90b114c060016791f7f34c8b5cd4d9ed
/src/com/sbs/java/crud/dto/Member.java
2ecb86664782d8d007a6ba5e5a321dc0ce02ac71
[]
no_license
jihey03040/JAVA_2021_07_15_CRUD
1dda7e8fcd6aa1766b86d4db5de20060ae4c5d98
42e496474aad59fd5f0f04df324bd9240480b060
refs/heads/master
2023-07-12T01:37:16.492415
2021-08-06T11:08:51
2021-08-06T11:08:51
386,139,319
0
0
null
null
null
null
UTF-8
Java
false
false
342
java
package com.sbs.java.crud.dto; public class Member extends Dto { public String loginId; public String loginPw; public String name; public Member(int id, String regDate, String loginId, String loginPw, String name) { this.id = id; this.regDate = regDate; this.loginId = loginId; this.loginPw = loginPw; this.name = name; } }
0ea0d237638e8196eda5311330e45c0a884a6f1e
486cee97d48d49b834659f3e269684138d7a556f
/src/de/MangoleHD/IMBedwars/Commands/Inventorys/cmd_adminInventory.java
6a8b7ec6c5ef1add6ee95e5d1a9e12d3abd1af15
[]
no_license
IclipseMangole/IMBedwars
dc43798155a328a6a9dc305f92a472c9dec7c290
80d46e3ad14fba0267f13959868af7cb790520b9
refs/heads/master
2023-01-25T04:20:10.222182
2020-11-27T14:35:43
2020-11-27T14:35:43
260,420,281
0
0
null
null
null
null
UTF-8
Java
false
false
89
java
package de.MangoleHD.IMBedwars.Commands.Inventorys; public class cmd_adminInventory { }
2628e6421a959c929b7daa265714df7dbca8a704
a2ed602db942c48b8216b878af53f300457e7f66
/sellersignupservice/sellersignupService/src/main/java/com/project/SellerSignupService/model/SellerSignupPojo.java
fb9b558c73637b4f75ea85fe1b00195380a63c12
[]
no_license
sravanI2207/emart_project_final
0254db607db13721b49bf8111ecb5db565da0859
b50a51f395e47d0f4b17f0bc77dd4e57e336be7f
refs/heads/master
2023-01-12T09:21:21.289600
2020-03-14T08:53:39
2020-03-14T08:53:39
247,242,841
0
0
null
2023-01-07T15:56:07
2020-03-14T08:54:07
Java
UTF-8
Java
false
false
2,546
java
package com.project.SellerSignupService.model; import java.util.Set; public class SellerSignupPojo { private int id; private String username; private String password; private String company; private String brief; private int gst; private String address; private String email; private int contact; private String website; Set<ItemPojo> allItems; public SellerSignupPojo() { super(); // TODO Auto-generated constructor stub } public SellerSignupPojo(int id, String username, String password, String company, String brief, int gst, String address, String email, int contact, String website, Set<ItemPojo> allItems) { super(); this.id = id; this.username = username; this.password = password; this.company = company; this.brief = brief; this.gst = gst; this.address = address; this.email = email; this.contact = contact; this.website = website; this.allItems = allItems; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBrief() { return brief; } public void setBrief(String brief) { this.brief = brief; } public int getGst() { return gst; } public void setGst(int gst) { this.gst = gst; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getContact() { return contact; } public void setContact(int contact) { this.contact = contact; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Set<ItemPojo> getAllItems() { return allItems; } public void setAllItems(Set<ItemPojo> allItems) { this.allItems = allItems; } @Override public String toString() { return "SellerSignupPojo [id=" + id + ", username=" + username + ", password=" + password + ", company=" + company + ", brief=" + brief + ", gst=" + gst + ", address=" + address + ", email=" + email + ", contact=" + contact + ", website=" + website + ", allItems=" + allItems + "]"; } }
1961a3c5a3f9d9dc0e504aa22e1c4a680f40d25f
a1e33c87754eabb3775c81fe2e024d708c8a2790
/ModuleDemo/app/src/test/java/com/kinson/demo/ExampleUnitTest.java
3d4f76164f92f37f8d66f45c06466f1abfe61fff
[]
no_license
smallKinson/HelloWorld
02cf24ca27f1939109d8bbc2f24fd141c85ca583
8742dad90d49b3501862e932f66da50e44f97e6c
refs/heads/master
2020-03-27T23:44:27.527283
2020-03-11T08:25:07
2020-03-11T08:25:07
147,341,963
0
0
null
null
null
null
UTF-8
Java
false
false
393
java
package com.kinson.demo; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
a0de79ddf4072a6db569c54dbb829b2f2ad15928
cf82f1989beafe7b2ea3aade912cf22ee5598a69
/src/Document.java
688628356d74921711139deec9f1fca575176233
[]
no_license
fool8474/IR_Inverted_index
e30108804800b87b1d64d8685f8f3e237f901135
439e031112b5e7fe1318044e2fcc8edd2283d162
refs/heads/master
2020-03-30T07:42:48.665506
2018-10-11T16:02:19
2018-10-11T16:02:19
150,961,136
0
0
null
null
null
null
UTF-8
Java
false
false
435
java
import java.util.TreeSet; class Document { TreeSet <String> dictionary; //use treeset for dictionary String pageName; private String contents; int docID; public Document(String pageName, int docID) { this.pageName = pageName; this.docID = docID; contents = ""; dictionary = new TreeSet<>(); } void addContent(String newContents) { contents += newContents; } String getContents() { return contents; } }
a43f72a0dda756965fb827c9cd9b0c44300bd8d6
3a3fb6129e5d2d90247075f00c31f0cf3739c1de
/app/src/main/java/mytodolist/androidtodolist/adapters/DoneTaskViewListAdapter.java
a813b97bd13470fce1658b0c7d84065814c1fb7b
[]
no_license
octaviocarpes/android-todo-list
4539b998a8062bb40dc96780dd69364b9e868c21
45d13631b4a60a0fc3d509173517f5e0f5a82bdc
refs/heads/master
2020-03-24T08:20:38.597733
2018-08-06T13:59:22
2018-08-06T13:59:22
142,592,909
0
0
null
null
null
null
UTF-8
Java
false
false
2,336
java
package mytodolist.androidtodolist.adapters; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import mytodolist.androidtodolist.R; import mytodolist.androidtodolist.model.DoneTaskManager; import mytodolist.androidtodolist.model.Task; import java.util.ArrayList; import mytodolist.androidtodolist.model.Task; public class DoneTaskViewListAdapter extends ArrayAdapter { private Activity context; private ArrayList<Task> doneTasks; public DoneTaskViewListAdapter(Activity context, ArrayList<Task> doneTasks) { super(context, R.layout.done_task_list_view_row, doneTasks); this.context = context; this.doneTasks = doneTasks; } public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.done_task_list_view_row, null, true); TextView taskNameTextView = (TextView) rowView.findViewById(R.id.doneTaskDescriptionID); TextView taskDateTextView = (TextView) rowView.findViewById(R.id.doneTaskDateID); taskNameTextView.setText(doneTasks.get(position).getDescription()); taskDateTextView.setText(doneTasks.get(position).getCurrentDate()); ImageButton deleteTaskButton = (ImageButton) rowView.findViewById(R.id.deleteTaskButtonID); deleteTaskButton.setTag(position); ImageButton restoreTaskButton = (ImageButton) rowView.findViewById(R.id.restoreTaskButtonID); restoreTaskButton.setTag(position); deleteTaskButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { removeRow(view); updateList(DoneTaskManager.getInstance().getDoneTasks()); } }); notifyDataSetChanged(); return rowView; } private void removeRow(View view) { Integer index = (Integer) view.getTag(); doneTasks.remove(index.intValue()); } public void updateList(ArrayList<Task> items) { this.doneTasks = items; this.notifyDataSetChanged(); } }
1619290d9370d76a852071068caf07f53c03f8c0
b72ffbd67905b6695b1b2cc4cbe328392741ea9f
/platform/platform-impl/src/com/intellij/notification/impl/NotificationGroupEP.java
825e80d0c85721e4a0bad50060290d76b804df01
[ "Apache-2.0" ]
permissive
samofcorinth/intellij-community
ad4db38dfa9b296b8e6cde71a7fd4b2dc463a0d8
c789b009e72bd05069b5023d58deaa9ecb1603ac
refs/heads/master
2023-05-08T10:56:00.042341
2021-06-07T20:09:41
2021-06-07T20:11:17
267,161,548
0
0
Apache-2.0
2020-05-26T22:05:22
2020-05-26T22:05:21
null
UTF-8
Java
false
false
5,472
java
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.notification.impl; import com.intellij.BundleBase; import com.intellij.DynamicBundle; import com.intellij.notification.Notification; import com.intellij.notification.NotificationDisplayType; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginAware; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.extensions.RequiredElement; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.util.xmlb.Converter; import com.intellij.util.xmlb.annotations.Attribute; import com.intellij.util.xmlb.annotations.Transient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ResourceBundle; /** * Registers notification group. * <p> * Use {@link com.intellij.notification.NotificationGroupManager#getNotificationGroup(String)} to obtain instance via {@link #id}. * </p> * <p> * See <a href="https://jetbrains.org/intellij/sdk/docs/user_interface_components/notifications.html#top-level-notifications">Top-Level Notifications</a>. * </p> */ public final class NotificationGroupEP implements PluginAware { static final ExtensionPointName<NotificationGroupEP> EP_NAME = new ExtensionPointName<>("com.intellij.notificationGroup"); @Attribute("id") @RequiredElement public @NlsSafe String id; @Attribute("displayType") @RequiredElement public DisplayType displayType; @Attribute("isLogByDefault") public boolean isLogByDefault = true; @Attribute("toolWindowId") public String toolWindowId; @Attribute("icon") public String icon; /** * Message bundle, e.g. {@code "messages.DiagnosticBundle"}. * If unspecified, plugin's {@code <resource-bundle>} is used. * * @see #key */ @Attribute("bundle") public String bundle; /** * Message key for {@link #getDisplayName}. * * @see #bundle */ @Attribute("key") @NlsContexts.NotificationTitle public String key; /** * Semicolon-separated list of notificationIds which should be recorded in feature usage statistics. * * @see Notification#getDisplayId */ @Attribute(value = "notificationIds", converter = IdParser.class) public @Nullable List<String> notificationIds; private static final class IdParser extends Converter<List<String>> { @Override public @NotNull List<String> fromString(@NotNull String value) { if (value.isEmpty()) { return Collections.emptyList(); } String[] values = StringUtilRt.convertLineSeparators(value, "").split(";"); List<String> result = new ArrayList<>(values.length); for (String item : values) { if (!item.isEmpty()) { result.add(item.trim()); } } return result; } @NotNull @Override public String toString(@NotNull List<String> ids) { return String.join(",", ids); } } private PluginDescriptor pluginDescriptor; public @NlsContexts.NotificationTitle @Nullable String getDisplayName() { String baseName = bundle == null ? getPluginDescriptor().getResourceBundleBaseName() : bundle; if (baseName == null || key == null) { return id; } ResourceBundle resourceBundle = DynamicBundle.INSTANCE.getResourceBundle(baseName, getPluginDescriptor().getPluginClassLoader()); return BundleBase.messageOrDefault(resourceBundle, key, null); } public @Nullable Icon getIcon() { return icon == null ? null : IconLoader.findIcon(icon, getClass()); } @Transient public final @NotNull PluginDescriptor getPluginDescriptor() { return pluginDescriptor; } @Override public void setPluginDescriptor(@NotNull PluginDescriptor value) { pluginDescriptor = value; } public @Nullable NotificationDisplayType getDisplayType() { return displayType == null ? null : displayType.getNotificationDisplayType(); } @Override public String toString() { return "NotificationGroupEP{" + "id='" + id + '\'' + ", displayType=" + displayType + ", isLogByDefault=" + isLogByDefault + ", toolWindowId='" + toolWindowId + '\'' + ", icon='" + icon + '\'' + ", bundle='" + bundle + '\'' + ", key='" + key + '\'' + ", notificationIds='" + notificationIds + '\'' + ", pluginDescriptor=" + pluginDescriptor + '}'; } private enum DisplayType { /** * No popup. */ NONE(NotificationDisplayType.NONE), /** * Expires automatically after 10 seconds. */ BALLOON(NotificationDisplayType.BALLOON), /** * Needs to be closed by user. */ STICKY_BALLOON(NotificationDisplayType.STICKY_BALLOON), /** * Tool window balloon. */ TOOL_WINDOW(NotificationDisplayType.TOOL_WINDOW); private final NotificationDisplayType myNotificationDisplayType; DisplayType(NotificationDisplayType type) {myNotificationDisplayType = type;} NotificationDisplayType getNotificationDisplayType() { return myNotificationDisplayType; } } }
0c72bd77d88d9f5ec8c47fdc6369c36473bcbe3b
9923e30eb99716bfc179ba2bb789dcddc28f45e6
/openapi-generator/java-play-framework/app/apimodels/HumidityResponseSensors.java
e0c98a5fe8a062dc3c27f02ff9315927418f4a4a
[ "Apache-2.0" ]
permissive
silverspace/samsara-sdks
cefcd61458ed3c3753ac5e6bf767229dd8df9485
c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa
refs/heads/master
2020-04-25T13:16:59.137551
2019-03-01T05:49:05
2019-03-01T05:49:05
172,804,041
2
0
null
null
null
null
UTF-8
Java
false
false
2,760
java
package apimodels; import com.fasterxml.jackson.annotation.*; import java.util.Set; import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; /** * HumidityResponseSensors */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-03-01T05:34:42.270Z[GMT]") @SuppressWarnings({"UnusedReturnValue", "WeakerAccess"}) public class HumidityResponseSensors { @JsonProperty("name") private String name; @JsonProperty("humidity") private Integer humidity; @JsonProperty("id") private Long id; public HumidityResponseSensors name(String name) { this.name = name; return this; } /** * Name of the sensor. * @return name **/ public String getName() { return name; } public void setName(String name) { this.name = name; } public HumidityResponseSensors humidity(Integer humidity) { this.humidity = humidity; return this; } /** * Currently reported relative humidity in percent, from 0-100. * @return humidity **/ public Integer getHumidity() { return humidity; } public void setHumidity(Integer humidity) { this.humidity = humidity; } public HumidityResponseSensors id(Long id) { this.id = id; return this; } /** * ID of the sensor. * @return id **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HumidityResponseSensors humidityResponseSensors = (HumidityResponseSensors) o; return Objects.equals(name, humidityResponseSensors.name) && Objects.equals(humidity, humidityResponseSensors.humidity) && Objects.equals(id, humidityResponseSensors.id); } @Override public int hashCode() { return Objects.hash(name, humidity, id); } @SuppressWarnings("StringBufferReplaceableByString") @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class HumidityResponseSensors {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" humidity: ").append(toIndentedString(humidity)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
a5d1d12dc97dfcd21bb11619f29944330ed795fa
f3b8f0a8a5e2063ea00cd61e85f373a239aa8530
/jTPS/src/jtps/PostTransaction.java
61211e57ed6bffa176105f635d1f006ecdedfc67
[]
no_license
rahelEZ/MetroMapMaker
baf3dfcda510404abddf2842df06a369367647bc
9db68b28f64c2aa13898c5575b0735d3c6d6c9f0
refs/heads/master
2020-04-09T17:16:42.535874
2018-12-05T07:23:03
2018-12-05T07:23:03
160,476,077
0
0
null
null
null
null
UTF-8
Java
false
false
320
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 jtps; /** * * @author Rahel Zewde */ public interface PostTransaction { public void run(boolean redo, boolean undo); }
22df5e3d0d1f47df36eebf58b2e4e7b0e63c044d
4c33926a5beaa9e491dd8e6fa10f5b1dcafe6194
/projeto-jpa/src/main/java/br/com/alura/jpa/modelo/TipoMovimentacao.java
85b5b9c7472739e3ada846e407e5e257fde6706c
[]
no_license
eugabiviana/jpaAlura
cada190ce770a4e2879b1c717502d47da558c203
745fa13dc070d4604bec5483eeedd525a3e2ad49
refs/heads/main
2023-04-15T19:36:10.583789
2021-04-19T13:49:28
2021-04-19T13:49:28
358,928,436
3
0
null
null
null
null
UTF-8
Java
false
false
88
java
package br.com.alura.jpa.modelo; public enum TipoMovimentacao { ENTRADA, SAIDA; }
90272cfc21712382d53cb860aea91cab4586d152
25dc9fa2b9375d1c2543cb2a631b8ce050e403ed
/cs10lab2/src/ListTest.java
55a5479cc90c4b0ffb71b903105b118e58c6df0c
[]
no_license
Dartaran/CS10
415573c4efa7f887a857d9143c02b38a365d4fb8
6a4ace3f933971eaef17e6423551a94b9e2ecdb8
refs/heads/master
2021-01-12T17:06:35.769249
2016-09-23T20:09:43
2016-09-23T20:09:43
69,057,318
0
0
null
null
null
null
UTF-8
Java
false
false
3,806
java
/** * ListTest.java * * An interactive driver program to test list functions. * This program is good to run with the debugger. * * Based on earlier demos by THC, Scot Drysdale, and others. * Modified by Scot Drysdale on 11/16/04 to make methods closer to those in Java's * LinkedList class. * * @author Scot Drysdale * @author Prasad Jayanti: changed the interface name from CS10LinkedList to CS10ListADT, April 11 2012 */ import java.util.Scanner; public class ListTest { public static void main(String args[]) { // Create a list to play with, initially empty. CS10LinkedList<String> theList = new SmartSentinelDLL<String>(); char command; // a command String name; // a name Scanner input = new Scanner(System.in); do { System.out.print("Command (q, C, a, f, l, c, r, p, h, t, n, H, g, s, ?): "); command = input.nextLine().charAt(0); switch (command) { case 'q': // Quit System.out.println("Bye!"); break; case 'C': // Clear theList.clear(); break; case 'a': // Add System.out.print("Enter name: "); name = input.nextLine(); theList.add(name); break; case 'f': // Add first System.out.print("Enter name: "); name = input.nextLine(); theList.addFirst(name); break; case 'l': // Add last System.out.print("Enter name: "); name = input.nextLine(); theList.addLast(name); break; case 'c': // Contains System.out.print("Enter name: "); name = input.nextLine(); if (theList.contains(name)) System.out.println("Found " + name); else System.out.println("Didn't find " + name); break; case 'r': // Remove theList.remove(); break; case 'p': // Print if (theList.isEmpty()) System.out.println("List is empty"); else System.out.print(theList); break; case 'h': // Head System.out.println(theList.getFirst()); break; case 't': // Tail System.out.println(theList.getLast()); break; case 'n': // Next System.out.println(theList.next()); break; case 'H': // Has Next? if (theList.hasNext()) System.out.println("The list has a next element"); else System.out.println("The list does not have a next element"); break; case 'g': // Get Current System.out.println(theList.get()); break; case 's': // Set System.out.print("Enter name: "); name = input.nextLine(); theList.set(name); break; case '?': // Print all the commands System.out.println("Commands are\n q: quit\n C: clear\n a: add\n " + "f: addFirst\n l: addLast\n c: contains\n r: remove\n p: print\n " + "h: head\n t: tail\n n: next\n H: has next\n " + "g: get current\n s: set current\n ?: print this command list\n"); break; default: System.out.println("Huh?"); } } while (command != 'q'); input.close(); } }
bf4255297efe82512d117def6860a0fac4ab3de7
cb0333d6e87fb71a919461665070fdf50f838e73
/day20.0811/code/consumer_productor/Product.java
bb4b8563e72f3bdc4541857a3b42e7b8b4132230
[]
no_license
Tempo59/Java
2622fed206f2f8238f460f8a098e8e0c3483af8e
8407456fa5bbfe318a412f9528e54e1e7f3a73cd
refs/heads/master
2021-01-02T09:03:59.051930
2017-08-21T12:15:23
2017-08-21T12:15:23
99,063,045
0
0
null
2017-08-02T06:31:49
2017-08-02T02:26:37
null
UTF-8
Java
false
false
299
java
package consumer_productor; public class Product { private String name; private int id; public void setName(String name) { this.name = name; this.id++; } @Override public String toString() { return "Product [name=" + name + ", id=" + id + "]"; } public Product() { super(); } }
8767d0b046d1358a2163611c685ef183714c7288
b2e79cc484ac077651aa3eefe7640dd739cb9353
/action-zuul-client/src/main/java/com/yixiu/action/zuul/client/ZuulClient.java
714e38421ffcc433dcb119c589285e464de4adba
[]
no_license
liuchangliyixin/spring-cloud-netf-all
7f17ccb1e51aff5328e96ee6acef7b2b243dc452
fd8142e12ac8691261baa546d4dfc45e3ad1cd09
refs/heads/master
2022-11-15T16:10:21.163557
2020-07-09T17:06:23
2020-07-09T17:06:23
277,838,781
0
0
null
null
null
null
UTF-8
Java
false
false
536
java
package com.yixiu.action.zuul.client; import org.springframework.boot.SpringApplication; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; @SpringCloudApplication @EnableZuulProxy public class ZuulClient { public static void main(String[] args) { SpringApplication.run(ZuulClient.class,args); } @Bean public SampleFilter sampleFilter(){ return new SampleFilter(); } }
ea956385c03174951cdec09ca4d1ebf59cd75568
995c038015036706cabcb1fae51f084d222aec90
/src/main/java/com/abhishek/SpringBootMongoDB/service/TodoService.java
8ae1c5d92afb5641ce27d2ee52705082b70fdc81
[]
no_license
AbhishekL2018/SpringBootMongoREST
c2570bb2b051082cc5b2f28a7da76405255020c5
8e9eda3c431275efbb1aba226720b4c71b86d424
refs/heads/master
2023-01-27T13:34:30.589119
2020-12-02T11:55:36
2020-12-02T11:55:36
317,822,327
0
0
null
null
null
null
UTF-8
Java
false
false
658
java
package com.abhishek.SpringBootMongoDB.service; import com.abhishek.SpringBootMongoDB.exception.TodoCollectionException; import com.abhishek.SpringBootMongoDB.model.TodoDTO; import javax.validation.ConstraintViolationException; import java.util.List; public interface TodoService { void createTodo(TodoDTO todo) throws ConstraintViolationException, TodoCollectionException; List<TodoDTO> getAllTodos(); TodoDTO getSingleTodo(String id) throws TodoCollectionException; void updateTodo(String id, TodoDTO newTodo) throws ConstraintViolationException, TodoCollectionException; void deleteTodo(String id) throws TodoCollectionException; }
1205b91137b92f8c30d51a79fe7f71b4891f54ea
382779327ad61e7a1dfed3d8a6f4775e481c964a
/src/com/example/oracle10/three/ThreeToast.java
fa217d1d15d29fa57c68bd051c022a39298a2524
[ "Apache-2.0" ]
permissive
iscodem/Android_Oracle
879b7a2b64323d28dd99e98883685fe69b6e0c2f
c8cc795993ac61de0bb1e00ecee3f9a662fe7ff3
refs/heads/master
2021-01-21T10:34:59.808637
2016-10-01T08:19:59
2016-10-01T08:19:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
554
java
package com.example.oracle10.three; import android.content.Context; import android.widget.Toast; public class ThreeToast { private Toast mToast; private Context context; public ThreeToast(Context context) { this.context = context; } public void showToast(String text) { if (mToast == null) { mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT); } else { mToast.setText(text); mToast.setDuration(Toast.LENGTH_SHORT); } mToast.show(); } public void cancelToast() { if (mToast != null) { mToast.cancel(); } } }
2e710a9013652a214e1b9e645f6d106f0106727f
2ec67b04f9da7ea270e3e305fd08806b77af6b01
/project/stage/ASTNodes/PrintStatement.java
625e915b270aeeeb3ceabc69cb772e03dc101bd8
[]
no_license
ShaeBrown/compiler-contruction
721a9b0ff2fcc917f25be6fa04f58a6efc1ab303
8ac7602cecd64bc62ccb38e3216ccf1f68dffad9
refs/heads/master
2021-09-09T11:35:33.701482
2018-03-15T18:07:26
2018-03-15T18:07:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
773
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 ASTNodes; import IR.IR; import Visitors.IRVisitor; import Visitors.Visitor; /** * * @author shaebrown */ public class PrintStatement extends Statement { public Expression e; public PrintStatement(Expression e) { this.e = e; } @Override public void accept(Visitor v) { v.visit(this); } @Override public int getLineNum() { return e.getLineNum(); } @Override public int getPos() { return e.getPos(); } @Override public IR accept(IRVisitor v) { return v.visit(this); } }
a592cef63602eda65ef3bb77561e390e9bdd2346
e843fe92649ff61085e385100062d1c697e3f26c
/app/src/main/java/com/example/musta/englishhelper/ShowWordDetails.java
39cc6eea04b0339c61eed4bf2eb895093b0274e6
[]
no_license
MustaMohamed/English-Helper
e672881380c484298d3b049eb0a07584a8b7d89f
eb1bd7e79b4a7f3d86693d5c6d618bbada51a526
refs/heads/master
2021-06-23T14:34:42.914176
2017-08-16T06:18:04
2017-08-16T06:18:04
100,303,218
0
0
null
null
null
null
UTF-8
Java
false
false
856
java
package com.example.musta.englishhelper; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class ShowWordDetails extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_word_details); ((TextView)findViewById(R.id.txtV_wordDetailsTitle)).setText(getIntent().getStringExtra("wordDetailsTitle")); ((ListView)findViewById(R.id.lstV_wordDetailsList)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getIntent().getStringArrayListExtra("wordDetailsArray"))); this.setTitle(getIntent().getStringExtra("wordDetailsTitle")); } }
1e989b45caf81cd029d7ff4b8fb83fc5026c60e0
376cc3f7524eb61a8bee0cb958fc4147d6d0ccb6
/Java/src/uk/ac/manchester/cs/wireit/module/OutputListModule.java
d66630568c0855e9fe0706f75303c69d4153e8fc
[ "MIT" ]
permissive
Christian-B/wireit
36f68cc84aa9ef207713b938a6b72aa2b144cfc9
f923bdda4f1708317fcebf0582264bfa1667eb1b
refs/heads/master
2021-04-18T19:36:24.707304
2011-11-30T16:42:11
2011-11-30T16:42:11
2,567,921
0
0
null
null
null
null
UTF-8
Java
false
false
2,668
java
package uk.ac.manchester.cs.wireit.module; import uk.ac.manchester.cs.wireit.utils.ListUtils; import uk.ac.manchester.cs.wireit.exception.WireItRunException; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import uk.ac.manchester.cs.wireit.event.OutputListener; /** * Module to receive the output from a depth 1 Upstream Modules and return these to wireIt. * <p> * This module is only expected to save any inputs which iut does in a single String * with the values tokenized with a newline. * This format is used as it is the one expcted by WireIt's textfield. * <p> * WARNING: This is a prototype so does not yet handle all possible input types. Please Exstend accordingly. * @author Christian */ public class OutputListModule extends OutputModule implements OutputListener { /** * Constructor for passing the json to the super class. * @param json JSON representation of the modules. * @throws JSONException Thrown if the json is not in the expected format. */ public OutputListModule (JSONObject json) throws JSONException{ super(json); } /** * Revieves output which could be a list or even list of lists and saves A single long String. * <p> * The output format of a Singkle String with the values split by newlines # * is because that is what WireIt's textField uses. * <p> * Lists of Lists are flattend. * <p> * WARNING: This is a prototype so does not yet handle all possible input types. Please Exstend accordingly. * @param outputBuilder Logging buffer. * @throws WireItRunException An unexpected Object Type. Please extend the method, */ public void outputReady(Object output, StringBuilder outputBuilder) throws WireItRunException { //ystem.out.println("InnerListLisener.outputReady"); //ystem.out.println(output); //ystem.out.println(output.getClass()); String[] array; if (output instanceof String[]){ array = (String[]) output; } else if (output instanceof ArrayList){ array = ListUtils.toStringArray(output); } else { throw new WireItRunException("Unexpected output type " + output.getClass()); } if (array.length == 0){ values.put(PORT_NAME, ""); } else { StringBuilder builder = new StringBuilder(array[0]); for (int i = 1; i < array.length; i++ ){ builder.append("\n"); builder.append(array[i]); } values.put(PORT_NAME, builder.toString()); } } }
0f2414c98f30acc8201f1f5fe6fd30daf0ccea7c
459921b16e9cff217feaab77f1aa700c373146bc
/permissonslibrary/src/main/java/com/zm/permissonslibrary/Permission/PermissionHelper.java
fd2d1eabe97f5f367e8210446e3a30602d8ee7e2
[]
no_license
SilenceMing/PermissionDemo
1a8025d55b16ed4e578a41e8a10e478802ef76d5
1c5ecd2706798478f7768caa9e02e826baad9945
refs/heads/master
2021-06-19T23:50:55.984012
2017-08-11T08:28:11
2017-08-11T08:28:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,247
java
package com.zm.permissonslibrary.Permission; import android.app.Activity; import android.app.Fragment; /** * @author slience * @des PermissionHelper * @time 2017/7/19 11:29 */ public class PermissionHelper { private static Object mObject; // 需要传入的Activity Fragment private static int mRequestCode; // 请求码 private String[] mRequestPermission; // 需要请求的权限集合 private static String mPermissionDes; // 需要显示的权限说明 public PermissionHelper(Object object) { this.mObject = object; } /***********************************利用链式传递权限参数******************************************/ public static PermissionHelper with(Activity activity) { return new PermissionHelper(activity); } public static PermissionHelper with(Fragment fragment) { return new PermissionHelper(fragment); } public PermissionHelper requestCode(int requestCode) { this.mRequestCode = requestCode; return this; } public PermissionHelper setPermissionDes(String permissionDes) { this.mPermissionDes = permissionDes; return this; } public PermissionHelper requestPermissions(String... requestPermission) { this.mRequestPermission = requestPermission; return this; } /***********************************利用链式传递权限参数******************************************/ /** * 权限的判断和请求的发送 */ public void request() { // 1.判断是否是6.0版本以上 if (!PermissionUtils.isOverMarshmallow()) { // 2.如果不是6.0以上,直接通过反射获取执行方法,执行方法 PermissionUtils.executeSuccessMethod(mObject, mRequestCode); return; } else { // 3.如果是6.0 以上,首先需要判断权限是否已经授予 //执行什么方法并不确定,只能通过注解的方式给方法打一个标记 //通过反射去执行 注解+反射 //获取没有授予权限的列表 if (PermissionUtils.hasAllPermissionsGranted(mObject,mRequestPermission)) { // 3.1. 授予:通过反射获取方法并执行 PermissionUtils.executeSuccessMethod(mObject,mRequestCode); } else { // 3.2. 没有全部授予: 申请权限 PermissionUtils.requestPermissions(mObject,mRequestPermission, mRequestCode); } } } /** * 处理权限申请的回调 * @param object * @param requestCode * @param grantResults */ public static void requestPermissionResult(Object object, int requestCode, int[] grantResults) { if (requestCode == mRequestCode){ if(PermissionUtils.hasAllPermissionsGranted(grantResults)){ //权限全部授予 执行方法 PermissionUtils.executeSuccessMethod(object, requestCode); }else{ //权限没有全部授予,再次请求权限 PermissionUtils.showMissingPermissionDialog(mObject,mPermissionDes); } } } }
c855ac12fdb04754cd64c79b2154b1b61969d1e3
7aec65a0fb176f74b6db614a5333e6d30969b35b
/java/code/core/src/edu/cmu/ri/createlab/hummingbird/HIDHummingbirdProxy.java
9b25d333031623b59a8063e648ff8cb7225c79e8
[]
no_license
CMU-CREATE-Lab/hummingbird
a11c5872c3fd47bb6138cca34932c341a1927beb
c0e2f9c46d941029c985c3653ad7a79499f7f343
refs/heads/master
2021-04-22T13:27:28.649340
2015-06-01T19:12:34
2015-06-01T19:12:34
32,417,072
1
1
null
null
null
null
UTF-8
Java
false
false
24,912
java
package edu.cmu.ri.createlab.hummingbird; import java.awt.Color; import java.util.HashMap; import java.util.Map; import java.util.Set; import edu.cmu.ri.createlab.hummingbird.commands.hid.DisconnectCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.EmergencyStopCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.FullColorLEDCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetAnalogInputCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetState0CommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetState1CommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetState2CommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetState3CommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.GetState4CommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.HummingbirdState0; import edu.cmu.ri.createlab.hummingbird.commands.hid.HummingbirdState1; import edu.cmu.ri.createlab.hummingbird.commands.hid.HummingbirdState2; import edu.cmu.ri.createlab.hummingbird.commands.hid.HummingbirdState3; import edu.cmu.ri.createlab.hummingbird.commands.hid.HummingbirdState4; import edu.cmu.ri.createlab.hummingbird.commands.hid.LEDCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.MotorCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.ServoCommandStrategy; import edu.cmu.ri.createlab.hummingbird.commands.hid.VibrationMotorCommandStrategy; import edu.cmu.ri.createlab.usb.hid.CreateLabHIDCommandStrategy; import edu.cmu.ri.createlab.usb.hid.HIDCommandExecutionQueue; import edu.cmu.ri.createlab.usb.hid.HIDConnectionException; import edu.cmu.ri.createlab.usb.hid.HIDDevice; import edu.cmu.ri.createlab.usb.hid.HIDDeviceFactory; import edu.cmu.ri.createlab.usb.hid.HIDDeviceNoReturnValueCommandExecutor; import edu.cmu.ri.createlab.usb.hid.HIDDeviceNotFoundException; import edu.cmu.ri.createlab.usb.hid.HIDDeviceReturnValueCommandExecutor; import edu.cmu.ri.createlab.util.commandexecution.CommandResponse; import org.apache.log4j.Logger; /** * @author Chris Bartley ([email protected]) */ final class HIDHummingbirdProxy extends BaseHummingbirdProxy { private static final Logger LOG = Logger.getLogger(HIDHummingbirdProxy.class); private static final HummingbirdVersionNumber DEFAULT_HUMMINGBIRD_VERSION_NUMBER = new HummingbirdVersionNumber(0, 0); private static final int DELAY_IN_MILLISECONDS_BETWEEN_PEER_PINGS = 400; /** * Tries to create a <code>Hummingbird</code> by connecting to a USB HID hummingbird. Returns <code>null</code> if * the connection could not be established. */ static Hummingbird create() { try { // create the HID device if (LOG.isDebugEnabled()) { LOG.debug("HIDHummingbirdProxy.create(): creating HID device for vendor ID [" + HIDConfiguration.HUMMINGBIRD_HID_DEVICE_DESCRIPTOR.getVendorIdAsHexString() + "] and product ID [" + HIDConfiguration.HUMMINGBIRD_HID_DEVICE_DESCRIPTOR.getProductIdAsHexString() + "]"); } final HIDDevice hidDevice = HIDDeviceFactory.create(HIDConfiguration.HUMMINGBIRD_HID_DEVICE_DESCRIPTOR); LOG.debug("HIDHummingbirdProxy.create(): attempting connection..."); hidDevice.connectExclusively(); // create the HID device command execution queue (which will attempt to connect to the device) final HIDCommandExecutionQueue commandQueue = new HIDCommandExecutionQueue(hidDevice); // create the HIDHummingbirdProxy final HIDHummingbirdProxy proxy = new HIDHummingbirdProxy(commandQueue, hidDevice); // call the emergency stop command immediately, to make sure the LED and motors are turned off. proxy.emergencyStop(); return proxy; } catch (UnsupportedOperationException e) { LOG.error("UnsupportedOperationException caught while trying to create the HIDCommandExecutionQueue", e); System.exit(1); } catch (HIDConnectionException e) { LOG.error("HIDConnectionException while trying to connect to the Hummingbird, returning null", e); } catch (HIDDeviceNotFoundException ignored) { LOG.error("HIDDeviceNotFoundException while trying to connect to the Hummingbird, returning null"); } return null; } private final HummingbirdProperties hummingbirdProperties; private final HIDCommandExecutionQueue commandQueue; private final HIDDevice hidDevice; private final CreateLabHIDCommandStrategy disconnectCommandStrategy = new DisconnectCommandStrategy(); private final Map<Integer, GetAnalogInputCommandStrategy> analogInputCommandStategyMap = new HashMap<Integer, GetAnalogInputCommandStrategy>(); private final GetState0CommandStrategy getState0CommandStrategy; private final GetState1CommandStrategy getState1CommandStrategy; private final GetState2CommandStrategy getState2CommandStrategy; private final GetState3CommandStrategy getState3CommandStrategy; private final EmergencyStopCommandStrategy emergencyStopCommandStrategy = new EmergencyStopCommandStrategy(); private final HIDDeviceNoReturnValueCommandExecutor noReturnValueCommandExecutor; private final HIDDeviceReturnValueCommandExecutor<Integer> integerReturnValueCommandExecutor; private final HIDDeviceReturnValueCommandExecutor<HummingbirdState0> hummingbirdState0ReturnValueCommandExecutor; private final HIDDeviceReturnValueCommandExecutor<HummingbirdState1> hummingbirdState1ReturnValueCommandExecutor; private final HIDDeviceReturnValueCommandExecutor<HummingbirdState2> hummingbirdState2ReturnValueCommandExecutor; private final HIDDeviceReturnValueCommandExecutor<HummingbirdState3> hummingbirdState3ReturnValueCommandExecutor; private final HummingbirdVersionNumber hardwareVersionNumber; private final HummingbirdVersionNumber firmwareVersionNumber; private HIDHummingbirdProxy(final HIDCommandExecutionQueue commandQueue, final HIDDevice hidDevice) { super(DELAY_IN_MILLISECONDS_BETWEEN_PEER_PINGS); this.commandQueue = commandQueue; this.hidDevice = hidDevice; noReturnValueCommandExecutor = new HIDDeviceNoReturnValueCommandExecutor(commandQueue, this); integerReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<Integer>(commandQueue, this); hummingbirdState0ReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<HummingbirdState0>(commandQueue, this); hummingbirdState1ReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<HummingbirdState1>(commandQueue, this); hummingbirdState2ReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<HummingbirdState2>(commandQueue, this); hummingbirdState3ReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<HummingbirdState3>(commandQueue, this); // get the hardware and firmware version numbers final HIDDeviceReturnValueCommandExecutor<HummingbirdState4> hummingbirdState4ReturnValueCommandExecutor = new HIDDeviceReturnValueCommandExecutor<HummingbirdState4>(commandQueue, this); final HummingbirdState4 hummingbirdState4 = hummingbirdState4ReturnValueCommandExecutor.execute(new GetState4CommandStrategy()); // We'll figure out exactly what kind of hardware this is below. Start by defaulting to HID Hummingbird. HummingbirdProperties hummingbirdPropertiesTemp = HIDHummingbirdProperties.getInstance(); if (hummingbirdState4 != null) { if (hummingbirdState4.getHardwareVersion() != null) { // check version number to determine whether this is an HID Hummingbird or a Hummingbird Duo hardwareVersionNumber = hummingbirdState4.getHardwareVersion(); final HummingbirdHardwareType hardwareType = BaseHIDHummingbirdProperties.getHardwareTypeFromHardwareVersion(hardwareVersionNumber); if (HummingbirdHardwareType.DUO.equals(hardwareType)) { hummingbirdPropertiesTemp = HummingbirdDuoProperties.getInstance(); } } else { hardwareVersionNumber = DEFAULT_HUMMINGBIRD_VERSION_NUMBER; } if (hummingbirdState4.getFirmwareVersion() != null) { firmwareVersionNumber = hummingbirdState4.getFirmwareVersion(); } else { firmwareVersionNumber = DEFAULT_HUMMINGBIRD_VERSION_NUMBER; } } else { hardwareVersionNumber = DEFAULT_HUMMINGBIRD_VERSION_NUMBER; firmwareVersionNumber = DEFAULT_HUMMINGBIRD_VERSION_NUMBER; } hummingbirdProperties = hummingbirdPropertiesTemp; getState0CommandStrategy = new GetState0CommandStrategy(hummingbirdProperties); getState1CommandStrategy = new GetState1CommandStrategy(hummingbirdProperties); getState2CommandStrategy = new GetState2CommandStrategy(hummingbirdProperties); getState3CommandStrategy = new GetState3CommandStrategy(hummingbirdProperties); // initialize the analog input command strategy map for (int i = 0; i < hummingbirdProperties.getAnalogInputDeviceCount(); i++) { analogInputCommandStategyMap.put(i, new GetAnalogInputCommandStrategy(i, hummingbirdProperties)); } } @Override public String getPortName() { return hidDevice.getDeviceFilename(); } /** Returns the {@link HummingbirdProperties} for this hummingbird. */ @Override public HummingbirdProperties getHummingbirdProperties() { return hummingbirdProperties; } @Override public HummingbirdVersionNumber getHardwareVersion() { return hardwareVersionNumber; } @Override public HummingbirdVersionNumber getFirmwareVersion() { return firmwareVersionNumber; } @Override public HummingbirdState getState() { final HummingbirdState0 state0 = hummingbirdState0ReturnValueCommandExecutor.execute(getState0CommandStrategy); if (state0 != null) { final HummingbirdState1 state1 = hummingbirdState1ReturnValueCommandExecutor.execute(getState1CommandStrategy); if (state1 != null) { final HummingbirdState2 state2 = hummingbirdState2ReturnValueCommandExecutor.execute(getState2CommandStrategy); if (state2 != null) { final HummingbirdState3 state3 = hummingbirdState3ReturnValueCommandExecutor.execute(getState3CommandStrategy); if (state3 != null) { return new HummingbirdStateImpl(state0, state1, state2, state3, hummingbirdProperties); } } } } return null; } @Override public Integer getAnalogInputValue(final int analogInputPortId) { final GetAnalogInputCommandStrategy strategy = analogInputCommandStategyMap.get(analogInputPortId); if (strategy != null) { return integerReturnValueCommandExecutor.execute(strategy); } throw new IllegalArgumentException("Invalid analog input port id: [" + analogInputPortId + "]"); } @Override public int[] getAnalogInputValues() { final HummingbirdState3 state = hummingbirdState3ReturnValueCommandExecutor.execute(getState3CommandStrategy); if (state != null) { return state.getAnalogInputValues(); } return null; } @Override public boolean isMotorPowerEnabled() { final HummingbirdState3 state3 = hummingbirdState3ReturnValueCommandExecutor.execute(getState3CommandStrategy); return state3 != null && state3.isMotorPowerEnabled(); } @Override public Double getMotorPowerPortVoltage() { final HummingbirdState3 state3 = hummingbirdState3ReturnValueCommandExecutor.execute(getState3CommandStrategy); return (state3 == null) ? null : state3.getMotorPowerPortVoltage(); } @Override public boolean setMotorVelocity(final int motorId, final int velocity) { return noReturnValueCommandExecutor.execute(new MotorCommandStrategy(motorId, velocity, hummingbirdProperties)); } @Override public int[] setMotorVelocities(final boolean[] mask, final int[] velocities) { // figure out which ids are masked on final Set<Integer> maskedIndeces = HummingbirdUtils.computeMaskedOnIndeces(mask, Math.min(velocities.length, hummingbirdProperties.getMotorDeviceCount())); boolean wereAllCommandsSuccessful = true; for (final int index : maskedIndeces) { wereAllCommandsSuccessful = wereAllCommandsSuccessful && setMotorVelocity(index, velocities[index]); } if (wereAllCommandsSuccessful) { final HummingbirdState2 state = hummingbirdState2ReturnValueCommandExecutor.execute(getState2CommandStrategy); if (state != null) { return state.getMotorVelocities(); } } return null; } @Override public boolean setVibrationMotorSpeed(final int motorId, final int speed) { return noReturnValueCommandExecutor.execute(new VibrationMotorCommandStrategy(motorId, speed, hummingbirdProperties)); } @Override public int[] setVibrationMotorSpeeds(final boolean[] mask, final int[] speeds) { // figure out which ids are masked on final Set<Integer> maskedIndeces = HummingbirdUtils.computeMaskedOnIndeces(mask, Math.min(speeds.length, hummingbirdProperties.getVibrationMotorDeviceCount())); boolean wereAllCommandsSuccessful = true; for (final int index : maskedIndeces) { wereAllCommandsSuccessful = wereAllCommandsSuccessful && setVibrationMotorSpeed(index, speeds[index]); } if (wereAllCommandsSuccessful) { final HummingbirdState2 state = hummingbirdState2ReturnValueCommandExecutor.execute(getState2CommandStrategy); if (state != null) { return state.getVibrationMotorSpeeds(); } } return null; } @Override public boolean setServoPosition(final int servoId, final int position) { return noReturnValueCommandExecutor.execute(new ServoCommandStrategy(servoId, position, hummingbirdProperties)); } @Override public int[] setServoPositions(final boolean[] mask, final int[] positions) { // figure out which ids are masked on final Set<Integer> maskedIndeces = HummingbirdUtils.computeMaskedOnIndeces(mask, Math.min(positions.length, hummingbirdProperties.getSimpleServoDeviceCount())); boolean wereAllCommandsSuccessful = true; for (final int index : maskedIndeces) { wereAllCommandsSuccessful = wereAllCommandsSuccessful && setServoPosition(index, positions[index]); } if (wereAllCommandsSuccessful) { final HummingbirdState1 state = hummingbirdState1ReturnValueCommandExecutor.execute(getState1CommandStrategy); if (state != null) { return state.getServoPositions(); } } return null; } @Override public boolean setLED(final int ledId, final int intensity) { return noReturnValueCommandExecutor.execute(new LEDCommandStrategy(ledId, intensity, hummingbirdProperties)); } @Override public int[] setLEDs(final boolean[] mask, final int[] intensities) { // figure out which ids are masked on final Set<Integer> maskedIndeces = HummingbirdUtils.computeMaskedOnIndeces(mask, Math.min(intensities.length, hummingbirdProperties.getSimpleLedDeviceCount())); boolean wereAllCommandsSuccessful = true; for (final int index : maskedIndeces) { wereAllCommandsSuccessful = wereAllCommandsSuccessful && setLED(index, intensities[index]); } if (wereAllCommandsSuccessful) { // LED state is spread across 2 different states... final HummingbirdState0 state0 = hummingbirdState0ReturnValueCommandExecutor.execute(getState0CommandStrategy); if (state0 != null) { final HummingbirdState1 state1 = hummingbirdState1ReturnValueCommandExecutor.execute(getState1CommandStrategy); if (state1 != null) { final int[] intensitiesOfLeds1Through3 = state1.getLedIntensities(); if (intensitiesOfLeds1Through3 != null) { final int[] actualIntensities = new int[hummingbirdProperties.getSimpleLedDeviceCount()]; actualIntensities[0] = state0.getLed0Intensity(); for (int i = 0; i < Math.min(intensitiesOfLeds1Through3.length, actualIntensities.length - 1); i++) { actualIntensities[i + 1] = intensitiesOfLeds1Through3[i]; } return actualIntensities; } } } } return null; } @Override public boolean setFullColorLED(final int ledId, final int red, final int green, final int blue) { return noReturnValueCommandExecutor.execute(new FullColorLEDCommandStrategy(ledId, red, green, blue, hummingbirdProperties)); } @Override public Color[] setFullColorLEDs(final boolean[] mask, final Color[] colors) { // figure out which ids are masked on final Set<Integer> maskedIndeces = HummingbirdUtils.computeMaskedOnIndeces(mask, Math.min(colors.length, hummingbirdProperties.getFullColorLedDeviceCount())); boolean wereAllCommandsSuccessful = true; for (final int index : maskedIndeces) { final Color color = colors[index]; if (color != null) { wereAllCommandsSuccessful = wereAllCommandsSuccessful && setFullColorLED(index, color.getRed(), color.getGreen(), color.getBlue()); } } if (wereAllCommandsSuccessful) { final HummingbirdState0 state = hummingbirdState0ReturnValueCommandExecutor.execute(getState0CommandStrategy); if (state != null) { return state.getFullColorLEDs(); } } return null; } @Override public boolean emergencyStop() { return noReturnValueCommandExecutor.execute(emergencyStopCommandStrategy); } @Override protected boolean disconnectAndReturnStatus() throws Exception { return commandQueue.executeAndReturnStatus(disconnectCommandStrategy); } @Override protected void shutdownCommandQueue() { commandQueue.shutdown(); } @Override protected CommandResponse executePingCommand() throws Exception { return commandQueue.execute(analogInputCommandStategyMap.get(0)); } private static final class HummingbirdStateImpl implements HummingbirdState { private static final String EOL = System.getProperty("line.separator", "\n"); private final HummingbirdState0 state0; private final HummingbirdState1 state1; private final HummingbirdState2 state2; private final HummingbirdState3 state3; private final HummingbirdProperties hummingbirdProperties; private HummingbirdStateImpl(final HummingbirdState0 state0, final HummingbirdState1 state1, final HummingbirdState2 state2, final HummingbirdState3 state3, final HummingbirdProperties hummingbirdProperties) { this.state0 = state0; this.state1 = state1; this.state2 = state2; this.state3 = state3; this.hummingbirdProperties = hummingbirdProperties; } @Override public Color[] getFullColorLEDs() { return state0.getFullColorLEDs(); } @Override public int[] getLedIntensities() { final int[] intensitiesOfLeds1Through3 = state1.getLedIntensities(); if (intensitiesOfLeds1Through3 != null) { final int[] intensities = new int[hummingbirdProperties.getSimpleLedDeviceCount()]; intensities[0] = state0.getLed0Intensity(); for (int i = 0; i < Math.min(intensitiesOfLeds1Through3.length, intensities.length - 1); i++) { intensities[i + 1] = intensitiesOfLeds1Through3[i]; } return intensities; } return null; } @Override public int[] getServoPositions() { return state1.getServoPositions(); } @Override public int[] getMotorVelocities() { return state2.getMotorVelocities(); } @Override public int[] getVibrationMotorSpeeds() { return state2.getVibrationMotorSpeeds(); } @Override public int[] getAnalogInputValues() { return state3.getAnalogInputValues(); } @Override public boolean isMotorPowerEnabled() { return state3.isMotorPowerEnabled(); } @Override public double getMotorPowerPortVoltage() { return state3.getMotorPowerPortVoltage(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final HummingbirdStateImpl that = (HummingbirdStateImpl)o; if (state0 != null ? !state0.equals(that.state0) : that.state0 != null) { return false; } if (state1 != null ? !state1.equals(that.state1) : that.state1 != null) { return false; } if (state2 != null ? !state2.equals(that.state2) : that.state2 != null) { return false; } if (state3 != null ? !state3.equals(that.state3) : that.state3 != null) { return false; } return true; } @Override public int hashCode() { int result = state0 != null ? state0.hashCode() : 0; result = 31 * result + (state1 != null ? state1.hashCode() : 0); result = 31 * result + (state2 != null ? state2.hashCode() : 0); result = 31 * result + (state3 != null ? state3.hashCode() : 0); return result; } @Override public String toString() { final StringBuilder s = new StringBuilder("HummingbirdState" + EOL); final Color[] orbs = getFullColorLEDs(); final int[] leds = getLedIntensities(); final int[] servos = getServoPositions(); final int[] motors = getMotorVelocities(); final int[] vibeMotors = getVibrationMotorSpeeds(); final int[] analogInputs = getAnalogInputValues(); for (int i = 0; i < orbs.length; i++) { s.append(" Orb ").append(i).append(": (").append(orbs[i].getRed()).append(",").append(orbs[i].getGreen()).append(",").append(orbs[i].getBlue()).append(")").append(EOL); } for (int i = 0; i < leds.length; i++) { s.append(" LED ").append(i).append(": ").append(leds[i]).append(EOL); } for (int i = 0; i < servos.length; i++) { s.append(" Servo ").append(i).append(": ").append(servos[i]).append(EOL); } for (int i = 0; i < motors.length; i++) { s.append(" Motor ").append(i).append(": ").append(motors[i]).append(EOL); } for (int i = 0; i < vibeMotors.length; i++) { s.append(" Vibe Motor ").append(i).append(": ").append(vibeMotors[i]).append(EOL); } for (int i = 0; i < analogInputs.length; i++) { s.append(" Sensor ").append(i).append(": ").append(analogInputs[i]).append(EOL); } s.append(" Motor Power Enabled: ").append(isMotorPowerEnabled()).append(EOL); s.append(" Motor Power Port Voltage: ").append(getMotorPowerPortVoltage()).append(EOL); return s.toString(); } } }
[ "[email protected]@8f9ae9e0-bd35-6d31-192c-db6722d48ff7" ]
[email protected]@8f9ae9e0-bd35-6d31-192c-db6722d48ff7
b7e868c436f7a28492f15018006f1dcb3abac721
68c852dd7b793434b5c087549789cdeeb1e45eb1
/app/src/main/java/cn/edu/gdpt/androiddemo/searchview/EditText_Clear.java
6a2d309536c7453acb75d2c8f5508ca5755da4e0
[]
no_license
leioalba/MyApp
aaec5e272f7df7103507772b4f9caa48555521ea
7042ebbf7d382a40842ef4cb1e7c07efd9282b89
refs/heads/master
2020-06-05T00:52:32.887327
2019-06-26T06:36:20
2019-06-26T06:36:20
192,257,562
0
0
null
null
null
null
UTF-8
Java
false
false
5,228
java
package cn.edu.gdpt.androiddemo.searchview; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; /** * Created by Carson_Ho on 17/8/10. */ public class EditText_Clear extends android.support.v7.widget.AppCompatEditText { /** * 步骤1:定义左侧搜索图标 & 一键删除图标 */ private Drawable clearDrawable,searchDrawable; public EditText_Clear(Context context) { super(context); init(); // 初始化该组件时,对EditText_Clear进行初始化 ->>步骤2 } public EditText_Clear(Context context, AttributeSet attrs) { super(context, attrs); init(); } public EditText_Clear(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } /** * 步骤2:初始化 图标资源 */ private void init() { clearDrawable = getResources().getDrawable(scut.carson_ho.searchview.R.drawable.clear); searchDrawable = getResources().getDrawable(scut.carson_ho.searchview.R.drawable.search); setCompoundDrawablesWithIntrinsicBounds(searchDrawable, null, null, null); // setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)介绍 // 作用:在EditText上、下、左、右设置图标(相当于android:drawableLeft="" android:drawableRight="") // 注1:setCompoundDrawablesWithIntrinsicBounds()传入的Drawable的宽高=固有宽高(自动通过getIntrinsicWidth()& getIntrinsicHeight()获取) // 注2:若不想在某个地方显示,则设置为null // 此处设置了左侧搜索图标 // 另外一个相似的方法:setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)介绍 // 与setCompoundDrawablesWithIntrinsicBounds()的区别:可设置图标大小 // 传入的Drawable对象必须已经setBounds(x,y,width,height),即必须设置过初始位置、宽和高等信息 // x:组件在容器X轴上的起点 y:组件在容器Y轴上的起点 width:组件的长度 height:组件的高度 } /** * 步骤3:通过监听复写EditText本身的方法来确定是否显示删除图标 * 监听方法:onTextChanged() & onFocusChanged() * 调用时刻:当输入框内容变化时 & 焦点发生变化时 */ @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); setClearIconVisible(hasFocus() && text.length() > 0); // hasFocus()返回是否获得EditTEXT的焦点,即是否选中 // setClearIconVisible() = 根据传入的是否选中 & 是否有输入来判断是否显示删除图标->>关注1 } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); setClearIconVisible(focused && length() > 0); // focused = 是否获得焦点 // 同样根据setClearIconVisible()判断是否要显示删除图标 } /** * 关注1 * 作用:判断是否显示删除图标 */ private void setClearIconVisible(boolean visible) { setCompoundDrawablesWithIntrinsicBounds(searchDrawable, null, visible ? clearDrawable : null, null); } /** * 步骤4:对删除图标区域设置点击事件,即"点击 = 清空搜索框内容" * 原理:当手指抬起的位置在删除图标的区域,即视为点击了删除图标 = 清空搜索框内容 */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { // 原理:当手指抬起的位置在删除图标的区域,即视为点击了删除图标 = 清空搜索框内容 case MotionEvent.ACTION_UP: Drawable drawable = clearDrawable; if (drawable != null && event.getX() <= (getWidth() - getPaddingRight()) && event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) { setText(""); } // 判断条件说明 // event.getX() :抬起时的位置坐标 // getWidth():控件的宽度 // getPaddingRight():删除图标图标右边缘至EditText控件右边缘的距离 // 即:getWidth() - getPaddingRight() = 删除图标的右边缘坐标 = X1 // getWidth() - getPaddingRight() - drawable.getBounds().width() = 删除图标左边缘的坐标 = X2 // 所以X1与X2之间的区域 = 删除图标的区域 // 当手指抬起的位置在删除图标的区域(X2=<event.getX() <=X1),即视为点击了删除图标 = 清空搜索框内容 break; } return super.onTouchEvent(event); } }
4f229f15a91d6fb725bee58b6fb97572728dd3e9
c9b5f911d95df3041641d18ffa56891ab4659508
/app/src/main/java/com/eribeiro/volleysimples/StringRequestActivity.java
4f6034f410941da21164af801e45d55fc1e827c2
[]
no_license
erickrribeiro/ComunicacaoComVolley
84e751efd11c9e9150c9fe52291f495636b50b94
0199602ff2cf393ccd5ce105149b7599716541ad
refs/heads/master
2016-09-14T19:11:37.668332
2016-04-12T17:36:44
2016-04-12T17:36:44
56,074,248
0
0
null
null
null
null
UTF-8
Java
false
false
2,335
java
package com.eribeiro.volleysimples; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.StringRequest; import com.eribeiro.volleysimples.app.AppController; import com.eribeiro.volleysimples.utils.Dominio; public class StringRequestActivity extends Activity implements View.OnClickListener{ private String TAG = StringRequestActivity.class.getSimpleName(); private TextView mTextViewResponse; private ProgressDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_string); Button btnStringReq = (Button) findViewById(R.id.btnStringReq); mTextViewResponse = (TextView) findViewById(R.id.msgResponse); pDialog = new ProgressDialog(getApplicationContext()); pDialog.setMessage("Carregando..."); pDialog.setCancelable(false); btnStringReq.setOnClickListener(this); } private void showProgressDialog() { if (!pDialog.isShowing()) pDialog.show(); } private void hideProgressDialog() { if (pDialog.isShowing()) pDialog.hide(); } /** * Making json object request * */ private void makeStringReq() { showProgressDialog(); StringRequest strReq = new StringRequest(Method.GET, Dominio.URL_STRING_REQ, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response); mTextViewResponse.setText(response); hideProgressDialog(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hideProgressDialog(); } }); /** * Adiciona um requisição a fila de requisições, nomeando esse requisição por "string_req" */ AppController.getInstance().addToRequestQueue(strReq, "string_req"); } @Override public void onClick(View v) { makeStringReq(); } }
bc4c8ad88aff0278165de4f6f1d1a1ddeb4dc1ec
0d35b36a6ea2bf9a283485150e444bfe252a8c1a
/app/src/main/java/com/example/tts_progmob_72170109/Admin/RecyclerViewDaftarMhs.java
0345935234315111932022207e9995c7c9ec938b
[]
no_license
saniba123/tts_progmob_72170109melsiora
5023e5d38edb02b786731c1cc8072578e01a6298
1964862500774dba8795c96f41e8213e65d9af24
refs/heads/master
2023-01-06T11:22:30.402013
2020-10-30T23:30:35
2020-10-30T23:30:35
308,765,749
0
0
null
null
null
null
UTF-8
Java
false
false
6,427
java
package com.example.tts_progmob_72170109.Admin; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.tts_progmob_72170109.Admin.Adapter.MahasiswaAdapter; import com.example.tts_progmob_72170109.Admin.Model.Mahasiswa; import com.example.tts_progmob_72170109.Network.DefaultResult; import com.example.tts_progmob_72170109.Network.GetDataService; import com.example.tts_progmob_72170109.Network.RetrofitClientInstance; import com.example.tts_progmob_72170109.R; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RecyclerViewDaftarMhs extends AppCompatActivity { private RecyclerView recyclerView; private MahasiswaAdapter mahasiswaAdapter; private ArrayList<Mahasiswa> mahasiswaList; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view_daftar_mhs); this.setTitle("SI - Hello Admin"); //tambahData(); recyclerView = findViewById(R.id.rvMhs); //mhsAdapter = new MahasiswaAdapter(mhsList); progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.show(); GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class); Call<ArrayList<Mahasiswa>> call = service.getMahasiswaAll("72170109"); call.enqueue(new Callback<ArrayList<Mahasiswa>>() { @Override public void onResponse(Call<ArrayList<Mahasiswa>> call, Response<ArrayList<Mahasiswa>> response) { progressDialog.dismiss(); mahasiswaList = response.body(); mahasiswaAdapter = new MahasiswaAdapter(response.body()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecyclerViewDaftarMhs.this); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(mahasiswaAdapter); } @Override public void onFailure(Call<ArrayList<Mahasiswa>> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(RecyclerViewDaftarMhs.this,"Error",Toast.LENGTH_SHORT); } }); registerForContextMenu(recyclerView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menucreate,menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId()==R.id.menu1){ Intent intent = new Intent(RecyclerViewDaftarMhs.this,CreateMhsActivity.class); startActivity(intent); } return true; } @Override public boolean onContextItemSelected(@NonNull MenuItem item) { Mahasiswa mahasiswa = mahasiswaList.get(item.getGroupId()); if (item.getTitle()== "Ubah Data Mhs"){ Intent intent = new Intent(RecyclerViewDaftarMhs.this, CreateDosenActivity.class); intent.putExtra("id_mahasiswa",mahasiswa.getId()); //(key, value) -> ketika manggil Mhs harus sama intent.putExtra("nama",mahasiswa.getNama()); intent.putExtra("nim",mahasiswa.getNim()); intent.putExtra("alamat",mahasiswa.getAlamatMhs()); intent.putExtra("email",mahasiswa.getEmailMhs()); intent.putExtra("foto",mahasiswa.getFoto()); intent.putExtra("is_update",true); startActivity(intent); }else if(item.getTitle() == "Hapus Data Mahasiswa"){ //Toast.makeText(RecyclerViewDaftarDosen.this,"Hapus",Toast.LENGTH_LONG).show(); progressDialog = new ProgressDialog(RecyclerViewDaftarMhs.this); progressDialog.show(); GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class); Call<DefaultResult> call = service.delete_dosen( mahasiswa.getId(), "72170109"); call.enqueue(new Callback<DefaultResult>() { @Override public void onResponse(Call<DefaultResult> call, Response<DefaultResult> response) { progressDialog.dismiss(); Toast.makeText(RecyclerViewDaftarMhs.this,"Berhasil Menghapus",Toast.LENGTH_SHORT).show(); recreate(); } @Override public void onFailure(Call<DefaultResult> call, Throwable t) { progressDialog.dismiss(); Toast.makeText(RecyclerViewDaftarMhs.this,"Gagal Hapus",Toast.LENGTH_SHORT).show(); } }); } return super.onContextItemSelected(item); } // private RecyclerView recyclerView; // private MahasiswaAdapter mhsAdapter; // private ArrayList<Mahasiswa> mhsList; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_recycler_view_daftar_mhs); // this.setTitle("SI- Hello Admin"); // tambahData(); // // recyclerView = findViewById(R.id.rvMhs); // mhsAdapter = new MahasiswaAdapter(mhsList); // // RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(RecyclerViewDaftarMhs.this); // recyclerView.setLayoutManager(layoutManager); // recyclerView.setAdapter(mhsAdapter); // } // private void tambahData(){ // mhsList = new ArrayList<>(); // mhsList.add(new Mahasiswa("72170107","Eka","[email protected]","Jl.Wonosari",R.drawable.eka)); // mhsList.add(new Mahasiswa("72170108","Mel","[email protected]","Jl.Wonosari",R.drawable.mel)); // mhsList.add(new Mahasiswa("72170109","Nono","[email protected]","Jl.Wonosari",R.drawable.nono)); }
ee28ad269a68db5446ba4c54b6f005b8b3df250c
611addd6d9c6f4dc4995d72f39e48a0d9f89b59b
/L_142.java
3659e7998607fcd5f368454c90d815e51ee0eb3a
[]
no_license
himanshudhawale/Leetcode-Medium
33b588bf6338918f64976bf2dd62e37c78b797a5
cda2cdd063e263a83608299fbfb757d2a010f390
refs/heads/master
2020-07-03T17:30:14.347271
2019-12-11T20:20:30
2019-12-11T20:20:30
201,986,246
1
1
null
null
null
null
UTF-8
Java
false
false
1,642
java
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ //O(n) space public class Solution { public ListNode detectCycle(ListNode head) { // ListNode temp = head; Set<ListNode> myset = new HashSet<ListNode>(); if(head == null || head.next == null ) return null; while(head!=null) { if(myset.contains(head)) return head; else { myset.add(head); } head = head.next; } return null; } } //O(1) space /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null ) return null; ListNode one = head; ListNode two = head; ListNode result = null; while(two!=null && two.next!=null) { one =one.next; two = two.next.next; if(one == two) { result = one; break; } } if (result == null) { return null; } ListNode ptr1 = head; ListNode ptr2 = result; while (ptr1 != ptr2) { ptr1 = ptr1.next; ptr2 = ptr2.next; } return ptr1; } }
4b98d3c410e3cf64435830579172531e7f964484
2c460e66298ea1d2144c19982e61dc221de535a0
/webflux/src/main/java/webflux/book/controller/BookController.java
10cf2adac4afef59da44abbdfcef3767f05cdee6
[]
no_license
mwwojcik/spring-webflux-mongodb
5988de1b61b684eac8185585124a4a4734f1575f
d59bb074c66f83bdbef40413bd60da83ca03bf73
refs/heads/master
2021-06-27T02:33:19.001500
2021-03-01T09:59:22
2021-03-01T09:59:22
225,149,806
0
0
null
2021-03-31T22:40:55
2019-12-01T11:25:42
Java
UTF-8
Java
false
false
685
java
package webflux.book.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import webflux.book.model.Book; import webflux.book.mongo.BookReactiveRepo; @RestController public class BookController { private BookReactiveRepo repository; public BookController(BookReactiveRepo repo) { repository = repo; } /* @PostMapping(value = "/book") public Mono<Book> createBook(@RequestBody Book book) { return repository.save(book); } */ }
1c8ec161238582e1b7dba57e0bd9c525e65ad1df
36599644ca17e1b1c1f6ca25d0f2861a4ca6adc7
/src/org/example/mediator/TV.java
8e49589680509dbbec3a5b1986db8d5317571741
[]
no_license
lxk403216058/Design-Partten
7303284619ee719ec6ef3beea826ede3c930616c
22215f82083fcac3beedf378b422c59bca0eb6ec
refs/heads/master
2023-02-23T14:52:54.499573
2021-01-26T07:57:46
2021-01-26T07:57:46
328,166,201
0
0
null
null
null
null
UTF-8
Java
false
false
626
java
package org.example.mediator; /** * @description * @author: lxk * @date: 2021-01-21 14:49 **/ public class TV extends Colleague { public TV(Mediator mediator, String name) { super(mediator, name); //创建TV同事对象时,将自己放入到ConcreteMediator mediator.register(name, this); } public void startTv() { System.out.println("开电视 ....."); } public void stopTv() { System.out.println("关电视 ....."); } @Override public void sendMessage(int stateChange) { this.getMediator().getMessage(stateChange, this.name); } }
be57ba4c4bc2731bdd43ae461ce73e94e4c4e175
35fce255ecfec795b1e3b98e189b69fe92b6e76d
/실버/DFS&BFS/7576(토마토)/Main.java
7464ee7248edde7bdb5abf8e4d05fcb3b291385a
[]
no_license
harandal24601/BOJ_answer
ea76b9d5cf1ea29f86f5f5c0562efe4d56b6f1df
2bfbb6c6a584a4cd593fd250a6bc4aa7d7bad3ca
refs/heads/master
2023-01-03T17:29:35.959625
2020-10-28T17:50:06
2020-10-28T17:50:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,589
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; class Pos { int x; int y; int time; Pos(int x, int y, int time){ this.x = x; this.y = y; this.time = time; } } class Main { static int width, height; static int[][] map; static int max; static boolean[][] visited; static ArrayList<Pos> tomatos; // 상,하,좌,우 static int[] xdir = {-1,1,0,0}; static int[] ydir = {0,0,-1,1}; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 상자의 가로 세로크기 입력 받기 String[] temp = br.readLine().split(" "); width = Integer.parseInt(temp[0]); height = Integer.parseInt(temp[1]); tomatos = new ArrayList<>(); map = new int[height][width]; // 상자에 담긴 토마토 정보 입력 받기 for(int i=0; i<height; i++){ temp = br.readLine().split(" "); for(int j=0; j<width; j++){ int t = Integer.parseInt(temp[j]); map[i][j] = t; if(t == 1) tomatos.add(new Pos(i,j,0)); } } max = 0; visited = new boolean[height][width]; bfs(); // 이미 모두 익어있는 경우 max 값이 1이 된다. if(max == 1){ System.out.println(0); return; } // 토마토가 모두 익었는지 검사 if(isGrow()) System.out.println(max); else System.out.println(-1); br.close(); } private static void bfs(){ Queue<Pos> q = new LinkedList<>(); // 익은 토마토 위치 모두 queue에 넣고 시작 // 동시에 퍼져나가기 위해서 for(Pos p : tomatos){ int x = p.x; int y = p.y; q.add(new Pos(x, y, 0)); visited[x][y] = true; } while(!q.isEmpty()){ Pos p = q.poll(); int x = p.x; int y = p.y; int t = p.time; // 저장된 시간이 max보다 크다면 update if(max < t) max = t; for(int i=0; i<4; i++){ int dx = x + xdir[i]; int dy = y + ydir[i]; // 유효한 위치 && 방문하지 않은 곳 if(isValidPosition(dx, dy) && !visited[dx][dy]){ // 빈 곳이 아니라면 방문 if(map[dx][dy] != -1){ map[dx][dy] = 1; visited[dx][dy] = true; q.add(new Pos(dx, dy, t+1)); } } } } } private static boolean isGrow(){ for(int[] a: map){ for(int num : a){ if(num == 0) return false; } } return true; } private static boolean isValidPosition(int x, int y){ if(x < 0 || x >= height || y < 0 || y >= width) return false; return true; } }
29dcf39be28dbb58a018cf61aba06187571829bb
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/4/4_8158c32270667da03459ca19831698646206b997/NewBuilder/4_8158c32270667da03459ca19831698646206b997_NewBuilder_s.java
b84cc5ef52802c53e05aa577b5bea42b9234c596
[]
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
22,410
java
package bndtools.builder; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.bndtools.core.utils.workspace.WorkspaceUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.IJavaModelMarker; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.lib.io.IO; import aQute.lib.osgi.Builder; import bndtools.Central; import bndtools.Plugin; import bndtools.classpath.BndContainerInitializer; public class NewBuilder extends IncrementalProjectBuilder { public static final String BUILDER_ID = Plugin.PLUGIN_ID + ".bndbuilder"; public static final String MARKER_BND_PROBLEM = Plugin.PLUGIN_ID + ".bndproblem"; private static final int LOG_FULL = 2; private static final int LOG_BASIC = 1; private static final int LOG_NONE = 0; private Project model; private List<String> classpathErrors; private List<String> buildLog; private int logLevel = LOG_FULL; // TODO: load this from some config?? @Override protected IProject[] build(int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, "Building bundles", 0); classpathErrors = new LinkedList<String>(); buildLog = new ArrayList<String>(5); // Initialise workspace OBR index (should only happen once) boolean builtAny = false; try { IProject myProject = getProject(); Project model = Workspace.getProject(myProject.getLocation().toFile()); if (model == null) return null; this.model = model; model.clear(); // Clear errors and warnings // CASE 1: CNF changed if (isCnfChanged()) { log(LOG_BASIC, "cnf project changed"); model.refresh(); model.getWorkspace().refresh(); if (BndContainerInitializer.resetClasspaths(model, myProject, classpathErrors)) { log(LOG_BASIC, "classpaths were changed"); } else { log(LOG_FULL, "classpaths did not need to change"); } return calculateDependsOn(); } // CASE 2: local Bnd file changed, or Eclipse asks for full build boolean localChange = false; if (kind == FULL_BUILD) { localChange = true; log(LOG_BASIC, "Eclipse requested full build"); } else if (isLocalBndFileChange()) { localChange = true; log(LOG_BASIC, "local bnd files changed"); } if (localChange) { model.refresh(); if (BndContainerInitializer.resetClasspaths(model, myProject, classpathErrors)) { log(LOG_BASIC, "classpaths were changed"); return calculateDependsOn(); } else { log(LOG_FULL, "classpaths were not changed"); rebuildIfLocalChanges(); return calculateDependsOn(); } } // (NB: from now on the delta cannot be null, due to the check in isLocalBndFileChange) // CASE 3: JAR file in dependency project changed Project changedDependency = getDependencyTargetChange(); if (changedDependency != null) { log(LOG_BASIC, "target files in dependency project %s changed", changedDependency.getName()); model.propertiesChanged(); if (BndContainerInitializer.resetClasspaths(model, myProject, classpathErrors)) { log(LOG_BASIC, "classpaths were changed"); return calculateDependsOn(); } else { log(LOG_FULL, "classpaths were not changed"); } } // CASE 4: local file changes builtAny = rebuildIfLocalChanges(); return calculateDependsOn(); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Build Error!", e)); } finally { if (!builtAny) { try { Central.getWorkspaceObrProvider().initialise(); } catch (Exception e) { Plugin.logError("Error initialising workspace OBR provider", e); } } if (!buildLog.isEmpty()) { System.err.println(String.format("==> BUILD LOG for project %s follows (%d entries):", getProject(), buildLog.size())); for (String message : buildLog) { StringBuilder builder = new StringBuilder().append(" ").append(message); System.err.println(builder.toString()); } } } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { try { IProject myProject = getProject(); Project model = Workspace.getProject(myProject.getLocation().toFile()); if (model == null) return; // Delete everything in the target directory File target = model.getTarget(); if (target.isDirectory() && target.getParentFile() != null) { IO.delete(target); target.mkdirs(); } // Tell Eclipse what we did... IFolder targetFolder = myProject.getFolder(calculateTargetDirPath(model)); targetFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (Exception e) { throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Build Error!", e)); } } boolean isCnfChanged() throws Exception { IProject cnfProject = WorkspaceUtils.findCnfProject(); if (cnfProject == null) { Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Bnd configuration project (cnf) is not available in the Eclipse workspace.", null)); return false; } IResourceDelta cnfDelta = getDelta(cnfProject); if (cnfDelta == null) { log(LOG_FULL, "no delta available for cnf project, ignoring"); return false; } final AtomicBoolean result = new AtomicBoolean(false); cnfDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if (!isChangeDelta(delta)) return false; if (IResourceDelta.MARKERS == delta.getFlags()) return false; IResource resource = delta.getResource(); if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT) return true; if (resource.getType() == IResource.FOLDER && resource.getName().equals("ext")) { log(LOG_FULL, "detected change in cnf due to resource %s, kind=0x%x, flags=0x%x", resource.getFullPath(), delta.getKind(), delta.getFlags()); result.set(true); } if (resource.getType() == IResource.FILE) { if (Workspace.BUILDFILE.equals(resource.getName())) { result.set(true); log(LOG_FULL, "detected change in cnf due to resource %s, kind=0x%x, flags=0x%x", resource.getFullPath(), delta.getKind(), delta.getFlags()); } else { // TODO: check other file names included from build.bnd } } return false; } }); return result.get(); } private boolean isLocalBndFileChange() throws CoreException { IResourceDelta myDelta = getDelta(getProject()); if (myDelta == null) { log(LOG_BASIC, "local project delta is null, assuming changes exist", model.getName()); return true; } final AtomicBoolean result = new AtomicBoolean(false); myDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if (!isChangeDelta(delta)) return false; IResource resource = delta.getResource(); if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT) return true; if (resource.getType() == IResource.FOLDER) return true; String extension = ((IFile) resource).getFileExtension(); if (resource.getType() == IResource.FILE && "bnd".equalsIgnoreCase(extension)) { log(LOG_FULL, "detected change due to resource %s, kind=0x%x, flags=0x%x", resource.getFullPath(), delta.getKind(), delta.getFlags()); result.set(true); return false; } return false; } }); return result.get(); } private Project getDependencyTargetChange() throws Exception { IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot(); Collection<Project> dependson = model.getDependson(); log(LOG_FULL, "project depends on: %s", dependson); for (Project dep : dependson) { File targetDir = dep.getTarget(); if (targetDir != null && !(targetDir.isDirectory())) // Does not exist... deleted? return dep; IProject project = WorkspaceUtils.findOpenProject(wsroot, dep); if (project == null) { Plugin.log(new Status(IStatus.WARNING, Plugin.PLUGIN_ID, 0, String.format("Dependency project '%s' from project '%s' is not in the Eclipse workspace.", dep.getName(), model.getName()), null)); return null; } IFile buildFile = project.getFolder(targetDir.getName()).getFile(Workspace.BUILDFILES); IPath buildFilePath = buildFile.getProjectRelativePath(); IResourceDelta delta = getDelta(project); if (delta == null) { // May have changed log(LOG_FULL, "null delta in dependency project %s", dep.getName()); return dep; } else if (!isChangeDelta(delta)) { continue; } else { IResourceDelta buildFileDelta = delta.findMember(buildFilePath); if (buildFileDelta != null && isChangeDelta(buildFileDelta)) { log(LOG_FULL, "detected change due to file %s, kind=0x%x, flags=0x%x", buildFile, delta.getKind(), delta.getFlags()); return dep; } } // this dependency project did not change, move on to next } // no dependencies changed return null; } /** * @return Whether any files were built */ private boolean rebuildIfLocalChanges() throws Exception { log(LOG_FULL, "calculating local changes..."); final Set<File> removedFiles = new HashSet<File>(); final Set<File> changedFiles = new HashSet<File>(); final IPath targetDirPath = calculateTargetDirPath(model); boolean force = false; IResourceDelta delta = getDelta(getProject()); if (delta != null) { delta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if (!isChangeDelta(delta)) return false; IResource resource = delta.getResource(); if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT) return true; if (resource.getType() == IResource.FOLDER) { IPath folderPath = resource.getProjectRelativePath(); // ignore ALL files in target dir return !folderPath.equals(targetDirPath); } if (resource.getType() == IResource.FILE) { File file = resource.getLocation().toFile(); if ((delta.getKind() & IResourceDelta.REMOVED) != 0) { removedFiles.add(file); } else { changedFiles.add(file); } } return false; } }); log(LOG_FULL, "%d local files (outside target) removed: %s", removedFiles.size(), removedFiles); log(LOG_FULL, "%d local files (outside target) changed: %s", changedFiles.size(), changedFiles); } else { log(LOG_BASIC, "no info on local changes available"); } // Process the sub-builders to determine whether a rebuild, force rebuild, or nothing is required. for (Builder builder : model.getSubBuilders()) { // If the builder's output JAR has been removed, this could be because the user // deleted it, so we should force build in order to regenerate it. File targetFile = new File(model.getTarget(), builder.getBsn() + ".jar"); if (!targetFile.isFile()) { log(LOG_FULL, "output file %s of builder %s was removed, will force a rebuild", targetFile, builder.getBsn()); force = true; break; } // Finally if any removed files are in scope for the bundle, we must force it to rebuild // because bnd will not notice the deletion if (!removedFiles.isEmpty() && builder.isInScope(removedFiles)) { log(LOG_FULL, "some removed files were in scope for builder %s, will force a rebuild", builder.getBsn()); force = true; break; } } // Do it boolean builtAny = false; if (force) { builtAny = rebuild(true); } else if (!changedFiles.isEmpty()) { builtAny = rebuild(false); } return builtAny; } private static IPath calculateTargetDirPath(Project model) throws Exception { IPath basePath = Path.fromOSString(model.getBase().getAbsolutePath()); final IPath targetDirPath = Path.fromOSString(model.getTarget().getAbsolutePath()).makeRelativeTo(basePath); return targetDirPath; } /** * @param force Whether to force bnd to build * @return Whether any files were built */ private boolean rebuild(boolean force) throws Exception { clearBuildMarkers(); // Abort build if compilation errors exist if (hasBlockingErrors()) { addBuildMarker(String.format("Will not build OSGi bundle(s) for project %s until compilation problems are fixed.", model.getName()), IMarker.SEVERITY_ERROR); log(LOG_BASIC, "SKIPPING due to Java problem markers"); return false; } else if (!classpathErrors.isEmpty()) { addBuildMarker("Will not build OSGi bundle(s) for project %s until classpath resolution problems are fixed.", IMarker.SEVERITY_ERROR); log(LOG_BASIC, "SKIPPING due to classpath resolution problem markers"); return false; } log(LOG_BASIC, "REBUILDING, force=%b", force); File[] built; // Build! model.clear(); model.setTrace(true); if (force) built = model.buildLocal(false); else built = model.build(); if (built == null) built = new File[0]; // Log rebuilt files log(LOG_BASIC, "requested rebuild of %d files", built.length); if (logLevel >= LOG_FULL) { for (File builtFile : built) { log(LOG_FULL, "target file %s has an age of %d ms", builtFile, System.currentTimeMillis() - builtFile.lastModified()); } } // Make sure Eclipse knows about the changed files (should already have been done?) IFolder targetFolder = getProject().getFolder(calculateTargetDirPath(model)); targetFolder.refreshLocal(IResource.DEPTH_INFINITE, null); // Replace into the workspace OBR provider if (built.length > 0) { try { Central.getWorkspaceObrProvider().replaceProjectFiles(model, built); } catch (Exception e) { Plugin.logError("Error rebuilding workspace OBR index", e); } } // Report errors List<String> errors = new ArrayList<String>(model.getErrors()); List<String> warnings = new ArrayList<String>(model.getWarnings()); createBuildMarkers(errors, warnings); return built.length > 0; } private IProject[] calculateDependsOn() throws Exception { Collection<Project> dependsOn = model.getDependson(); List<IProject> result = new ArrayList<IProject>(dependsOn.size() + 1); result.add(WorkspaceUtils.findCnfProject()); IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot(); for (Project project : dependsOn) { IProject targetProj = WorkspaceUtils.findOpenProject(wsroot, project); if (targetProj == null) Plugin.log(new Status(IStatus.WARNING, Plugin.PLUGIN_ID, 0, "No open project in workspace for Bnd '-dependson' dependency: " + project.getName(), null)); else result.add(targetProj); } log(LOG_FULL, "returning depends-on list: %s", result); return result.toArray(new IProject[result.size()]); } private boolean hasBlockingErrors() { try { if (containsError(getProject().findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE))) return true; return false; } catch (CoreException e) { Plugin.logError("Error looking for project problem markers", e); return false; } } private static boolean containsError(IMarker[] markers) { if (markers != null) for (IMarker marker : markers) { int severity = marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO); if (severity == IMarker.SEVERITY_ERROR) return true; } return false; } private static boolean isChangeDelta(IResourceDelta delta) { if (IResourceDelta.MARKERS == delta.getFlags()) return false; if ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED | IResourceDelta.REMOVED)) == 0) return false; return true; } private void createBuildMarkers(Collection<? extends String> errors, Collection<? extends String> warnings) throws CoreException { for (String error : errors) { addBuildMarker(error, IMarker.SEVERITY_ERROR); } for (String warning : warnings) { addBuildMarker(warning, IMarker.SEVERITY_WARNING); } for (String error : classpathErrors) { addClasspathMarker(error, IMarker.SEVERITY_ERROR); } } private void clearBuildMarkers() throws CoreException { IFile bndFile = getProject().getFile(Project.BNDFILE); if (bndFile.exists()) { bndFile.deleteMarkers(MARKER_BND_PROBLEM, true, IResource.DEPTH_INFINITE); } } private IResource getBuildMarkerTargetResource() { IProject project = getProject(); IResource bndFile = project.getFile(Project.BNDFILE); if (bndFile == null || !bndFile.exists()) return project; return bndFile; } private void addBuildMarker(String message, int severity) throws CoreException { IResource resource = getBuildMarkerTargetResource(); IMarker marker = resource.createMarker(MARKER_BND_PROBLEM); marker.setAttribute(IMarker.SEVERITY, severity); marker.setAttribute(IMarker.MESSAGE, message); // marker.setAttribute(IMarker.LINE_NUMBER, 1); } private void addClasspathMarker(String message, int severity) throws CoreException { IResource resource = getBuildMarkerTargetResource(); IMarker marker = resource.createMarker(BndContainerInitializer.MARKER_BND_CLASSPATH_PROBLEM); marker.setAttribute(IMarker.SEVERITY, severity); marker.setAttribute(IMarker.MESSAGE, message); // marker.setAttribute(IMarker.LINE_NUMBER, 1); } private void log(int level, String message, Object... args) { if (logLevel >= level) buildLog.add(String.format(message, args)); } }
7898858f8b822f799339e94cfa97f8463a5083b1
c46cbeb710e7d1e9c74e06a51715ca4c9ce91c3c
/Project02/src/URCalculator.java
4efb856d9b537afd905a9b67b13bebd35559d545
[]
no_license
oddguan/CSC-172
e54ddb48132c75ca469f5d63c43d9ac28a030756
ab1679d2fa38bb28e0591eea1e775e7aa2498583
refs/heads/master
2021-03-27T11:54:05.776285
2018-10-11T04:02:29
2018-10-11T04:02:29
104,930,015
2
2
null
null
null
null
UTF-8
Java
false
false
18,317
java
import java.util.*; public class URCalculator { private static Map<String, String> variables = new HashMap<>(); //A hashmap that stores values of variables private static boolean empty = false; //a boolean that indicates whether the evaluate stack is empty private static String[] split(String input){ //a method that splits the string in a desired way //split the string based on the operators String[] s = input.split("((?<=[\\+|\\-|\\*|\\/|\\(|\\)\\[\\]\\{\\}])|(?=[\\+|\\-|\\*|\\/|\\(|\\)\\[\\]\\{\\}]))"); ArrayList<String> sal = new ArrayList<String>(Arrays.asList(s)); //convert the array to an arraylist for(int i=0;i<sal.size();i++){ //for each element in the array if(sal.get(i).chars().allMatch(Character::isDigit) || variables.containsKey(sal.get(i))){ //if the read is a number if(i>=1 && sal.get(i-1).equals("+")){ //if the element before the number is a "+" if(i==1){ //if the number is the second element sal.remove(i-1); //remove the plus sign before it because it has no usage i=-1; //start at the beginning again } else if(i==2 && sal.get(i-2).equals("+")){ //if two elements before the number are all "+" sal.remove(i-1); //remove both of the "+" sal.remove(i-2); i = i - 3; //start at the number again } //if two elements before the number are all "+" and the third element before the number is not a number else if(i>2 && sal.get(i-2).equals("+") && (!sal.get(i-3).chars().allMatch(Character::isDigit) || !variables.containsKey(sal.get(i-3)))){ sal.remove(i-1); //remove both of the "+" sal.remove(i-2); sal.add(i-2,"+"); //add another plus i = i - 2;//start at the number again } //if two elements before the number are all "+" and the third element before the number is a number else if(i>2 && sal.get(i-2).equals("+") && (sal.get(i-3).chars().allMatch(Character::isDigit) || variables.containsKey(sal.get(i-3)))){ sal.remove(i-1); //only remove 1 "+" i = i - 2; //start again } else if(sal.get(i-2).equals("-")){ //check the invalid expression System.out.println("This is not a valid expression (can't put minus sign before a plus sign)"); break; } } else if(i>=1 && sal.get(i-1).equals("-")){ //if the element before the number is a "-" if(i==1){//if the number is the second element sal.add(0,"0"); //add a zero before the minus sign i=i+1; //start at the next element } //if two elements before the number is a parentheses, remove the minus sign and multiply the element by -1 else if(sal.get(i-2).equals("(") || sal.get(i-2).equals("[") || sal.get(i-2).equals("{")){ sal.set(i, Double.toString((Double.parseDouble(sal.get(i))*(-1)))); sal.remove(i-1); i=i-2; } else if(sal.get(i-2).equals("+")){ //if two elements before the number is a plus sign sal.remove(i-2); //remove the plus sign i = i - 2; } else if(sal.get(i-2).equals("-")){ //if two elements before the number is a minus sign sal.remove(i-1); //remove both of the numbers sal.remove(i-2); sal.add(i-2,"+"); //add a plus sign before the element i=i-3; } } } } return sal.toArray(new String[sal.size()]); //return the revised version of the string into an array } private static String evaluateExpression(String input){ //a method that evaluate the expression Stack<String> operators = new Stack<String>(); //initialize a empty stack that stores operators ArrayList sorted = new ArrayList(); //an arraylist that stores the expression after performing the shunting yard algorithm Stack evaluate = new Stack(); //a stack to evaluate the expression boolean ope = true; //a boolean to check whether all of the operators are supported in the expression empty = false; for(String w : split(input)){ //for every element in the input if(w.chars().allMatch(Character::isDigit)){ //if the element is a number sorted.add(Double.valueOf(w)); //put it into the output arraylist } else if(w.contains(".")){ //if the element contains a dot, it is a number sorted.add(Double.valueOf(w));//put it into the output arraylist } else if(variables.containsKey(w)){ //if the element is a name of the variable that has a given value before try{ sorted.add(Double.valueOf(variables.get(w))); //put the value of the variable into the output arraylist } catch(NullPointerException npe){ //catch the null pointer exception if the value of the variable is null System.out.println("variable has a value of NULL (NullPointerException)"); } } else if(operators.isEmpty()){ //else means the element is not a number. if the operator stack is empty, push the operator onto the stack operators.push(w); } //else if the element is one of the supported given operators else if(w.equals("(") || w.equals(")") || w.equals("+") || w.equals("-") || w.equals("*") || w.equals("/") || w.equals("]") || w.equals("}") || w.equals("[") || w.equals("{")){ if(w.equals("(") || w.equals("[") || w.equals("{")){ //if the operator is one of the left parentheses operators.push(w); //push it directly to the stack } else if(w.equals("*") || w.equals("/")){ //if the operator is either * or / if(operators.peek().equals("(") || operators.peek().equals("[") || operators.peek().equals("{")){ //if the element before is the left parentheses operators.push(w); //push it directly to the stack } else if(operators.peek().equals("+")||operators.peek().equals("-")){ //if the element before is + or - operators.push(w); //push it directly to the stack } else if(operators.peek().equals("*")||operators.peek().equals("/")){ //if the element before is * or / sorted.add(operators.peek()); //add the element before to the output arraylist operators.pop(); //pop the operator before operators.push(w); //push the element onto the stack } } else if(w.equals("+") || w.equals("-") ){ //if the operator is either + or - if(operators.peek().equals("*") || operators.peek().equals("/")){ //if the element before is * or / sorted.add(operators.peek()); //add the element before to the output arraylist operators.pop(); //pop the operator before sorted.add(w); //push the element onto the stack } else if(operators.peek().equals("+")||operators.peek().equals("-")){ //if the element before is either + or - sorted.add(operators.peek()); //do the same thing as above operators.pop(); operators.add(w); } else if(operators.peek().equals("(") || operators.peek().equals("[") || operators.peek().equals("{")){ //if the element before is one of the left parentheses operators.push(w); //push the element directly onto the stack } } else if(w.equals(")")){ //if the element is the small right parentheses while(!operators.peek().equals("(")){//while the top element on the operator stack is not the left corresponding parentheses if(operators.peek().equals("{") || operators.peek().equals("[")){ //if the top element is not the corresponding parentheses //the order of the parentheses in the expression is wrong System.out.println("Invalid expression (parentheses out of order ) )"); ope=false; break; //berak the loop because the expression is wrong } sorted.add(operators.peek()); //add the top element on the operator stack into the output arraylist operators.pop(); //pop the operator } operators.pop(); //pop the last operator } else if(w.equals("]")){ //same as above while(!operators.peek().equals("[")){ if(operators.peek().equals("{") || operators.peek().equals("(")){ System.out.println("Invalid expression (parentheses out of order ] )"); ope=false; break; } sorted.add(operators.peek()); operators.pop(); } operators.pop(); } else if(w.equals("}")){ //same as above while(!operators.peek().equals("{")){ if(operators.peek().equals("(") || operators.peek().equals("[")){ System.out.println("Invalid expression (parentheses out of order } )"); ope=false; break; } sorted.add(operators.peek()); operators.pop(); } operators.pop(); } } else{ //if the element is not one of the supported operators System.out.println("The operator is not supported"); ope = false; break; //break the shunting yard loop } } while(!operators.isEmpty() && ope){ //while the operator stack is not empty if(!(operators.peek().equals("(") || operators.peek().equals(")") || operators.peek().equals("[") || operators.peek().equals("]") || operators.peek().equals("{") || operators.peek().equals("}"))){ sorted.add(operators.peek()); //pop everything off except the parentheses and add them into the sorted list in the correct order } operators.pop(); } for(int i=0;i<sorted.size();i++){ if(sorted.get(i) instanceof Double){ //if the element in the sorted arraylist is a number evaluate.push(sorted.get(i)); //push it onto the evaluate stack } else{ //if the element is the operator try{ if(sorted.get(i).equals("+")){ //if the operator is + Object first = evaluate.peek(); //sum the top two elements on the evaluate stack evaluate.pop();//delete the old element Object second = evaluate.peek(); evaluate.pop(); evaluate.push((double)first + (double)second); //push the sum onto the stack } else if(sorted.get(i).equals("-")){ //if the operator is - Object first = evaluate.peek(); //calculate the difference evaluate.pop(); //delete the old element Object second = evaluate.peek(); evaluate.pop(); evaluate.push((double)second - (double)first); //push the difference onto the stack } else if(sorted.get(i).equals("*")){ //if the operator is * Object first = evaluate.peek();//calculate the multiplication evaluate.pop(); //delete the old element Object second = evaluate.peek(); evaluate.pop(); evaluate.push((double)first * (double)second); //push the multiplication onto the stack } else if(sorted.get(i).equals("/")){ //if the operator is / Object first = evaluate.peek(); //calculate the division evaluate.pop(); //delete the old element Object second = evaluate.peek(); evaluate.pop(); evaluate.push((double)second / (double)first); //push the division onto the stack } } catch(EmptyStackException ese){ //catch any error that causes the stack to be empty empty=true; } } } try{ if(ope){ //if ope is still true, that means every operator is supported return evaluate.peek() + ""; //return the result of the expression } else{ return null; //return null if evaluation cannot be performed } } catch(EmptyStackException ese){ //catch any error that causes the stack to be empty empty = true; } if(empty){ //if the stack is empty System.out.println("The expression is not well formed (Empty Stack)"); } return null; //return null if unable to evaluate } private static void storeVariable(String input){ //a method that stores the value of the variable String right = ""; ArrayList<Integer> p = new ArrayList<>(); if(input.equals("clearall")){ //if the user wants to clear all the memories of the variables variables = new HashMap<>(); //re-initialize the variable hashmap System.out.println("All variables cleared."); } else if(input.contains("clear")){//if not clear all and still contains clear String[] s = input.split("r",2); //read the substring after "clear" if(variables.containsKey(s[1])){ //if there is a variable that the user wants to clear variables.remove(s[1]); //remove the key System.out.println(s[1] + " has been removed"); } else{ System.out.println("There is no value that has been stored for this variable"); } } else{ //read all of the equal signs in the input, store the index for(int i=0;i<input.length();i++){ if(input.charAt(i) == '='){ p.add(i); } } if(p.get(p.size()-1)>0){ //stores the value in a string right = input.substring(p.get(p.size()-1)+1); } int post = 0; for(int i=0;i<p.size();i++){ //if the user is replacing a exsisting variable if(variables.containsKey(input.substring(post,p.get(i))) && evaluateExpression(right)!=null){ //output the variable name and the value that has been stored for this variable System.out.print(input.substring(post,p.get(i))+" = "); System.out.println(evaluateExpression(right)+" stored"); variables.replace(input.substring(post,p.get(i)), evaluateExpression(right)); } else if(evaluateExpression(right)!=null){ //if the expression in the right is not null try{ //try to store the value into the hashmap variables.put(input.substring(post,p.get(i)), evaluateExpression(right)); System.out.print(input.substring(post,p.get(i))+" = "); System.out.println(variables.get(input.substring(post,p.get(i)))+" stored"); post = p.get(i)+1; } catch(NumberFormatException nfe){ //catch the null pointer exception if the user is trying to store the value of the variable to be null System.out.println("THe equation is not well formed (NumberFormatException: Empty String)"); } } } } } public static void main(String[] args) { boolean goOn = true; //a boolean to control the program System.out.println("Welcome to use my calculator."); while(goOn){ System.out.println("Enter the equation, store the value of a specific variable or clear the storage of variables below:"); Scanner scan = new Scanner(System.in); //scan the input from the user String input = scan.nextLine(); if(input.equals("exit")){ //if the user wants to exit the program System.out.println("Thanks for using!"); goOn=false; System.exit(0); //exit } if(input.contains("=") || input.contains("clear")){ //if the input contains equal sign or contains clear storeVariable(input); //perform the storevariable method } else{ if(evaluateExpression(input)!=null){ //if evaluating the expression does not return null System.out.print(">>>"); System.out.println(evaluateExpression(input)); //print out the result } } } } }
b48db755b807a4ca291be0041b7ceb9b16cb7d67
485a038a4af182a76690467af6ce1814ffff0a15
/src/main/java/com/greglturnquist/magicspreadsheet/BookAndShort.java
28cd970c4bb6dc5924499eaa743ae61dbfe7f017
[ "Apache-2.0" ]
permissive
gregturn/magic-spreadsheet
26aa4e68a3fe137454bd826ddd2cd155cb1b9ff1
685b1cc772a85c6ebd0bd917e4b3279f9451a10c
refs/heads/master
2020-03-23T08:47:59.194373
2018-09-14T17:56:59
2018-09-14T17:56:59
141,348,665
0
0
null
null
null
null
UTF-8
Java
false
false
899
java
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.greglturnquist.magicspreadsheet; import lombok.Data; import lombok.NoArgsConstructor; /** * @author Greg Turnquist */ @Data @NoArgsConstructor class BookAndShort { String bookShort; String bookTitle; String bookSeries; Integer bookSeriesNumber; double kenpc; }
eb725640f0211e3db4dc26b06c0ff8e9598c5fb5
e213a97acc4bc012131ce16d05254a4c6614507d
/src/com/uom/pimote/SensorManagement.java
72b76b41a6e953afb817dd63ee698def73006d33
[]
no_license
offbye/PiMote-Android-App
4dc16c30f406b189404c899a784962d8aab35cae
e37df3e9fda4d646bea85daf280bca3214a0e994
refs/heads/master
2020-12-11T03:49:16.198080
2013-08-27T13:39:11
2013-08-27T13:39:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,791
java
package com.uom.pimote; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * Created by Tom on 05/08/2013. */ public class SensorManagement implements SensorEventListener { float sensorX; float sensorY; float sensorZ; SensorManager mSensorManager; Sensor mAccelerometer; int speed; TCPClient tcp; public SensorManagement(Context c, int speedValue, TCPClient tcp) { this.tcp = tcp; mSensorManager = (SensorManager) c.getSystemService(Activity.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); switch(speedValue){ case 1: speed = SensorManager.SENSOR_DELAY_NORMAL; break; case 2: speed = SensorManager.SENSOR_DELAY_GAME; break; case 3: speed = SensorManager.SENSOR_DELAY_UI; break; } mSensorManager.registerListener(this, mAccelerometer, speed); } public void pause() { mSensorManager.unregisterListener(this); } public void resume() { mSensorManager.registerListener(this, mAccelerometer, speed); } public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return; sensorX = event.values[0]; sensorY = event.values[1]; sensorZ = event.values[2]; tcp.sendMessage(Communicator.SEND_DATA + "," + "8827," + sensorX + "," + sensorY+","+sensorZ); } public float[] getValues() { return new float[]{sensorX, sensorY, sensorZ}; } }
c9d93448f74fdba709a8344a58a6dee4b5cd9e4c
42c2a9050521d9cb5ff094c8179ecf6a68830b19
/src/test/java/pro/landlabs/pricing/test/PriceDataMother.java
6158c11e1ea67c3ab2de18708e95d992edd507e0
[]
no_license
alexluix/last-price-ws
e5997585fd66e803041decafc595c3029aeb00a3
bbb26e9fe4dac2ea6c08ef273f85cf2d84668fd7
refs/heads/master
2021-09-19T02:50:27.389768
2018-07-22T22:11:00
2018-07-22T22:11:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,107
java
package pro.landlabs.pricing.test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.Resources; import org.joda.time.LocalDateTime; import pro.landlabs.pricing.model.Price; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.Random; public class PriceDataMother { private static final String TEST_DATA_FOLDER = "test-data"; private static ObjectMapper objectMapper = new ObjectMapper(); public static String getJsonPriceDataChunk1() { return readResourceFile(TEST_DATA_FOLDER + "/price-data-chunk-1.json"); } public static String getJsonPriceDataChunkCorrupted() { return readResourceFile(TEST_DATA_FOLDER + "/price-data-chunk-corrupted.json"); } private static String readResourceFile(String filePath) { URL url = Resources.getResource(filePath); try { return Resources.toString(url, Charset.forName("UTF-8")); } catch (IOException e) { throw new RuntimeException(e); } } public static Price<JsonNode> createRandomPrice() { Random random = new Random(); int refId = random.nextInt(1_000); return createRandomPrice(refId, LocalDateTime.now()); } public static Price<JsonNode> createRandomPrice(int refId, LocalDateTime localDateTime) { return createPrice(refId, localDateTime, createRandomPricePayload()); } private static JsonNode createRandomPricePayload() { Random random = new Random(); double randomAmount = 1 + Math.pow(random.nextInt(9) + 1, -1); JsonNode pricePayload; try { pricePayload = objectMapper.readValue("{ \"price\": " + randomAmount + " }", JsonNode.class); } catch (IOException e) { throw new RuntimeException(e); } return pricePayload; } private static Price<JsonNode> createPrice(long refId, LocalDateTime asOf, JsonNode pricePayload) { return new Price<>(refId, asOf, pricePayload); } }
9d3e4ad6c65bbea20bb79336c0c173afd4a46e3a
22ee39a7ea78e235b613cf83168795c644886b7b
/swf_statemachine_sm_model/src/test/java/org/salgar/swf_statemachine/enumeration/state/Intial2StateEnumeration.java
ec1f5e0f280a4f1f1ae5c6dc42600928f748400d
[]
no_license
mehmetsalgar/swf_statemachine
467410b43400173d1e36650115dd049dc8cde8b8
b976a4c44e4117d321322b8c287abb5fb92bd98c
refs/heads/master
2016-09-06T08:09:14.348893
2014-01-10T11:27:04
2014-01-10T11:27:04
1,808,680
3
0
null
null
null
null
UTF-8
Java
false
false
940
java
package org.salgar.swf_statemachine.enumeration.state; import org.salgar.statemachine.domain.StateEnumeration; import org.salgar.statemachine.domain.StateMachineEnumeration; import org.salgar.swf_statemachine.enumeration.InitialTestStateMachineEnumeration; public enum Intial2StateEnumeration implements StateEnumeration { STATE_5("state_5", InitialTestStateMachineEnumeration.STATE_MACHINE_2), STATE_6( "state_6", InitialTestStateMachineEnumeration.STATE_MACHINE_2); private String stateName; private StateMachineEnumeration stateMachineEnumeration; Intial2StateEnumeration(String stateName, StateMachineEnumeration stateMachineEnumeration) { this.stateName = stateName; this.stateMachineEnumeration = stateMachineEnumeration; } public String getStateName() { return this.stateName; } public StateMachineEnumeration getStateMachineName() { return this.stateMachineEnumeration; } }
0c588874b743fbefdc5c640fc6ccfa004d836861
196f8a82224b860119af79f3be8428621ff1da17
/app/src/main/java/Services/DarajaApiClient.java
71732d4cd51b3238fa941aa683018593e327892a
[]
no_license
denniskimtai/kenyan_rides_app
68879505dc08b33d74a418b9f34c3336402a66fa
0f2ee04be526244f29379f6cb62d4a5ebba01f06
refs/heads/master
2023-07-07T10:38:36.045406
2021-08-10T20:40:24
2021-08-10T20:40:24
282,633,323
0
0
null
null
null
null
UTF-8
Java
false
false
2,508
java
package Services; import Interceptor.AccessTokenInterceptor; import Interceptor.AuthInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static com.gcodedevelopers.kenyanrides.Constants.BASE_URL; import static com.gcodedevelopers.kenyanrides.Constants.CONNECT_TIMEOUT; import static com.gcodedevelopers.kenyanrides.Constants.READ_TIMEOUT; import static com.gcodedevelopers.kenyanrides.Constants.WRITE_TIMEOUT; public class DarajaApiClient { private Retrofit retrofit; private boolean isDebug; private boolean isGetAccessToken; private String mAuthToken; private HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); public DarajaApiClient setIsDebug(boolean isDebug) { this.isDebug = isDebug; return this; } public DarajaApiClient setAuthToken(String authToken) { mAuthToken = authToken; return this; } public DarajaApiClient setGetAccessToken(boolean getAccessToken) { isGetAccessToken = getAccessToken; return this; } private OkHttpClient.Builder okHttpClient() { OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder(); okHttpClient .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) .addInterceptor(httpLoggingInterceptor); return okHttpClient; } private Retrofit getRestAdapter() { Retrofit.Builder builder = new Retrofit.Builder(); builder.baseUrl(BASE_URL); builder.addConverterFactory(GsonConverterFactory.create()); if (isDebug) { httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); } OkHttpClient.Builder okhttpBuilder = okHttpClient(); if (isGetAccessToken) { okhttpBuilder.addInterceptor(new AccessTokenInterceptor()); } if (mAuthToken != null && !mAuthToken.isEmpty()) { okhttpBuilder.addInterceptor(new AuthInterceptor(mAuthToken)); } builder.client(okhttpBuilder.build()); retrofit = builder.build(); return retrofit; } public STKPushService mpesaService() { return getRestAdapter().create(STKPushService.class); } }
3975365024ec8441bd5011c40eb06af1c54f325d
a5c143c0d629cb6baa40c113cab33808b9644dca
/app/src/main/java/com/chiligram/android/app/modelo/messagesLib/SentFileMessageHolder.java
d4a8eab7779b2a2cac98c7c043070a18c828b9d2
[]
no_license
educanovas93/Chiligram
ed235a798ee4462fe0ab57ae5b41bcfdfae4b370
337e01aa0cba9ee1081546a791c8633d9585feac
refs/heads/master
2021-09-28T16:19:28.879484
2021-09-27T11:56:31
2021-09-27T11:56:31
235,199,204
1
0
null
null
null
null
UTF-8
Java
false
false
366
java
package com.chiligram.android.app.modelo.messagesLib; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chiligram.android.app.modelo.Message; public class SentFileMessageHolder extends RecyclerView.ViewHolder { public SentFileMessageHolder(View itemView) { super(itemView); } void bind(Message m){ } }
92a798054c15633c5dc6719ed6243fda97f923bf
74f14fce29972bddea47229c7dd1069968434f0b
/boot/src/main/java/tw/freely/impl/rest/MemberController.java
d23195928813cd59d904d537fe822a2c74590ec1
[]
no_license
TingChern/boot
8be8c5a3f448165129cbc7cc687411ba554acb2d
f0e24a0e7c11bcea1a1216704aecfb6b316350f0
refs/heads/master
2023-06-02T14:33:51.477789
2021-06-17T09:25:35
2021-06-17T09:25:35
377,730,438
0
0
null
null
null
null
UTF-8
Java
false
false
1,931
java
package tw.freely.impl.rest; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tw.freely.impl.model.Member; @RestController @RequestMapping(value = "/members", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) public class MemberController { private static Map<Integer,Member> members = new HashMap<>(); static { members.put(1, new Member(1, "Apple")); members.put(2, new Member(2, "Orange")); } @GetMapping("/{id}") public Member get(@PathVariable("id") String id) { Optional<Member> optionalMember = Optional.of(members.get(Integer.parseInt(id))); return optionalMember.get(); } @PostMapping() public Member post(@RequestBody Member newMember) { Integer key = members.keySet().stream().max(Integer::compare).get() + 1; newMember.setId(key); members.put(key, newMember); return newMember; } @PutMapping("/{id}") public Member put(@PathVariable("id") String id, @RequestBody Member member) { members.put(Optional.of(members.get(member.getId())).get().getId(), member); return Optional.of(members.get(Integer.parseInt(id))).get(); } @DeleteMapping("/{id}") public Object delete(@PathVariable("id") String id) { members.remove(Integer.parseInt(id)); return id; } // // @Override // public Object patch(String... pk) { // // TODO Auto-generated method stub // return null; // } }
a1ca4db660ba896c5f1f747d3909a3f93a0e2b9c
c02a71246c309fb370ded9bb72ad92e3d408d917
/src/test/java/helpers/DriverHelper.java
8e4125b46d5466116b340b4531da07a61aec9ac1
[]
no_license
npolyakova/qa_guru_11
011018ab44d5cc4742953d736495ab7ae3e44d53
fde0904292369a2b6aa44090447122d93c92cf15
refs/heads/master
2023-04-13T06:00:27.896384
2021-04-18T15:47:39
2021-04-18T15:47:39
352,870,365
0
0
null
null
null
null
UTF-8
Java
false
false
1,516
java
package helpers; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Selenide; import config.ConfigHelper; import io.qameta.allure.selenide.AllureSelenide; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.WebDriverRunner.getWebDriver; import static com.codeborne.selenide.logevents.SelenideLogger.addListener; import static org.openqa.selenium.logging.LogType.BROWSER; public class DriverHelper { public static void configureDriver() { addListener("AllureSelenide", new AllureSelenide().screenshots(true).savePageSource(true)); Configuration.baseUrl = ConfigHelper.getWebUrl(); Configuration.startMaximized = true; Configuration.timeout = 10000; if (ConfigHelper.isRemoteWebDriver()) { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("enableVNC", true); capabilities.setCapability("enableVideo", true); Configuration.browserCapabilities = capabilities; Configuration.remote = ConfigHelper.getWebRemoteDriver(); } } public static String getSessionId(){ return ((RemoteWebDriver) getWebDriver()).getSessionId().toString().replace("selenoid",""); } public static String getConsoleLogs() { return String.join("\n", Selenide.getWebDriverLogs(BROWSER)); } }
611d90cc10e1eda0a2ede9852325698b628a65d3
0ae9594087f7f7fdd710544a63b1bcb2bc2f1fea
/src/main/java/life/majiang/community/community/interceptor/WebConfig.java
96e5a1e3a243b95b7976d48985c36b580189dfa2
[]
no_license
ZuofromCN/community
d76a17f6e1eb1499d2f456a05ddbb5e7d674cdd1
ad03f7a6d58d88df6faf416709f76a54bf72ae89
refs/heads/master
2022-06-24T23:34:29.111359
2020-03-27T08:48:06
2020-03-27T08:48:06
241,244,049
0
0
null
2022-06-17T02:55:33
2020-02-18T01:19:39
Java
UTF-8
Java
false
false
701
java
package life.majiang.community.community.interceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private SessionInterceptor sessionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessionInterceptor).addPathPatterns("/**"); } }
8d5d7230e84bf5bc9670262a2c7e196d9a384594
1682dc9d2f1e18f2777b28c6c72d93bf6d676d26
/Day 17 - Binary Tree/PostorderTraversal.java
a4e95fae699f3e0c83942f6467620be5d0c76f5d
[]
no_license
nachiketbhuta/DSA-Interview-Problems
439db05a5e999e279e2385a4f384847ee99597dc
88f99a30369ab0209a5e51f05d8dd5450ef7af11
refs/heads/main
2023-01-16T01:52:36.793604
2020-11-18T14:18:52
2020-11-18T14:18:52
312,611,030
1
0
null
null
null
null
UTF-8
Java
false
false
1,444
java
import java.util.Stack; public class PostorderTraversal { static class Node { int data; Node left, right; Node(int data) { this.data = data; this.left = null; this.right = null; } } public static void postorderTraversalRecursive(Node root) { if (root == null) return; postorderTraversalRecursive(root.left); postorderTraversalRecursive(root.right); System.out.print(root.data + " "); } public static void postorderTraversalIterative(Node root) { if (root == null) return; Stack<Node> stack1 = new Stack(); Stack<Node> stack2 = new Stack(); stack1.push(root); while (!stack1.isEmpty()) { Node curr = stack1.pop(); // System.out.println("Popped element: " + curr.data); stack2.push(curr); if (curr.left != null) { // System.out.println("Push L: " + curr.left.data); stack1.push(curr.left); } if (curr.right != null) { // System.out.println("Push R: " + curr.right.data); stack1.push(curr.right); } } while (!stack2.isEmpty()) { Node temp = stack2.pop(); System.out.print(temp.data + " "); } System.out.println(); } public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); postorderTraversalRecursive(root); System.out.println(); postorderTraversalIterative(root); System.out.println(); } }
c736a69526a019e9e12bd54f712c0f9a1f1d6246
8a72d5139e60437500605b404b266469d04d2dcc
/src/IsAnagram.java
cde80e6bcf1e0c005fc8be16b503f3e5adae2968
[]
no_license
OSir-C/Leetcode
42099eb6acdba142809cea1a652d2ccef3d1d26d
42c96b86ca67eff0101653d7af6e5cae44aa79e6
refs/heads/master
2022-12-20T22:35:10.014924
2020-09-28T12:30:31
2020-09-28T12:30:31
290,155,312
0
0
null
null
null
null
UTF-8
Java
false
false
1,353
java
import java.util.Arrays; /** * 有效的字母异位词 * 242 https://leetcode-cn.com/problems/valid-anagram/ */ public class IsAnagram { public static void main(String[] args) { } /** * 数组排序 * 时间复杂度O(NlogN) * 空间复杂度O(N) * @param s * @param t * @return */ public static boolean solution1(String s, String t) { // 边界条件 if (s.length() != t.length()) return false; // 创建数组 char[] sArr = s.toCharArray(); char[] tArr = t.toCharArray(); // 数组排序 Arrays.sort(sArr); Arrays.sort(tArr); return Arrays.equals(sArr, tArr); } /** * 哈希表 * 时间复杂度 O(N) * 空间复杂度 O(1) * @param s * @param t * @return */ public static boolean solution2(String s, String t) { // 边界条件 if (s.length() != t.length()) return false; int[] counter = new int[26]; // 统计计数 for (int i = 0; i < s.length(); i++) { counter[s.charAt(i) - 'a']++; counter[t.charAt(i) - 'a']--; } // 任何一个字母大于0,都不是异位词 for (int count : counter) { if (count != 0) return false; } return true; } }
302d905d03859486eddaa7dab20d90fb0db985c8
42a9d8b3ef87209481e6605107c3a4261ab07a5e
/WeatherXML/app/src/main/java/com/royalbob/weatherxml/WeatherParser.java
386222d08e5391cf5c6222db0837b4bd136b3e4e
[]
no_license
RoyalBob/Android
f2994308b22eca6814125e1051a0334f434fc547
bcf440d8ca4225f729113cd2d2fb9f0e10e8db79
refs/heads/master
2021-06-21T16:01:14.427757
2017-07-07T10:13:38
2017-07-07T10:13:38
48,705,150
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package com.royalbob.weatherxml; import java.io.InputStream; import java.util.List; public interface WeatherParser { /** * 解析输入流 得到Book对象集合 * @param is * @return * @throws Exception */ public List<Weather> parse(InputStream is) throws Exception; /** * 序列化Book对象集合 得到XML形式的字符串 * @param books * @return * @throws Exception */ public String serialize(List<Weather> books) throws Exception; }
5be758a2e63fc757ad1f65903af3672e2682d474
b777c7a10237da84c132238af66a942da563529e
/Rusted/game-lib/com/corrodinggames/rts/gameFramework/c/class_28.java
90e8852102d3699c30928ec8ddb968baa24e80d3
[]
no_license
macuser47/SaltyRust
6ce11ffe9a8d6bcd609e3346f6c17f5f580ce4a8
02db02c7dadbd5397367d66e9e39331fe3f438b7
refs/heads/master
2020-04-20T13:09:11.311551
2019-02-02T18:03:02
2019-02-02T18:03:02
168,861,365
0
0
null
null
null
null
UTF-8
Java
false
false
1,106
java
package com.corrodinggames.rts.gameFramework.c; import android.graphics.Paint; import com.corrodinggames.rts.gameFramework.h.class_22; import com.corrodinggames.rts.gameFramework.h.class_27; // $FF: renamed from: com.corrodinggames.rts.gameFramework.c.n public class class_28 extends class_27 { // $FF: renamed from: a float[] float[] field_4; // $FF: renamed from: b int int field_5 = 0; // $FF: renamed from: c android.graphics.Paint Paint field_6; // $FF: renamed from: d int int field_7; class_28(int var1, Paint var2) { this.field_7 = var1; this.field_4 = new float[var1 * 2]; this.field_6 = var2; } // $FF: renamed from: a (float, float) void public final void method_147(float var1, float var2) { this.field_4[this.field_5] = var1; this.field_4[this.field_5 + 1] = var2; this.field_5 += 2; } // $FF: renamed from: a (com.corrodinggames.rts.gameFramework.h.l) void public void method_146(class_22 var1) { var1.method_86(this.field_4, 0, this.field_5, this.field_6); class_174.method_1235(this); } }
a3294ade81969c6ae9c9924543e38b3225cff15a
fc5f7c7d4c11a0bae8cec90600cbe47aedab1b70
/app/src/main/java/com/submission/picodiploma/moviecatalogue/MainActivity.java
c432295918277f402a39051e4e95f7219f78747b
[]
no_license
ndgspn/submission1-moviecatalogue
74ac4ecea42117a6b5e465048f3ee216bb8b3657
bfd44d63fd7f79bff8cf32b0213ab8e86379936b
refs/heads/master
2020-05-25T03:14:24.994155
2019-05-20T14:02:26
2019-05-20T14:02:26
187,596,024
0
0
null
null
null
null
UTF-8
Java
false
false
3,571
java
package com.submission.picodiploma.moviecatalogue; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.ColorInt; 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.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private String[] movieTitle; private String[] movieScore; private String[] movieReleaseDate; private String[] movieOverview; private TypedArray movieImage; private TypedArray movieImagePoster; private MovieAdapter adapter; private ArrayList<Movie> movies; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getSupportActionBar() != null) getSupportActionBar().setTitle("The Movie Catalogue"); MyColorUtility.darkenNavigationBar(this, R.color.colorBlack); MyColorUtility.darkenStatusBar(this, R.color.colorBlack); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000"))); adapter = new MovieAdapter(this); ListView listView = findViewById(R.id.lv_movie_lists); listView.setAdapter(adapter); prepare(); addItem(); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Toast.makeText(MainActivity.this, movies.get(i).getTitle(), Toast.LENGTH_SHORT).show(); Movie movie = new Movie(); movie.setPhotoPoster(movies.get(i).getPhotoPoster()); movie.setPhoto(movies.get(i).getPhoto()); movie.setTitle(movies.get(i).getTitle()); movie.setScore(movies.get(i).getScore()); movie.setOverview(movies.get(i).getOverview()); movie.setReleaseDate(movies.get(i).getReleaseDate()); Intent intent = new Intent(MainActivity.this, DetailMovieActivity.class); intent.putExtra("Movie", movie); startActivity(intent); } }); } private void prepare() { movieTitle = getResources().getStringArray(R.array.movie_title); movieScore = getResources().getStringArray(R.array.movie_score); movieReleaseDate = getResources().getStringArray(R.array.movie_release_date); movieOverview = getResources().getStringArray(R.array.movie_overview); movieImage = getResources().obtainTypedArray(R.array.movie_photo); movieImagePoster = getResources().obtainTypedArray(R.array.movie_photo_poster); } private void addItem() { movies = new ArrayList<>(); for (int i = 0; i < movieTitle.length; i++) { Movie movie = new Movie(); movie.setPhotoPoster(movieImagePoster.getResourceId(i, -1)); movie.setPhoto(movieImage.getResourceId(i, -1)); movie.setTitle(movieTitle[i]); movie.setScore(String.format("★ %s ", movieScore[i])); movie.setReleaseDate(movieReleaseDate[i]); movie.setOverview(movieOverview[i]); movies.add(movie); } adapter.setMovies(movies); } }
de88f8aa4b46798f09466e7943a3e55391aaa888
65f20dbb7603aebd4de995ecd837f8f34eca758f
/src/main/java/com/produtos/apirest/config/SwaggerConfig.java
1357fdc83e9b84a3cfa1a62585d773632c1c714a
[]
no_license
brunoassis01/ApiProdutosAutenticado
314e962677ad873ef376b9487e8ce6096e602e40
6198e947dd06e47cac0a4d261d18aaf7bf908097
refs/heads/master
2020-08-13T08:16:51.863296
2019-10-14T03:20:27
2019-10-14T03:20:27
214,938,090
0
0
null
null
null
null
UTF-8
Java
false
false
1,614
java
package com.produtos.apirest.config; import springfox.documentation.swagger2.annotations.EnableSwagger2; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.VendorExtension; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import static springfox.documentation.builders.PathSelectors.regex; import java.util.ArrayList; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.produtos.apirest")) .paths(regex("/api.*")) .build() .apiInfo(metaInfo()); } private ApiInfo metaInfo() { ApiInfo apiInfo = new ApiInfo( "Produtos API REST", "API REST de cadastro de produtos.", "1.0", "Terms of Service", new Contact("Michelli Brito", "https://www.youtube.com/michellibrito", "[email protected]"), "Apache License Version 2.0", "https://www.apache.org/licesen.html", new ArrayList<VendorExtension>() ); return apiInfo; } }
1fe61240de44f4993016cec3cd1a2561d80118a0
a3e59d2158a30ad53e4eab26dc9f3ef38287bdd1
/toDoApp_2017/src/main/java/com/bridgelabz/toDoApp/model/GoogleEmails.java
c0859364eb27bd1f6fd9d4dc29c785dc656c6ab8
[]
no_license
iamvinayhv/ToDoApp.
8674be2b340c56c62c128dca86e90d3c7e887451
c32e23b78b886bed941b6ff22413bad01fb9f393
refs/heads/master
2020-12-30T12:12:01.654069
2017-06-28T10:37:14
2017-06-28T10:37:14
91,415,061
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
package com.bridgelabz.toDoApp.model; public class GoogleEmails { private String value; private String type; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "GoogleEmails [value=" + value + ", type=" + type + "]"; } }
ff0740af14fc55e8c2de0aac572ad4884e8d0418
1c352e140f1e0dbc39c28fa992a57029d36dae4c
/src/test/java/com/marinatest/steps/NavigationBarSteps.java
d660682fa0f399c35f6b7e326b08cfde8722d2b8
[]
no_license
Melphomenea/marinatest
af9901508c020d0ab46c68ddde5de1bbf10eb35f
a24704f1fd3ce700b4e5bcc9e986a4c6d6125070
refs/heads/master
2021-08-12T02:45:46.525545
2017-11-14T10:22:24
2017-11-14T10:22:24
110,486,481
0
0
null
null
null
null
UTF-8
Java
false
false
2,080
java
package com.marinatest.steps; import com.marinatest.pages.ErrorPage; import com.marinatest.pages.FormPage; import com.marinatest.pages.LandingPage; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.After; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import javax.inject.Inject; public class NavigationBarSteps { private WebDriver webDriver; private final LandingPage landingPage; private final FormPage formPage; private final ErrorPage errorPage; @Inject public NavigationBarSteps (WebDriver webDriver) { this.webDriver = webDriver; landingPage = PageFactory.initElements(this.webDriver, LandingPage.class); formPage = PageFactory.initElements(this.webDriver, FormPage.class); errorPage = PageFactory.initElements(this.webDriver, ErrorPage.class); } @And("^I click the UI Testing Button in the Navbar$") public void iClickUITestingButton() { formPage.clickUITestingButton(); } @When("^I click on the Homepage in the header$") public void clickHomepageNavbar () { formPage.clickHomepageNavbar(); } @When("^I click the Form button in the header$") public void clickFormNavbar() { landingPage.clickFormNavbar(); } @Then ("^Homepage becomes active element$") public void navHomepageIsActive() { landingPage.isElementActive(); } @Then ("^Form Page becomes active element$") public void navFormPageIsActive() { formPage.isElementActive(); } @Then("^I should navigate to the Form Page$") public void iShouldNavigateToFormPage() { formPage.isFormPageDisplayed(); } @When("^I click the Error button in the header$") public void clickErrorNavbar () { landingPage.clickErrorNavbar(); } @Then("^I should navigate to Error Page$") public void iShouldNavigatetoErrorPage() { Assert.assertTrue(errorPage.isCorrectPage()); } }
3a405e43ded359120b4152f200dd42435674292e
d81860acb15be9226252e9fe07e8d04728a1d6bb
/src/main/java/uk/gov/hmcts/ethos/replacement/docmosis/service/CaseCreationForCaseWorkerService.java
3b92bc10a6345e2f29cdfb5f4568401c5d96c971
[ "MIT" ]
permissive
uk-gov-mirror/hmcts.ethos-repl-docmosis-service
b01284d0ea19384fbb6d13da1014816f12af9b22
4708434131a0c9dbff55aafa5132bef759b28860
refs/heads/master
2023-04-15T13:16:00.447733
2021-04-14T14:27:48
2021-04-14T14:27:48
356,712,718
0
0
null
null
null
null
UTF-8
Java
false
false
3,436
java
package uk.gov.hmcts.ethos.replacement.docmosis.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import uk.gov.hmcts.ecm.common.client.CcdClient; import uk.gov.hmcts.ecm.common.exceptions.CaseCreationException; import uk.gov.hmcts.ecm.common.helpers.UtilHelper; import uk.gov.hmcts.ecm.common.model.ccd.CCDRequest; import uk.gov.hmcts.ecm.common.model.ccd.CaseData; import uk.gov.hmcts.ecm.common.model.ccd.CaseDetails; import uk.gov.hmcts.ecm.common.model.ccd.SubmitEvent; import java.util.List; @Slf4j @RequiredArgsConstructor @Service("caseCreationForCaseWorkerService") public class CaseCreationForCaseWorkerService { private static final String MESSAGE = "Failed to create new case for case id : "; private final CcdClient ccdClient; private final SingleReferenceService singleReferenceService; private final MultipleReferenceService multipleReferenceService; private final PersistentQHelperService persistentQHelperService; @Value("${ccd_gateway_base_url}") private String ccdGatewayBaseUrl; public SubmitEvent caseCreationRequest(CCDRequest ccdRequest, String userToken) { CaseDetails caseDetails = ccdRequest.getCaseDetails(); log.info("EventId: " + ccdRequest.getEventId()); try { return ccdClient.submitCaseCreation(userToken, caseDetails, ccdClient.startCaseCreation(userToken, caseDetails)); } catch (Exception ex) { throw new CaseCreationException(MESSAGE + caseDetails.getCaseId() + ex.getMessage()); } } public CaseData generateCaseRefNumbers(CCDRequest ccdRequest) { CaseData caseData = ccdRequest.getCaseDetails().getCaseData(); if (caseData.getCaseRefNumberCount() != null && Integer.parseInt(caseData.getCaseRefNumberCount()) > 0) { log.info("Case Type: " + ccdRequest.getCaseDetails().getCaseTypeId()); log.info("Count: " + Integer.parseInt(caseData.getCaseRefNumberCount())); caseData.setStartCaseRefNumber(singleReferenceService.createReference( ccdRequest.getCaseDetails().getCaseTypeId(), Integer.parseInt(caseData.getCaseRefNumberCount()))); caseData.setMultipleRefNumber(multipleReferenceService.createReference( UtilHelper.getBulkCaseTypeId(ccdRequest.getCaseDetails().getCaseTypeId()), 1)); } return caseData; } public void createCaseTransfer(CaseDetails caseDetails, List<String> errors, String userToken) { CaseData caseData = caseDetails.getCaseData(); persistentQHelperService.sendCreationEventToSinglesWithoutConfirmation( userToken, caseDetails.getCaseTypeId(), caseDetails.getJurisdiction(), errors, caseData.getEthosCaseReference(), caseData.getOfficeCT().getValue().getCode(), caseData.getPositionTypeCT(), ccdGatewayBaseUrl ); caseData.setLinkedCaseCT("Transferred to " + caseData.getOfficeCT().getValue().getCode()); caseData.setPositionType(caseData.getPositionTypeCT()); log.info("Clearing the CT payload"); caseData.setOfficeCT(null); caseData.setPositionTypeCT(null); } }
bcfd8135f8e5bde437c1c18d31d3bbbad3bef2ac
0ba8eeab8a7d5b0c9430f253c910999b4ec50fab
/src/main/java/com/salon/lucca/service/AuditEventService.java
501c68a2acfebde8168c0294f361526e7cba1c2f
[]
no_license
BulkSecurityGeneratorProject/lucca
5d0aff24708475ee0d43f11874c29b715e2ad2ab
6776a820a13a7a9909a7c9a777f7a2cfb7e1b890
refs/heads/master
2022-12-15T14:50:40.433762
2018-03-12T06:35:55
2018-03-12T06:35:55
296,574,421
0
0
null
2020-09-18T09:22:13
2020-09-18T09:22:12
null
UTF-8
Java
false
false
1,773
java
package com.salon.lucca.service; import com.salon.lucca.config.audit.AuditEventConverter; import com.salon.lucca.repository.PersistenceAuditEventRepository; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.Optional; /** * Service for managing audit events. * <p> * This is the default implementation to support SpringBoot Actuator AuditEventRepository */ @Service @Transactional public class AuditEventService { private final PersistenceAuditEventRepository persistenceAuditEventRepository; private final AuditEventConverter auditEventConverter; public AuditEventService( PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } public Page<AuditEvent> findAll(Pageable pageable) { return persistenceAuditEventRepository.findAll(pageable) .map(auditEventConverter::convertToAuditEvent); } public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) { return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) .map(auditEventConverter::convertToAuditEvent); } public Optional<AuditEvent> find(Long id) { return Optional.ofNullable(persistenceAuditEventRepository.findOne(id)).map (auditEventConverter::convertToAuditEvent); } }
703681fcd53aebe79479c61a0109d13e1f338316
4ab734844123dba2bf46d14a4d184d1f0fcdeb12
/app/src/main/java/com/florianmski/tracktoid/ui/fragments/traktitems/MovieFragment.java
31189e451c4c33ed3f28d3688a41257151388e0b
[ "Apache-2.0" ]
permissive
andy-culshaw/Traktoid
ce4eb5d2ca17c27143b11f124c27a2ed2aaef4fd
70a30f9d026c6cf03318f791e3c56d1565c7b64a
refs/heads/master
2021-01-21T01:35:15.452285
2015-02-12T21:52:07
2015-02-12T21:52:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,120
java
package com.florianmski.tracktoid.ui.fragments.traktitems; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.florianmski.tracktoid.utils.DateHelper; import com.florianmski.tracktoid.utils.DbHelper; import com.florianmski.tracktoid.R; import com.florianmski.tracktoid.TraktoidTheme; import com.florianmski.tracktoid.data.WMovie; import com.florianmski.tracktoid.data.database.ProviderSchematic; import com.florianmski.tracktoid.rx.observables.CursorObservable; import com.florianmski.tracktoid.trakt.TraktManager; import com.florianmski.tracktoid.trakt.TraktSender; import com.florianmski.tracktoid.ui.activities.CommentsActivity; import com.uwetrottmann.trakt.v2.entities.Movie; import com.uwetrottmann.trakt.v2.enums.Extended; import rx.Observable; import rx.functions.Action1; public class MovieFragment extends MediaBaseFragment<WMovie> { private TextView tvTagline; public MovieFragment() {} public static MovieFragment newInstance(String id) { MovieFragment f = new MovieFragment(); Bundle args = getBundle(id); f.setArguments(args); return f; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); tvTagline = (TextView) view.findViewById(R.id.textViewTagline); } @Override public void launchCommentActivity() { CommentsActivity.launchMovie(getActivity(), id); } @Override public TraktSender.Builder addItemToBuilder(TraktSender.Builder builder) { return builder.movie(item.getTraktItem()); } @Override public Observable<WMovie> getDownloadAndInsertItemObservable() { return Observable.just(item).doOnNext(new Action1<WMovie>() { @Override public void call(WMovie wMovie) { DbHelper.insertMovie(getActivity(), wMovie.getTraktItem()); } }); } @Override public void refreshView(WMovie item) { this.item = item; Movie movie = item.getTraktItem(); setSubtitle(String.valueOf(movie.year)); if(movie.tagline != null && !movie.tagline.isEmpty()) { tvTagline.setVisibility(View.VISIBLE); tvTagline.setText("\"" + movie.tagline + "\""); } else tvTagline.setVisibility(View.GONE); tlInfos.removeAllViews(); addInfo("Runtime", DateHelper.getRuntime(movie.runtime)); addInfo("Released", DateHelper.getDate(getActivity(), movie.released)); Double rating = item.getTraktItem().rating; if(rating != null && item.getTraktItem().votes > 0) addInfo("Ratings", String.format("%.01f/10", rating)); addInfo("Certification", movie.certification); refreshGeneralView(item.getTraktBase()); getActionBar().setTitle(movie.title); } @Override public String getDateText(boolean invalidTime) { if(invalidTime) return "Unknown release date"; else return DateHelper.getDate(getActivity(), item.getTraktItem().released); } @Override public WMovie getTraktObject() { Movie movie = TraktManager.getInstance().movies().summary(id, Extended.FULLIMAGES); return new WMovie(movie); } @Override public CursorObservable<WMovie> getCursorObservable() { return new CursorObservable<WMovie>( getActivity(), ProviderSchematic.Movies.withId(id), ProviderSchematic.Movies.PROJECTION, null, null, null) { @Override protected WMovie toObject(Cursor cursor) { return WMovie.unpack(cursor); } }; } @Override public TraktoidTheme getTheme() { return TraktoidTheme.MOVIE; } }
2078891a3be01485b66740adae697f6108f6f5c7
b75855675310ecaeb39b035b746a37cf7bf40c5c
/src/ThreadDemo5/ThreadExecutor3.java
eb4fddce826ddae98bbf0a2f32d9fc6556dc5dcf
[]
no_license
cwc972135903/ThreadMulti
151431bd1d7fe24c2d2d8951ed5b497cb4bcf07d
95c1b295f5dc83c6fa1a49df0256e0235721a1e4
refs/heads/master
2023-03-28T16:09:39.175261
2021-04-04T13:23:13
2021-04-04T13:23:13
348,916,324
0
0
null
null
null
null
UTF-8
Java
false
false
2,670
java
package ThreadDemo5; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.stream.IntStream; /** * <p>Title: xCRMS </p> * Description: 通过ThreadPoolExecutor创建线程池, callable的方式<br> * 1.新线程到来,当前运行的线程是否大于核心线程数量,如果没有,直接加入核心线程运行 * 2.如果核心线程满了,判断等待队列是否满了,如果等待队列没有满,加入等待队列,等待执行 * 3,如果等待队列也满了,查看线程池空闲线程是否还有,如果有创建线程执行 * 4. 如果线程池也没了,直接使用拒绝策略,根据初始化ThreadPoolExecutor的策略进行操作 * Copyright: CorpRights xQuant.com<br> * Company: xQuant.com<br> * * @author wenchao.chai * @version 1.1.1.RELEASE * @date 2020/4/23 16:04 */ public class ThreadExecutor3 { //定义核心线程数量 private static final int CORP_POOL_SIZE = 5; //定义最大线程数量 private static final int MAXIMUM_POOL_SIZE = 50; //定义空闲线程存活时间单位 private static final long KEEP_ALIVE_TIME = 1L; //定义空闲线程存活时间 //定义工作队列 private static BlockingQueue blockingQueue = new ArrayBlockingQueue<>(100); public static void main(String ...args){ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORP_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, blockingQueue, new ThreadPoolExecutor.CallerRunsPolicy()); List<Future> futureList = new ArrayList<>(); IntStream.range(0, 9).forEach(item -> { Future submit = threadPoolExecutor.submit(new CallableTest()); futureList.add(submit); }); futureList.forEach(future -> { try { System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); threadPoolExecutor.shutdown(); } } class CallableTest implements Callable{ @Override public String call() { System.out.println(Thread.currentThread().getName()+"Start:" + "--" + LocalDateTime.now().toString()); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"end:"+ "--" + LocalDateTime.now().toString()); return Thread.currentThread().getName()+"|执行成功"; } }
4eb43b0978764b94f553194d7e06f8e08b8d024a
7654e64202768e67cc356e4410ab857bf059c3e1
/src/main/java/com/example/phoenix/models/Business.java
e6d6ec49a8bee0270f86afa13c17315b930480e5
[]
no_license
PhoenixAdTracking/PhoenixClient
f356cb83f1bddbefac379f76ab23516b5493eb21
961d42140da292b20cb5704c17a63e17c2a02733
refs/heads/master
2023-02-16T14:32:11.709340
2021-01-19T20:00:09
2021-01-19T20:00:09
287,613,489
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
package com.example.phoenix.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Generated; /** * POJO model class for a business's information. */ @Data @Generated @AllArgsConstructor public class Business { /** * The id of the business. */ private int id; /** * The name of the business. */ private String name; }
b3f226b6e97dfea1fb7ea8c75cd0bbb55051b7ef
f6ad3063fc228829ad40f2f287ceb0fb56400cae
/java-for-gitee/pagehelper/src/com/imooc/project/entity/Person.java
e86102bc0bac3bbcce45844388b80de301cb41ba
[ "Apache-2.0" ]
permissive
OSrcD/java-for-linux
dd3418723652d06f48cef7288ce135ac9933fd0f
5424b1af0e74797d57d820425b91c991aa28fda9
refs/heads/master
2023-06-26T15:23:17.882935
2021-07-18T04:52:42
2021-07-18T04:52:42
299,023,756
10
4
MIT
2021-02-18T03:17:13
2020-09-27T12:08:37
Java
UTF-8
Java
false
false
1,424
java
package com.imooc.project.entity; /** * */ public class Person { private Integer id; private String username; private String email; private String gender; private Dept dept; public Person() { } public Person(String username, String email, String gender, Dept dept) { this.id = id; this.username = username; this.email = email; this.gender = gender; this.dept = dept; } public Person(String username, String email, String gender) { this.id = id; this.username = username; this.email = email; this.gender = gender; } public Person(String username, String gender) { this.username = username; this.gender = gender; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } @Override public String toString() { return "Person [id=" + id + ", username=" + username + ", email=" + email + ", gender=" + gender + ", dept=" + dept + "]"; } }