text
stringlengths
10
2.72M
import java.util.Scanner; /** * Counts up to the users number with commas inbetween * @author Cole Girling */ public class Main { /** * The method that is executed when you hit the run button. * @param args the command line arguments */ public static void main(String[] args) { //scanner for user input Scanner input = new Scanner(System.in); //ask the user for a positive integer System.out.println("Please enter a positive integer"); int userNumber = input.nextInt(); //loop will run until it is 1 less than the users number for(int i = 1; i < userNumber; i++){ //loop action: prints i and then a comma to the screen System.out.print(i + ","); } //prints the users number to the screen without a comma System.out.print(userNumber); } }
package com.tencent.mm.plugin.appbrand.jsapi.share; import com.tencent.mm.plugin.appbrand.ipc.AppBrandMainProcessService; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import org.json.JSONObject; public final class JsApiShowUpdatableMessageSubscribeButton extends a { public static final int CTRL_INDEX = 465; public static final String NAME = "showUpdatableMessageSubscribeButton"; public final void a(l lVar, JSONObject jSONObject, int i) { if (jSONObject == null) { x.e("MicroMsg.JsApiShowUpdatableMessageSubscribeButton", "data is null, err"); lVar.E(i, f("fail:invalid data", null)); return; } String optString = jSONObject.optString("shareKey"); if (bi.oW(optString)) { x.e("MicroMsg.JsApiShowUpdatableMessageSubscribeButton", "shareKey is null, err"); lVar.E(i, f("fail:invalid data", null)); return; } ShowUpdatableMessageSubscribeButtonTask showUpdatableMessageSubscribeButtonTask = new ShowUpdatableMessageSubscribeButtonTask(); showUpdatableMessageSubscribeButtonTask.dzR = optString; AppBrandMainProcessService.a(showUpdatableMessageSubscribeButtonTask); lVar.E(i, f("ok", null)); } }
package ru.lischenko_dev.fastmessenger.vkapi.models; public class VkPollAnswer { public long id; public int votes; public String text; public int rate; }
package com.example.konovodov_hw_131; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.HashSet; import java.util.Set; public class ValuesActivity extends AppCompatActivity { Set<UserValues> userValues = new HashSet<UserValues>(); private static final String TAG = "myLogs"; Button buttonValues; Button buttonSave; EditText userWeight; EditText userSteps; //float value = new BigDecimal(str).floatValue(); //ввод значения с плавающей точкой @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_values); init(); buttonValuesClick(); buttonSaveClick(); } public void init() { Log.d(TAG, "найдем View элементы на экране ввода давления...."); buttonValues = (Button) findViewById(R.id.buttonValues); buttonSave = (Button) findViewById(R.id.buttonSave); userWeight = (EditText) findViewById(R.id.editText); userSteps = (EditText) findViewById(R.id.editText2); Log.d(TAG, "элементы View найдены"); } public void buttonValuesClick() { buttonValues.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void buttonSaveClick() { buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int UserStepsValue; float weightUserValue; try { UserStepsValue = Integer.parseInt(userSteps.getText().toString()); weightUserValue = Float.parseFloat(userWeight.getText().toString()); userValues.add(new UserValues(weightUserValue, UserStepsValue)); Toast toast = Toast.makeText(getApplicationContext(), "Вес= " + Float.toString(weightUserValue) + "\n" + "Шаги= " + Integer.toString(UserStepsValue) + "\n" + "Объем коллекции= " + userValues.size(), Toast.LENGTH_SHORT); toast.show(); } catch (NumberFormatException e) { Toast toast = Toast.makeText(getApplicationContext(), "Введите корректные значения", Toast.LENGTH_SHORT); toast.show(); } } }); } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import beans.Book; import dao.BookDao; public class BookUpdate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String author = request.getParameter("author"); float price = Float.parseFloat(request.getParameter("price")); String note = request.getParameter("note"); int num = Integer.parseInt(request.getParameter("num")); //Integer temp = (Integer) request.getSession().getAttribute("temp"); //Integer temp2 = (Integer) request.getSession().getAttribute("temp2"); Book book = new Book(); book.setId(id); book.setName(name); book.setAuthor(author); book.setPrice(price); book.setNote(note); book.setNum(num); BookDao bookdao = new BookDao(); try { bookdao.update(book); request.getRequestDispatcher("successDB.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); request.getRequestDispatcher("errorDB.jsp").forward(request, response); }; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * 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 net.theelm.sewingmachine.deathchests.mixins.Player; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.math.BlockPos; import net.minecraft.world.GameRules; import net.minecraft.world.World; import net.theelm.sewingmachine.base.objects.PlayerBackpack; import net.theelm.sewingmachine.config.SewConfig; import net.theelm.sewingmachine.deathchests.config.SewDeathConfig; import net.theelm.sewingmachine.deathchests.utilities.DeathChestUtils; import net.theelm.sewingmachine.interfaces.BackpackCarrier; import net.theelm.sewingmachine.interfaces.PvpEntity; import net.theelm.sewingmachine.utilities.InventoryUtils; import net.theelm.sewingmachine.utilities.text.MessageUtils; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(value = PlayerEntity.class, priority = 1) public abstract class PlayerEntityMixin extends LivingEntity implements BackpackCarrier, PvpEntity { @Shadow protected abstract void vanishCursedItems(); @Shadow @Final private PlayerInventory inventory; protected PlayerEntityMixin(EntityType<? extends LivingEntity> entityType, World world) { super(entityType, world); } /** * Check if we should spawn a death chest for the player BEFORE vanilla drops any of the players items * @param callback The Mixin Callback */ @Inject(at = @At("HEAD"), method = "dropInventory", cancellable = true) public void onInventoryDrop(CallbackInfo callback) { if (this.isAlive()) return; boolean keepInventory = this.getWorld() .getGameRules() .getBoolean(GameRules.KEEP_INVENTORY); // Only do if we're not keeping the inventory, and the player is actually dead! (Death Chest!) if (!keepInventory) { DeathChestUtils.createDeathSnapshotFor((PlayerEntity)(LivingEntity) this); BlockPos chestPos; PlayerBackpack backpack = this.getBackpack(); // Check if player is in combat if (SewConfig.get(SewDeathConfig.PVP_DISABLE_DEATH_CHEST) && this.inCombat()) { // Drop the backpack as well as the inventory (Only if the player HAS one) if (backpack != null) backpack.dropAll(true); MutableText chestMessage = (this.getPrimeAdversary() instanceof PlayerEntity attacker) ? Text.literal("A death chest was not generated because you were killed by ") .append(MessageUtils.equipmentToText(attacker)) .append(".") : Text.literal("A death chest was not generated because you died while in combat."); // Tell the player that they didn't get a death chest this.sendMessage( chestMessage.formatted(Formatting.RED) ); // Reset the hit by time this.resetCombat(); return; } // If the inventory is NOT empty, and we found a valid position for the death chest if ((!(InventoryUtils.isInvEmpty(this.inventory) && InventoryUtils.isInvEmpty(backpack))) && ((chestPos = DeathChestUtils.getChestPosition(this.getEntityWorld(), this.getBlockPos() )) != null)) { // Vanish cursed items this.vanishCursedItems(); // If a death chest was successfully spawned if (DeathChestUtils.createDeathChestFor((PlayerEntity)(LivingEntity) this, chestPos)) callback.cancel(); } } } }
package cn.timebusker.web; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import cn.timebusker.entity.User; import cn.timebusker.service.UserService; @RestController @RequestMapping("/user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService service; /** * 使用ID查询用户 * * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User findOneUser(@PathVariable long id) { logger.info("传入的参数 ID : " + id); User u = service.findUserById(id); return u; } /** * 查询所有用户 * * @return */ @RequestMapping(value = "/", method = RequestMethod.GET) public List<User> findAllUser() { logger.info("查询所有用户信息"); List<User> list = service.findAllUser(); return list; } /** * 更新或者新增用户信息 * * @param user */ @RequestMapping(value = "/", method = RequestMethod.POST) public User saveAndFlushUser(@ModelAttribute User user) { logger.info("传入的参数 user : " + JSON.toJSONString(user)); service.saveAndFlush(user); return user; } /** * 通过ID删除一个用户 * * @param id */ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public User deleteUser(@PathVariable long id) { User user = service.findUserById(id); logger.info("查询到的user信息是: " + JSON.toJSONString(user)); service.deleteUserById(id); return user; } }
/** * * 项目名称:schedule * 类名称:ScheduleServlet * 类描述: * 创建人:zhoushun * 创建时间:2012-11-27 下午06:45:17 * 修改人:zhoushun * 修改时间:2012-11-27 下午06:45:17 * 修改备注: * @version * */ package com.wonders.schedule.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wonders.schedule.common.util.SimpleLogger; import com.wonders.schedule.main.ScheduleMain; /** * @ClassName: ScheduleServlet * @Description: TODO(计划任务) * @author zhoushun * @date 2012-11-27 下午06:45:17 * */ public class ScheduleServlet extends HttpServlet { SimpleLogger log = new SimpleLogger(this.getClass()); /** * */ private static final long serialVersionUID = -1600327747212116607L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doPost(req, resp); } @Override public void destroy() { // TODO Auto-generated method stub super.destroy(); } /** * @Title: init * @Description: TODO(这里用一句话描述这个方法的作用) * @param @throws ServletException 设定文件 * @throws */ @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); log.debug("计划任务启动"); //ScheduleMain.start(); } }
package com.heartmarket.model.dto.response; import java.util.List; import com.heartmarket.model.dto.Trade; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @AllArgsConstructor @NoArgsConstructor public class MyBuyList { MyBuyListTrade bTrade; int eval; }
/* * Copyright 2013 MovingBlocks * * 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.terasology.questing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.engine.CoreRegistry; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.EventPriority; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.ComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.common.ActivateEvent; import org.terasology.logic.inventory.InventoryComponent; import org.terasology.logic.inventory.ItemComponent; import org.terasology.logic.inventory.events.ReceivedItemEvent; import org.terasology.logic.manager.GUIManager; import org.terasology.questing.gui.UIScreenQuest; import org.terasology.questing.utils.ModIcons; @RegisterSystem public class QuestingCardFetchSystem implements ComponentSystem { private static final Logger logger = LoggerFactory.getLogger(QuestingCardFetchSystem.class); public static String questName = null; private static String goal = null; public static String friendlyGoal = null; private static String amount = null; private static Integer currentAmount = 1; @Override public void initialise() { ModIcons.loadIcons(); } @Override public void shutdown() { // nothing to do } @ReceiveEvent(components = { InventoryComponent.class }, priority = EventPriority.PRIORITY_HIGH) public void onReceiveItem(ReceivedItemEvent event, EntityRef entity) { ItemComponent item = event.getItem().getComponent(ItemComponent.class); // Make sure we have a valid item if (item == null) { logger.warn("Got an invalid item for entity {}", entity); return; } String stackID = item.stackId; // logger.info("Picked up item with id " + stackID); if (goal != null) { if (stackID.equals(goal)) { Integer amounts = Integer.parseInt(amount); if (!currentAmount.equals(amounts)) { currentAmount += 1; logger.info("You have gotten " + currentAmount + " blocks."); } else { resetQuest(); logger.info("Quest finished! Quest goal is now {}", friendlyGoal); UIScreenQuest.qName.setText("Quest finished!"); UIScreenQuest.qGoal.setText(" "); CoreRegistry.get(GUIManager.class).openWindow("journal"); } } } } @ReceiveEvent(components = { QuestingCardFetchComponent.class }) public void onActivate(ActivateEvent event, EntityRef entity) { QuestingCardFetchComponent questingCard = entity.getComponent(QuestingCardFetchComponent.class); questName = questingCard.questName; goal = questingCard.goal; friendlyGoal = questingCard.friendlyGoal; amount = questingCard.amount; logger.info("Quest is now active! The quest is {}", questName); } public static void resetQuest() { questName = null; goal = null; friendlyGoal = null; amount = null; currentAmount = 1; } }
/* ***************************************** * CSCI205 - Software Engineering and Design * Spring 2015 * * Name: Morgan Eckenroth * Date: Mar 18, 2015 * Time: 11:27:02 PM * * Project: csci205 * Package: lab14 * File: KelvinConvertUtility * Description: * Basic utility methods for converting to kelvin * **************************************** */ package lab14; /** * * @author Morgan Eckenroth */ public class KelvinConvertUtility { /** * Converts Fahrenheit temperature to Kelvin * * @param f * @return Kelvin temp */ public static double fahToKev(double f) { return (f + 459.67) * (5.0 / 9.0); } /** * Converts Celsius temperature to Kelvin * * @param c * @return Kelvin temp */ public static double celToKev(double c) { return c + 273.15; } /** * Converts Kelvin temperature to Celsius * * @param k * @return Celsius temp */ public static double kevToCel(double k) { return k - 273.15; } /** * Converts Kelvin temperature to Fahrenheit * * @param k * @return Fahrenheit temp */ public static double kevToFah(double k) { return ((k - 273.15) * 1.8) + 32.0; } /** * Converts Fahrenheit temperature to Celsius * * @param f * @return Celsius temp */ public static double fahToCel(double f) { return (f - 32) * (5.0 / 9.0); } /** * Converts the Celsius temperature to Fahrenheit * * @param c * @return Fahrenheit temp */ public static double celToFah(double c) { return (c * 1.8) + 32.0; } }
package com.google.android.exoplayer2; public final class w$a { public int adO; public Object adz; public Object aeX; public long aeY; public long[] aeZ; public long aet; public int[] afa; public int[] afb; public int[] afc; public long[][] afd; public long afe; public final int iW() { return this.aeZ == null ? 0 : this.aeZ.length; } public final boolean cc(int i) { return this.afa[i] != -1 && this.afc[i] == this.afa[i]; } public final int v(long j) { if (this.aeZ == null) { return -1; } int length = this.aeZ.length - 1; while (length >= 0 && (this.aeZ[length] == Long.MIN_VALUE || this.aeZ[length] > j)) { length--; } if (length < 0 || cc(length)) { return -1; } return length; } public final int w(long j) { if (this.aeZ == null) { return -1; } int i = 0; while (i < this.aeZ.length && this.aeZ[i] != Long.MIN_VALUE && (j >= this.aeZ[i] || cc(i))) { i++; } return i >= this.aeZ.length ? -1 : i; } public final boolean aq(int i, int i2) { return i2 < this.afb[i]; } public final long ar(int i, int i2) { if (i2 >= this.afd[i].length) { return -9223372036854775807L; } return this.afd[i][i2]; } }
package com.jobinesh.example.grpc.server; import io.grpc.stub.StreamObserver; public class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase { @Override public void sayHello(HelloWorldServiceOuterClass.HelloWorldRequest request, StreamObserver<HelloWorldServiceOuterClass.HelloWorldResponse> responseObserver) { // HelloRequest has toString auto-generated. System.out.println(request); // You must use a builder to construct a new Protobuffer object HelloWorldServiceOuterClass.HelloWorldResponse response = HelloWorldServiceOuterClass.HelloWorldResponse.newBuilder() .setGreeting("Hello there, " + request.getName()) .build(); // Use responseObserver to send a single response back responseObserver.onNext(response); // When you are done, you must call onCompleted. responseObserver.onCompleted(); } }
package sample; public class ChatServerModel { private String portNumber; public String getPortNumber() { return portNumber; } public void setPortNumber(String portNumber) { this.portNumber = portNumber; } public ChatServerModel(){ } }
package org.firstinspires.ftc.tekerz; /** * Created by FTC11109 on 11/16/2016. */ public class Constants { // constants for servos EDIT THESE WHEN TESTING THE SYSTEM!! public static final double DIRECT_PARTICLE_BASE = 0.0; public static final double DIRECT_PARTICLE_MIN = 0.0; public static final double DIRECT_PARTICLE_MAX = 0.75; public static final double LEFT_ROLLER_BASE = 0.5; public static final double LEFT_ROLLER_OPEN = 1.0; // LET THESE CALC FOR THEMSELVES public static final double RIGHT_ROLLER_BASE = 1.0 - LEFT_ROLLER_BASE; public static final double RIGHT_ROLLER_OPEN = 1.0 - LEFT_ROLLER_BASE; public static final double ROLLER_SPEED = 0.5; public static final double DIRECT_PARTICLE_SPEED = 0.005; public static final double SHOOTER_POWER = 1.0; public static final double COLLECTOR_POWER = 0.7; public static final double SHOOTER_CLIP_POWER = 0.40; public static final double SHOOTER_CLIP_LAUNCH = 1.0; }
package com.tencent.mm.plugin.wallet.pay.ui; import com.tencent.mm.plugin.wallet_core.c.w; import com.tencent.mm.plugin.wallet_core.ui.n.b; class WalletPayCustomUI$1 implements b { final /* synthetic */ WalletPayCustomUI pfT; WalletPayCustomUI$1(WalletPayCustomUI walletPayCustomUI) { this.pfT = walletPayCustomUI; } public final void c(String str, boolean z, String str2) { int i; int i2 = WalletPayCustomUI.a(this.pfT).sqz; String str3 = WalletPayCustomUI.a(this.pfT).sqy; String str4 = WalletPayCustomUI.a(this.pfT).sign; String str5 = WalletPayCustomUI.a(this.pfT).hFk; String str6 = WalletPayCustomUI.a(this.pfT).rFf; if (z) { i = 1; } else { i = 0; } this.pfT.a(new w(str, i2, str3, str4, str5, str6, i, str2, ""), true, false); } }
// // FingerDot // // Created by Eduardo Almeida and Joao Almeida // LPOO 13/14 // package pt.up.fe.lpoo.fingerdot.test; import org.junit.*; import pt.up.fe.lpoo.fingerdot.logic.singleplayer.LeaderboardEntry; import pt.up.fe.lpoo.fingerdot.logic.singleplayer.LeaderboardManager; import static org.junit.Assert.*; public class LeaderboardTests { LeaderboardManager _manager = LeaderboardManager.sharedManager(); @Before public void setUp() throws Exception { } /** * Tests whether the game can read the internet leaderboards. */ @Test public void readInternetHighScores() { assertTrue(_manager.retrieveOnlineLeaderboard()); } /** * Tests whether the game can add a score to the internet leaderboards. */ @Test public void addInternetHighScore() { assertTrue(_manager.publishScoreOnOnlineLeaderboard(new LeaderboardEntry("Test Suite", "0", "test-suite", 1))); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.webdav.resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bradmcevoy.common.Path; import com.bradmcevoy.http.Resource; import com.bradmcevoy.http.ResourceFactory; import com.openkm.core.AccessDeniedException; import com.openkm.core.Config; import com.openkm.core.DatabaseException; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; /** * You should generally avoid using any request information other then that * provided in the method arguments. But if you find you need to you can access * the request and response objects from HttpManager.request() and * HttpManager.response() * * @author pavila */ public class ResourceFactoryImpl implements ResourceFactory { private static final Logger log = LoggerFactory.getLogger(ResourceFactoryImpl.class); public static final String REALM = "OpenKM"; @Override public Resource getResource(String host, String url) { log.debug("getResource({}, {})", host, url); Path srcPath = Path.path(url); Path path = null; if (url.startsWith("/" + Config.CONTEXT + "/webdav")) { // STRIP PRECEEDING PATH path = srcPath.getStripFirst().getStripFirst(); } else { path = Path.path(url); } try { if (path.isRoot()) { log.debug("ROOT"); return new RootResource(srcPath); } else { return ResourceUtils.getNode(srcPath, path.toPath()); } } catch (PathNotFoundException e) { log.error("PathNotFoundException: " + e.getMessage()); } catch (AccessDeniedException e) { log.error("AccessDeniedException: " + e.getMessage()); } catch (RepositoryException e) { log.error("RepositoryException: " + e.getMessage()); } catch (DatabaseException e) { log.error("DatabaseException: " + e.getMessage()); } return null; } }
package com.lnunno.musicapp.adapters; import android.content.Context; import android.widget.ArrayAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Keeps track of items in itself. * <p/> * Use getContext from ArrayAdapter to get the Context. * <p/> * Created by Lucas on 3/17/2015. */ public class TrackerAdapter<T> extends ArrayAdapter<T> { private Context context; private List<T> list = new ArrayList<>(); public TrackerAdapter(Context context, int resource) { super(context, resource); } public TrackerAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public TrackerAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId); this.list = objects; } public TrackerAdapter(Context context, int resource, List<T> objects) { super(context, resource, objects); this.list = objects; } @Override public void addAll(Collection<? extends T> collection) { super.addAll(collection); list.addAll(collection); } @Override public void clear() { super.clear(); list.clear(); } public List<T> getData() { return list; } }
package com.tencent.mm.plugin.setting.ui.setting; import android.graphics.Bitmap; import com.tencent.mm.aa.g.b; import com.tencent.mm.aa.q; import com.tencent.mm.sdk.platformtools.x; class PreviewHdHeadImg$3 implements b { final /* synthetic */ PreviewHdHeadImg mQr; final /* synthetic */ Bitmap mQt; PreviewHdHeadImg$3(PreviewHdHeadImg previewHdHeadImg, Bitmap bitmap) { this.mQr = previewHdHeadImg; this.mQt = bitmap; } public final int bd(int i, int i2) { PreviewHdHeadImg.c(this.mQr).Ku(); x.i("MicroMsg.PreviewHdHeadImg", "onSceneEnd: errType=%d, errCode=%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); if (i == 0 && i2 == 0) { Bitmap jU = q.Kp().jU(PreviewHdHeadImg.a(this.mQr)); if (jU != null) { PreviewHdHeadImg.a(this.mQr, jU, q.Kp().c(PreviewHdHeadImg.a(this.mQr), true, false)); } else { PreviewHdHeadImg.a(this.mQr, this.mQt, null); } } else { PreviewHdHeadImg.a(this.mQr, this.mQt, null); } return 0; } }
package cs455.deleter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class DeleteMapper extends Mapper<LongWritable, Text, Text, Text> { private static String sentence; private static HashMap<String, LinkedList<String>> sentenceBigrams; private IntWritable count; private Text second; private Text first; public static void setSentence(String input) { sentenceBigrams = new HashMap<String, LinkedList<String>>(); sentence = input; String[] split = input.split(" "); for (int i = 0; i < split.length - 1; i++) { String first = split[i]; String second = split[i + 1]; if (!sentenceBigrams.containsKey(second)) { sentenceBigrams.put(second, new LinkedList<String>()); } sentenceBigrams.get(second).add(first); } } @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // second = key; String[] line = value.toString().split("\t"); second = new Text(line[0]); line = line[1].split(";"); for (String s : line) { String[] bigram = s.split(","); first = new Text(bigram[0]); Float prob = Float.parseFloat(bigram[1]); if (sentenceBigrams.containsKey(second.toString())) { if (sentenceBigrams.get(second.toString()).contains(first.toString())) { context.write(new Text(sentence), new Text(first.toString() + " " + second.toString() + " " + prob)); } } } } }
package com.project.linkedindatabase.domain.Type; import com.project.linkedindatabase.domain.BaseEntity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public abstract class BaseType extends BaseEntity { private String name;// name or description or id code or ... }
package theekransje.douaneapp.API; import android.os.AsyncTask; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.io.Console; import java.net.HttpURLConnection; import java.util.ArrayList; import theekransje.douaneapp.Domain.DouaneStatus; import theekransje.douaneapp.Domain.Freight; import theekransje.douaneapp.Domain.MRNFormulier; import theekransje.douaneapp.Interfaces.OnStatusDetailAvail; /** * Created by Sander on 5/24/2018. */ ///////Gedetaileerde status ophalen public class AsyncGetStatusDetail extends AsyncTask { private static final String TAG = "AsyncGetStatusDetail"; private final String endPoint = "customs/form/"; private String mrn; private OnStatusDetailAvail listener; public AsyncGetStatusDetail(String mrn, OnStatusDetailAvail listener) { this.mrn = mrn; this.listener = listener; } @Override protected Object doInBackground(Object[] objects) { try { Log.d(TAG, "doInBackground: called"); ApiHelper apiHelper = new ApiHelper(endPoint + mrn , APIMethodes.GET); HttpURLConnection conn = apiHelper.getConnection(); int statusCode = conn.getResponseCode(); Log.d(TAG, "doInBackground: statuscode: " + statusCode); if (statusCode == 200) { Log.d(TAG, "doInBackground: "); JSONObject reply = new JSONObject(ApiHelper.convertIStoString(conn.getInputStream())); JSONObject jsonObject = reply.getJSONObject("message"); MRNFormulier mrnFormulier = new MRNFormulier(); mrnFormulier.setMrn(mrn); mrnFormulier.setAantalArtikelen(jsonObject.getInt("articleAmount")); mrnFormulier.setAfzender(jsonObject.getString("sender")); mrnFormulier.setOntvanger(jsonObject.getString("receiver")); mrnFormulier.setCurrency(jsonObject.getString("currency")); mrnFormulier.setTotaalGewicht(jsonObject.getDouble("totalWeight")); mrnFormulier.setTotaalBedrag(jsonObject.getDouble("totalAmount")); mrnFormulier.setOpdrachtgever(jsonObject.getString("client")); mrnFormulier.setReference(jsonObject.getString("reference")); mrnFormulier.DateTime = jsonObject.getString("dateTime"); mrnFormulier.setVerzenderAdres(jsonObject.getString("addressOrigin")); mrnFormulier.setOntvangstAdres(jsonObject.getString("addressDestination")); Freight freight = new Freight(); freight.setMRNFormulier(mrnFormulier); freight.setDouaneStatus(StatusDecoder.decodeStatusCode(jsonObject.getInt("declarationStatus"))); Log.d(TAG, "doInBackground: MRN form received " + mrn); listener.OnStatusDetailAvail(freight); } else if (statusCode == 401) { Log.d(TAG, "doInBackground: Login failed"); } else { Log.d(TAG, "doInBackground: " + "Undefined error"); } conn.disconnect(); conn = null; } catch (Exception e) { e.printStackTrace(); } return null; } }
package id.ac.ub.ptiik.papps.parsers; import java.util.ArrayList; import id.ac.ub.ptiik.papps.base.Karyawan; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class KaryawanListParser { public static ArrayList<Karyawan> Parse(String JSONString){ try { JSONObject object = new JSONObject(JSONString); ArrayList<Karyawan> karyawanList = new ArrayList<Karyawan>(); JSONArray karyawanArray = object.getJSONArray("karyawan"); for(int i=0; i<karyawanArray.length(); i++) { JSONObject karyawan = (JSONObject) karyawanArray.get(i); String id = karyawan.getString("karyawan_id"); String nama = karyawan.getString("nama"); String gelar_awal = karyawan.getString("gelar_awal"); String gelar_akhir = karyawan.getString("gelar_akhir"); Karyawan u = new Karyawan(id, nama, gelar_awal, gelar_akhir); karyawanList.add(u); } return karyawanList; } catch (JSONException e) { e.printStackTrace(); } return null; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mertbilgic.yazlab2; /** * * @author mertbilgic */ //https://stackoverflow.com/questions/2832472/how-to-return-2-values-from-a-java-method class Result { private int step; private String message; private int[][] graph; public Result(int step, int[][] graph) { this.step = step; this.graph = graph; } public Result(String message, int[][] graph) { this.message = message; this.graph = graph; } public int getStep() { return step; } public int[][] getGraph() { return graph; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package com.rockwellcollins.atc.limp.reasoning.visitor; import com.rockwellcollins.atc.limp.StringLiteralExpr; public class StringHack extends LimpVisitor { @Override public Unit caseStringLiteralExpr(StringLiteralExpr x) { System.out.println("** Hacking string " + x.getStringVal()); x.setStringVal(x.getStringVal() + "_hacked"); return Unit.UNIT; } }
package banyuan.day13.package01; /** * @author 陈浩 * @date Created on 2019/11/7 * 1. 四个线程 其中A,B线程对每次对i增加1 C.D线程每次对i减1 */ public class Tools { int a = 1; int b = 1; }
package com.wonders.task.asset.model.bo; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "DW_ASSET_CODE_INFO") public class DwAssetCodeInfo implements Serializable{ /** * */ private static final long serialVersionUID = 8334825036189361329L; private Date addTime; // addTime private String dm; // dm private String id; // id private String name; // name private Long removed; // removed private Long typeId; // typeId private Date updateTime; // updateTime private Long value; // value public void setAddTime(Date addTime) { this.addTime = addTime; } @Column(name = "ADD_TIME", nullable = true, length = 7) public Date getAddTime() { return addTime; } public void setDm(String dm) { this.dm = dm; } @Column(name = "DM", nullable = true, length = 199) public String getDm() { return dm; } public void setId(String id) { this.id = id; } @Id @GeneratedValue(generator="system.uuid") @GenericGenerator(name="system.uuid",strategy="uuid") @Column(name = "ID", nullable = false, length = 50) public String getId() { return id; } public void setName(String name) { this.name = name; } @Column(name = "NAME", nullable = true, length = 199) public String getName() { return name; } public void setRemoved(Long removed) { this.removed = removed; } @Column(name = "REMOVED", nullable = true, length = 22) public Long getRemoved() { return removed; } public void setTypeId(Long typeId) { this.typeId = typeId; } @Column(name = "TYPE_ID", nullable = true, length = 22) public Long getTypeId() { return typeId; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Column(name = "UPDATE_TIME", nullable = true, length = 7) public Date getUpdateTime() { return updateTime; } public void setValue(Long value) { this.value = value; } @Column(name = "VALUE", nullable = true, length = 22) public Long getValue() { return value; } }
package interviews.google; import common.TreeNode; public class LongestIncreasingSubsequence { public int function(TreeNode node) { return dfs(node); } public int dfs(TreeNode node) { if (node == null) return 0; if (node.left == null && node.right == null) return 1; int left = 0, right = 0; if (node.left != null) left = dfs(node.left) + (node.left.val - node.val == 1 ? 1 : 0); if (node.right != null) right = dfs(node.right) + (node.right.val - node.val == 1 ? 1 : 0); return Math.max(left, right); } }
package com.example.postgresdemo.repositoryIntegrationtest; import com.example.postgresdemo.model.Employee; import com.example.postgresdemo.repository.EmployeeRepository; import com.example.postgresdemo.repository.SurveyRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jdbc.EmbeddedDatabaseConnection; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @DataJpaTest @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) public class SurveyRepositoryIntegrationTest { @Autowired private TestEntityManager entityManager; @Autowired private SurveyRepository surveyRepository; @Test public void employeeAssignment() { } @Test public void addToolRatingToSurvey(){ } @Test public void updateToolRating(){ } @Test public void deleteToolRating(){ } @Test public void addSecondToolRating(){ } @Test public void deleteSurvey(){ } }
package ars.ramsey.interviewhelper.model.bean; import android.os.Parcel; import android.os.Parcelable; /** * Created by Ramsey on 2017/5/9. */ public class Author implements Parcelable { private String bio; private String hash; private String description; private String profileUrl; private Avatar avatar; private String slug; private String name; protected Author(Parcel in) { this.bio = in.readString(); this.hash = in.readString(); this.description = in.readString(); this.profileUrl = in.readString(); this.avatar = in.readParcelable(Avatar.class.getClassLoader()); this.slug = in.readString(); this.name = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.bio); dest.writeString(this.hash); dest.writeString(this.description); dest.writeString(this.profileUrl); dest.writeParcelable(this.avatar, flags); dest.writeString(this.slug); dest.writeString(this.name); } @Override public int describeContents() { return 0; } public static final Creator<Author> CREATOR = new Creator<Author>() { @Override public Author createFromParcel(Parcel in) { return new Author(in); } @Override public Author[] newArray(int size) { return new Author[size]; } }; public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getProfileUrl() { return profileUrl; } public void setProfileUrl(String profileUrl) { this.profileUrl = profileUrl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package be_a_good_visitor; public class Main { public static void main(String[] args) { ShapeD s = new Trans( new CartesianPt(3, 7), new Union( new Square(10), new Circle(10))); boolean x = s.accept(new UnionHasPtV(new CartesianPt(13, 17))); System.out.println(x); } }
package it.hw.catapushdemo; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.graphics.Color; import android.media.RingtoneManager; import android.os.Build; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.multidex.MultiDexApplication; import com.catapush.library.Catapush; import com.catapush.library.hms.CatapushHms; import com.catapush.library.interfaces.Callback; import com.catapush.library.notifications.NotificationTemplate; import java.io.IOException; import java.util.Collections; import io.reactivex.exceptions.UndeliverableException; import io.reactivex.plugins.RxJavaPlugins; public class CataPushDemo extends MultiDexApplication { private void setupRxErrorHandler() { RxJavaPlugins.setErrorHandler(e -> { if (e instanceof UndeliverableException) { // The exception was wrapped e = e.getCause(); } if (e instanceof IOException) { // Fine, irrelevant network problem or API that throws on cancellation return; } if (e instanceof InterruptedException) { // Fine, some blocking code was interrupted by a dispose call return; } if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) { // That's likely a bug in the application Thread.currentThread().getUncaughtExceptionHandler() .uncaughtException(Thread.currentThread(), e); return; } if (e instanceof IllegalStateException) { // That's a bug in RxJava or in a custom operator Thread.currentThread().getUncaughtExceptionHandler() .uncaughtException(Thread.currentThread(), e); return; } // Log this to your analytics platform Log.e(Catapush.class.getCanonicalName(), e.getMessage()); }); } @Override public void onCreate() { super.onCreate(); String NOTIFICATION_CHANNEL_ID = getResources().getString(R.string.catapush_notification_channel_id); setupRxErrorHandler(); // Required: see section 'RxJava catch-all error handler' for the implementation // This is the Android system notification channel that will be used by the Catapush SDK // to notify the incoming messages since Android 8.0. It is important that the channel // is created before starting Catapush. // See https://developer.android.com/training/notify-user/channels NotificationManager nm = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)); if (nm != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelName = getString(R.string.catapush_notification_channel_name); NotificationChannel channel = nm.getNotificationChannel(NOTIFICATION_CHANNEL_ID); if (channel == null) { channel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH); // Customize your notification appearance here (Android >= 8.0) // it's possible to customize a channel only on creation channel.enableVibration(true); channel.setVibrationPattern(new long[]{100, 200, 100, 300}); channel.enableLights(true); channel.setLightColor(ContextCompat.getColor(this, R.color.primary)); } else if (!channelName.contentEquals(channel.getName())) { // Update channel name, useful when the user changes the system language channel.setName(channelName); } nm.createNotificationChannel(channel); } Catapush.getInstance().init( this, NOTIFICATION_CHANNEL_ID, Collections.singletonList(CatapushHms.INSTANCE),//修改處 new Callback() { @Override public void failure(@NonNull Throwable t) { Log.d("MyApp", "Catapush initialization error: " + t.getMessage()); } @Override public void success(Object response) { Log.d("MyApp", "Catapush has been successfully initialized"); // This is the notification template that the Catapush SDK uses to build // the status bar notification shown to the user. // Some settings like vibration, lights, etc. are duplicated here because // before Android introduced notification channels (Android < 8.0) the // styling was made on a per-notification basis. final NotificationTemplate template = NotificationTemplate.builder() .swipeToDismissEnabled(false) .title("Your notification title!") .iconId(R.drawable.ic_stat_notify_default) .vibrationEnabled(true) .vibrationPattern(new long[]{100, 200, 100, 300}) .soundEnabled(true) .soundResourceUri(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)) .circleColor(ContextCompat.getColor(CataPushDemo.this, R.color.primary)) .ledEnabled(true) .ledColor(Color.BLUE) .ledOnMS(2000) .ledOffMS(1000) .build(); Catapush.getInstance().setNotificationTemplate(template); } } ); } }
package com.telyo.trainassistant.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.telyo.trainassistant.R; import com.telyo.trainassistant.entity.Passengers; import java.util.List; /** * Created by Administrator onCutImgClickListener 2017/6/15. */ public class RecyclerPassengersViewAdapter extends RecyclerView.Adapter<RecyclerPassengersViewAdapter.MyViewHolder> { private Context context; private List<Passengers> passengerses; private LayoutInflater inflater; private OnCutImgClickListener onCutImgClickListener; public void setOnCutImgClickListener(OnCutImgClickListener onCutImgClickListener) { this.onCutImgClickListener = onCutImgClickListener; } public RecyclerPassengersViewAdapter(Context context, List<Passengers> passengerses){ this.passengerses = passengerses; this.context = context; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.recycler_passenger_item,parent,false); MyViewHolder myViewHolder= new MyViewHolder(view); return myViewHolder; } @Override public void onBindViewHolder(final MyViewHolder holder, int position) { holder.name.setText(passengerses.get(position).getName()); holder.idCard.setText(passengerses.get(position).getAdCard()); holder.itemView.setBackgroundResource(R.drawable.recycler_item_click); if (onCutImgClickListener != null){ holder.img_cut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = holder.getLayoutPosition(); onCutImgClickListener.OnItemClick(holder.itemView,position); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { return false; } }); } } @Override public int getItemCount() { return passengerses.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ public TextView name; public TextView idCard; public ImageView img_cut; public MyViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.tv_name); idCard = (TextView) itemView.findViewById(R.id.tv_id_card); img_cut = (ImageView) itemView.findViewById(R.id.img_cut_down); } } public interface OnCutImgClickListener { void OnItemClick(View v, int position); } }
package AnnotationDemo; import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; /** * @Repeatable allows repeat annotation in one place. The method must contain * massive with field 'value'. * * Annotations have few limitations. (1) one annotation cannot inherit another * one; (2) all methods which are declared in annotation must not have * parameters; (3) they should return anything, such as (String, int...), except * Generic types * * @author Bohdan Skrypnyk */ @Retention(RetentionPolicy.RUNTIME) @Repeatable(MyRepeatableAnno.class) // make annotation @MyAnno2 repeatable @interface MyAnno2 { String str(); int num() default 15; } // all repeating annotations are stored in 'container annotations', such as below @Retention(RetentionPolicy.RUNTIME) @interface MyRepeatableAnno { MyAnno2[] value(); } public class RepeatAnno { // repeat annotations '@MyAnno2' in 'myMeth' method @MyAnno2(str = "First annotation", num = 25) @MyAnno2(str = "Second annotation") @MyAnno2(str = "Third annotation", num = -1) public static void myMeth(int i) { RepeatAnno obj = new RepeatAnno(); try { // get object Class, then get method Method meth = obj.getClass().getMethod("myMeth", int.class); // get annotations from the 'myMeth' method Annotation annn = meth.getAnnotation(MyRepeatableAnno.class); // display annotations // all repeated annotations returned as a single line, but they divided by coma System.out.println(annn); // another way to get all repeated annotations from '@MyAnno2' Annotation annn1[] = meth.getAnnotationsByType(MyAnno2.class); for (Annotation ann : annn1) { System.out.println(ann); } } catch (NoSuchMethodException ex) { System.out.println("No Such Method "); } } public static void main(String args[]) { myMeth(25); } }
package com.example.luigitercero.appcolonia; public class LoginToken { private static LoginToken instance; private static String correo; private static String idCodigo; private LoginToken(){} public void setCorreo(String correo) { LoginToken.correo = correo; } public void setIdCodigo(String codigo) {LoginToken.idCodigo = codigo;} public String getCorreo() { return LoginToken.correo; } public String getIdCodigo() {return LoginToken.idCodigo;} public static synchronized LoginToken getInstance(){ if(instance == null){ instance = new LoginToken(); }else { return instance; } return instance; } }
import java.util.Scanner; public class GameDriver { private Scanner input; private Object random; public static void main(String[] args) { GameDriver game = new GameDriver(); Player player1 = new Player(); Player player2 = new Player(); Armor arm = new Armor(); Player p1 = game.getPlayerInfo(); System.out.println(p1); game.getArmorInfo(p1); Player p2 = game.getPlayerInfo(); System.out.println(p2); game.getArmorInfo(p2); if(p1.getHitPoints() > 0){ int damage = 1 + ((Scanner) game.random).nextInt(100); System.out.println(p1.takeDamage(damage)); } if(p2.getHitPoints() > 0){ int damage = 1 + ((Scanner) game.random).nextInt(100); System.out.println(p1.takeDamage(damage)); } } public Player getPlayerInfo(){ Scanner input = new Scanner(System.in); Player player = new Player(); System.out.println("Please enter the character's name: "); player.setName(input.nextLine()); System.out.println("Please enter the class for " + player.getName() + ": "); player.setCharClass(input.nextLine()); System.out.println("Please enter the hit points for " + player.getName() + ": "); player.setHitPoints(input.nextInt()); return player; } public static void getArmorInfo(Player player){ Scanner input = new Scanner(System.in); System.out.print("Please enter the type for the armor: "); String arm = input.nextLine(); System.out.println("Please enter the armor class for " + arm + ": "); int ac = input.nextInt(); System.out.println("Please enter the durability for " + arm + ": "); int durability = input.nextInt(); char sa; do{ System.out.println("Do you want to enter a special property for " + arm + " (Y/N): "); sa = input.next().charAt(0); if(sa == 'y' || sa == 'Y'){ System.out.println("Please enter the special property for " + arm + ": "); player.arm.addSpecialProperties(input.nextLine()); } else{ break; } }while(sa == 'y' || sa == 'Y'); } }//end of class
package com.yang.stethodemo; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { //页码 private int pageNo = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(v -> sendRequest()); Button btn2 = findViewById(R.id.btn2); btn2.setOnClickListener(v -> modifySharedPreferences()); } private void sendRequest() { OkHttpClient okHttpClient = OkHttpContext.getInstance().getOkHttpClient(); Request request = new Request.Builder() .get() //玩Android 首页文章列表接口 .url("https://www.wanandroid.com/article/list/" + (pageNo++) + "/json") .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { } }); } private void modifySharedPreferences() { SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); //当前时间 String time = format.format(new Date()); SharedPreferencesUtils.putString(this, "time", time); Toast.makeText(this, "当前时间:" + time, Toast.LENGTH_SHORT).show(); } }
package graphic.Gui.Items; import Domain.Risorsa; import graphic.Gui.ControllerCallback; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import lorenzo.Applicazione; import java.io.IOException; import static java.io.File.separator; /** * Created by pietro on 07/06/17. */ public class PrivilegioConsiglioController { private static final Risorsa[] RISORSEPRIVILEGIO = {/*0*/ new Risorsa(1,1,0,0,0,0,0), /*1*/ new Risorsa(Risorsa.TipoRisorsa.SERVI, 2), /*2*/ new Risorsa(Risorsa.TipoRisorsa.MONETE, 2), /*3*/ new Risorsa(Risorsa.TipoRisorsa.PMILITARI, 2), /*4*/ new Risorsa(Risorsa.TipoRisorsa.PFEDE, 1)}; private Rectangle[] aree; private int numPergamene; private Pane pannelloPadre; private AnchorPane pannelloPrivilegio; private ControllerCallback callback; public PrivilegioConsiglioController(int numPergamene, Pane pannelloPadre, ControllerCallback callback, Applicazione loader) throws IOException { this.numPergamene=numPergamene; this.pannelloPadre=pannelloPadre; this.callback=callback; Parent parent= loader.getFXML("privilegio_consiglio.fxml"); //Recupero elementi Label numeroPergmaneLabel = (Label) parent.lookup("#nPrivilegi"); pannelloPrivilegio = (AnchorPane) parent.lookup("#pannelloPrivilegio"); ImageView sfondo = (ImageView) parent.lookup("#imageView"); aree = new Rectangle[5]; aree[0] = (Rectangle) parent.lookup("#sceltaA"); aree[1] = (Rectangle) parent.lookup("#sceltaB"); aree[2] = (Rectangle) parent.lookup("#sceltaC"); aree[3] = (Rectangle) parent.lookup("#sceltaD"); aree[4] = (Rectangle) parent.lookup("#sceltaE"); //Setta il numro di pergamene a video e lo sfondo numeroPergmaneLabel.setText("Seleziona "+numPergamene+" pergamene"); sfondo.setImage(new Image("file:"+System.getProperty("user.dir")+separator+"ClientApplication"+separator+"Risorse"+separator+"privilegioConsiglio.png")); //SetOnCLick rettangoli for (int i = 0; i < aree.length; i++) { Rectangle area = aree[i]; int finalI = i; area.setOnMouseClicked(mouseEvent -> toggleScelta(finalI)); } //Aggiungi al pannelloPadre nella posizione appropriata pannelloPrivilegio.setLayoutX((pannelloPadre.getWidth()-sfondo.getFitWidth())/2); pannelloPrivilegio.setLayoutY((pannelloPadre.getHeight()-sfondo.getFitHeight())/2); pannelloPadre.getChildren().add(pannelloPrivilegio); pannelloPrivilegio.toFront(); } private void toggleScelta(int i){ //se attivo, disattivo if (aree[i].getStroke()==Color.BLUE) aree[i].setStroke(Color.TRANSPARENT); //se disattivo, lo attivo else{ aree[i].setStroke(Color.BLUE); //Conto le scelte selezionate int opzioniSelezionate=0; for(Rectangle r : aree){ if (r.getStroke()==Color.BLUE) opzioniSelezionate=opzioniSelezionate+1; } //se ho raggiunto il numero di pergamene richieste notifico il server if (opzioniSelezionate == numPergamene){ Risorsa risorseSelezionate = new Risorsa(); for (int j = 0; j < aree.length; j++) { if (aree[j].getStroke()==Color.BLUE) risorseSelezionate.add(RISORSEPRIVILEGIO[j]); } callback.riscossionePrivilegio(risorseSelezionate); pannelloPadre.getChildren().remove(pannelloPrivilegio); } } } }
package controlador; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; public class LimpiarFormularioSolicitud implements TaskListener{ public void notify(DelegateTask delegateTask) { DelegateExecution e =delegateTask.getExecution(); e.setVariable("ci", null); e.setVariable("nombre", null); e.setVariable("apellido", null); e.setVariable("mail_solicitante", null); e.setVariable("informacion_familiar", null); e.setVariable("ingresos", null); e.setVariable("nivel_educativo", null); e.setVariable("integrantes_familia", null); e.setVariable("otros_ingresos", null); e.setVariable("", false); } }
package three; import java.util.Random; public class MathOps { public static void main(String[]args){ Random random=new Random(); } }
package com.tencent.mm.plugin.product.ui; import com.tencent.mm.plugin.product.ui.f.a; class MallProductSubmitUI$1 implements a { final /* synthetic */ MallProductSubmitUI lTQ; MallProductSubmitUI$1(MallProductSubmitUI mallProductSubmitUI) { this.lTQ = mallProductSubmitUI; } public final void m(int i, int i2, String str) { if (i == 0 && i2 == 0) { MallProductSubmitUI.a(this.lTQ); } else { this.lTQ.JB(str); } } }
package org.sankozi.rogueland.gui.actions; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.KeyStroke; import org.sankozi.rogueland.gui.ComponentSwitcher; /** * * @author sankozi */ @Singleton public class ShowInventoryAction extends AbstractAction{ private final ComponentSwitcher switcher; private final JComponent inventoryPanel; { this.putValue(Action.NAME, "Inventory"); this.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke('i')); this.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_I); } @Inject ShowInventoryAction( ComponentSwitcher switcher, @Named("inventory-panel") JComponent inventoryPanel){ this.switcher = switcher; this.inventoryPanel = inventoryPanel; } @Override public void actionPerformed(ActionEvent e) { switcher.setComponent(inventoryPanel); } }
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class Finish_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html lang=\"en\">\n"); out.write("\n"); out.write(" <head>\n"); out.write(" <meta charset=\"utf-8\">\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"); out.write(" <title>Success</title>\n"); out.write(" <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Roboto|Varela+Round\">\n"); out.write(" <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\">\n"); out.write(" <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n"); out.write(" <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\">\n"); out.write(" <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"></script>\n"); out.write(" <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\"></script>\n"); out.write(" <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"></script>\n"); out.write(" <style>\n"); out.write(" body {\n"); out.write(" font-family: 'Varela Round', sans-serif;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm {\n"); out.write(" color: #434e65;\n"); out.write(" width: 525px;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .modal-content {\n"); out.write(" padding: 20px;\n"); out.write(" font-size: 16px;\n"); out.write(" border-radius: 5px;\n"); out.write(" border: none;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .modal-header {\n"); out.write(" background: #47c9a2;\n"); out.write(" border-bottom: none;\n"); out.write(" position: relative;\n"); out.write(" text-align: center;\n"); out.write(" margin: -20px -20px 0;\n"); out.write(" border-radius: 5px 5px 0 0;\n"); out.write(" padding: 35px;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm h4 {\n"); out.write(" text-align: center;\n"); out.write(" font-size: 36px;\n"); out.write(" margin: 10px 0;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .form-control,\n"); out.write(" .modal-confirm .btn {\n"); out.write(" min-height: 40px;\n"); out.write(" border-radius: 3px;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .close {\n"); out.write(" position: absolute;\n"); out.write(" top: 15px;\n"); out.write(" right: 15px;\n"); out.write(" color: #fff;\n"); out.write(" text-shadow: none;\n"); out.write(" opacity: 0.5;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .close:hover {\n"); out.write(" opacity: 0.8;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .icon-box {\n"); out.write(" color: #fff;\n"); out.write(" width: 95px;\n"); out.write(" height: 95px;\n"); out.write(" display: inline-block;\n"); out.write(" border-radius: 50%;\n"); out.write(" z-index: 9;\n"); out.write(" border: 5px solid #fff;\n"); out.write(" padding: 15px;\n"); out.write(" text-align: center;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .icon-box i {\n"); out.write(" font-size: 64px;\n"); out.write(" margin: -4px 0 0 -4px;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm.modal-dialog {\n"); out.write(" margin-top: 80px;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .btn,\n"); out.write(" .modal-confirm .btn:active {\n"); out.write(" color: #fff;\n"); out.write(" border-radius: 4px;\n"); out.write(" background: #eeb711 !important;\n"); out.write(" text-decoration: none;\n"); out.write(" transition: all 0.4s;\n"); out.write(" line-height: normal;\n"); out.write(" border-radius: 30px;\n"); out.write(" margin-top: 10px;\n"); out.write(" padding: 6px 20px;\n"); out.write(" border: none;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .btn:hover,\n"); out.write(" .modal-confirm .btn:focus {\n"); out.write(" background: #eda645 !important;\n"); out.write(" outline: none;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .btn span {\n"); out.write(" margin: 1px 3px 0;\n"); out.write(" float: left;\n"); out.write(" }\n"); out.write("\n"); out.write(" .modal-confirm .btn i {\n"); out.write(" margin-left: 1px;\n"); out.write(" font-size: 20px;\n"); out.write(" float: right;\n"); out.write(" }\n"); out.write("\n"); out.write(" .trigger-btn {\n"); out.write(" display: inline-block;\n"); out.write(" margin: 100px auto;\n"); out.write(" }\n"); out.write(" </style>\n"); out.write(" </head>\n"); out.write("\n"); out.write(" <body>\n"); out.write(" <div class=\"modal-dialog modal-confirm\">\n"); out.write(" <div class=\"modal-content\">\n"); out.write(" <div class=\"modal-header justify-content-center\">\n"); out.write(" <div class=\"icon-box\">\n"); out.write(" <i class=\"material-icons\">&#xE876;</i>\n"); out.write(" </div>\n"); out.write(" <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">&times;</button>\n"); out.write(" </div>\n"); out.write(" <div class=\"modal-body text-center\" style=\"background-color: blanchedalmond;\">\n"); out.write(" <h4>Success!</h4>\n"); out.write(" <p>You have finished your purchase successfully</p>\n"); out.write(" <p>Check your email for details.</p>\n"); out.write(" <button onclick=\"window.location.href=google.com\" class=\"btn btn-success\" data-dismiss=\"modal\"><span>Continue Purchase</span> <i\n"); out.write(" class=\"material-icons\">&#xE5C8;</i></button>\n"); out.write(" <button onclick=\"window.location.href=home\">click me</button>\n"); out.write(" \n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </body>\n"); out.write("\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
package components; import java.awt.Color; final class Couleur { private static final int size = 4; public static final Color getCouleur(int couleur) { Color color = Color.white; switch (couleur) { case 0: { color = new Color(255, 128, 128); break; } case 1: { color = new Color(128, 255, 128); break; } case 2: { color = new Color(128, 128, 255); break; } case 3: { color = new Color(191, 191, 191); } } return color; } public static final String getNomCouleur(int couleur) { String nom = ""; switch (couleur) { case 0: { nom = "Rouge clair"; break; } case 1: { nom = "Vert clair"; break; } case 2: { nom = "Bleu clair"; break; } case 3: { nom = "Gris clair"; } } return nom; } public static final int getSize() { return 4; } Couleur() { } }
package com.nxtlife.mgs.filtering.filter; import org.springframework.stereotype.Component; import com.nxtlife.mgs.entity.activity.QActivityPerformed; import com.querydsl.core.types.Predicate; @Component public class ActivityPerformedFilterBuilder implements FilterBuilder<ActivityPerformedFilter> { private final QActivityPerformed ActivityPerformed = QActivityPerformed.activityPerformed; // @Override // public Predicate build(ActivityPerformedFilter filter) { // return new OptionalBooleanBuilder(ActivityPerformed.isNotNull()) // .notEmptyAnd(ActivityPerformed.teacher.cid::contains, // filter.getTeacherId()) // .notEmptyAnd(ActivityPerformed.activity.fourS.stringValue()::containsIgnoreCase, // filter.getFourS()) // .notEmptyAnd(ActivityPerformed.activityStatus.stringValue()::containsIgnoreCase, // filter.getStatus()) // .notEmptyAnd(ActivityPerformed.activity.cid::contains, // filter.getActivityId()) // .notEmptyAnd(ActivityPerformed.activity.focusAreas.any().cid::contains, // filter.getFocusAreaId()) // .notEmptyAnd(ActivityPerformed.activity.focusAreas.any().psdArea.stringValue()::containsIgnoreCase, // filter.getPsdArea()) // .notEmptyAnd(ActivityPerformed.dateOfActivity.year().stringValue()::containsIgnoreCase, // filter.getYear()) // .build(); // } @Override public Predicate build(ActivityPerformedFilter filter) { return new OptionalBooleanBuilder(ActivityPerformed.isNotNull()) .notEmptyAnd(ActivityPerformed.student.cid::eq, filter.getStudentId()) .notEmptyAnd(ActivityPerformed.teacher.cid::eq, filter.getTeacherId()) .notEmptyAnd(ActivityPerformed.activity.fourS.stringValue()::containsIgnoreCase, filter.getFourS()) .notEmptyAnd(ActivityPerformed.activityStatus.stringValue()::containsIgnoreCase, filter.getStatus()) .notEmptyAnd(ActivityPerformed.activity.cid::contains, filter.getActivityId()) .notEmptyAnd(ActivityPerformed.activity.focusAreas.any().name::containsIgnoreCase, filter.getFocusArea()) .notEmptyAnd(ActivityPerformed.activity.focusAreas.any().psdArea.stringValue()::containsIgnoreCase, filter.getPsdArea()) .notEmptyAnd(ActivityPerformed.dateOfActivity.year().stringValue()::containsIgnoreCase, filter.getYear()) .notEmptyAnd(ActivityPerformed.student.school.cid::eq, filter.getSchoolId()) .notEmptyAnd(ActivityPerformed.student.grade.name::equalsIgnoreCase, filter.getGrade()) .notEmptyAnd(ActivityPerformed.student.grade.section::equalsIgnoreCase, filter.getSection()) .notEmptyAnd(ActivityPerformed.active.stringValue()::containsIgnoreCase, "TRUE").build(); } }
package com.tencent.mm.plugin.appbrand.jsapi.audio; import com.tencent.mm.g.a.s; import com.tencent.mm.plugin.appbrand.jsapi.e; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.x; class e$a extends a { public String appId = ""; public String bGW = ""; private e fFF; public l fFa; public int fFd; public boolean fHX = false; public e$a(e eVar, l lVar, int i) { this.fFF = eVar; this.fFa = lVar; this.fFd = i; } public final void ahW() { x.i("MicroMsg.Audio.JsApiDestroyInstanceAudio", "runTask"); x.i("MicroMsg.AudioPlayerHelper", "destroyAudio, audioId:%s", new Object[]{this.bGW}); s sVar = new s(); sVar.bGU.action = 5; sVar.bGU.bGW = r0; a.sFg.m(sVar); this.fHX = sVar.bGV.bGZ; En(); } public final void En() { super.En(); x.i("MicroMsg.Audio.JsApiDestroyInstanceAudio", "callback"); if (this.fFa == null) { x.e("MicroMsg.Audio.JsApiDestroyInstanceAudio", "server is null"); } else if (this.fHX) { this.fFa.E(this.fFd, this.fFF.f("fail", null)); } else { this.fFa.E(this.fFd, this.fFF.f("ok", null)); } } }
package leetcode; /** * @author kangkang lou */ public class Main_231 { public static boolean isPowerOfTwo(int n) { if (n <= 0) { return false; } if (n == 1) { return true; } while (n != 1) { if (n % 2 == 0) { n = n / 2; } else { return false; } } return true; } public static void main(String[] args) { System.out.println(isPowerOfTwo(2)); System.out.println(isPowerOfTwo(1)); System.out.println(isPowerOfTwo(3)); System.out.println(isPowerOfTwo(16)); } }
package com.tencent.mm.plugin.freewifi.d; import com.tencent.mm.protocal.c.xo; import java.util.LinkedList; class e$1 implements Runnable { final /* synthetic */ e jkz; e$1(e eVar) { this.jkz = eVar; } public final void run() { xo xoVar = (xo) this.jkz.diG.dIE.dIL; if (xoVar != null) { LinkedList linkedList = xoVar.rDs; } } }
package com.tencent.mm.bs; import com.tencent.mm.bs.b.b; import java.util.HashSet; import java.util.Iterator; public class a<T> implements b<T> { private final String mName; private T sNA; private HashSet<com.tencent.mm.bs.b.a<T>> sNB; private final Object sNC; private a(String str) { this.sNC = new Object(); this.mName = str; this.sNB = new HashSet(); } a(String str, T t) { this(str); this.sNA = t; } public final String name() { return this.mName; } public final T get() { return this.sNA; } final void set(T t) { T t2 = this.sNA; Object obj = (t == t2 || (t != null && t.equals(t2))) ? 1 : null; if (obj == null) { this.sNA = t; synchronized (this.sNC) { Iterator it = this.sNB.iterator(); while (it.hasNext()) { ((com.tencent.mm.bs.b.a) it.next()).aZ(t); } } } } public final void a(com.tencent.mm.bs.b.a<T> aVar) { boolean add; synchronized (this.sNC) { add = this.sNB.add(aVar); } if (add) { c(aVar); } } public final void b(com.tencent.mm.bs.b.a<T> aVar) { boolean remove; synchronized (this.sNC) { remove = this.sNB.remove(aVar); } if (remove) { d(aVar); } } public final void removeAllListeners() { HashSet hashSet; synchronized (this.sNC) { hashSet = this.sNB; this.sNB = new HashSet(); } Iterator it = hashSet.iterator(); while (it.hasNext()) { d((com.tencent.mm.bs.b.a) it.next()); } } protected void c(com.tencent.mm.bs.b.a<T> aVar) { } protected void d(com.tencent.mm.bs.b.a<T> aVar) { } public String toString() { return "Status: " + this.mName; } }
package SortingPack; import java.util.Scanner; public class InsertionSort { void insertionsort(int arr[],int n){ int i,j,temp; for(i=1;i<n;i++) { temp=arr[i]; j=i; while (j>0&&arr[j-1]>temp) { arr[j] = arr[j-1]; j--; } arr[j]=temp; } } } class InsertionSortDemo { public static void main(String []args) { int i,n; Scanner sc=new Scanner(System.in); System.out.println("Eneter the no of elements in array"); n=sc.nextInt(); int arr[]=new int[n]; System.out.println("Enter the array elements"); for(i=0;i<n;i++) { arr[i]=sc.nextInt(); } InsertionSort is=new InsertionSort(); is.insertionsort(arr,n); System.out.println(); for(i=0;i<n;i++) System.out.print(arr[i]+" "); } }
package tij.annotations; import org.junit.Test; public class JUnitTest { String na(String world){ return "hello "+world; } @Test public void f(){ System.out.println(na("world").equals("hello world")); } }
package enthu_l; public class e_1366 { public static void main(String[] args) {while(int k = 5; k<7) {System.out.println(k++);}} }
package com.ecommerce.Repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ecommerce.model.Book; public interface BookRepository extends JpaRepository<Book,Long> { }
/** * @since 2016/01/30 */ public class DatabaseTest { public static void main(String[] args) { } }
package com.jack.hotitems; import com.jack.beans.ItemViewCount; import com.jack.beans.UserBehavior; import com.jack.connect.ConnectDescribe; import com.jack.sourceData.SourceData; import org.apache.flink.api.common.functions.AggregateFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.state.ListState; import org.apache.flink.api.common.state.ListStateDescriptor; import org.apache.flink.api.java.tuple.Tuple; import org.apache.flink.configuration.Configuration; import org.apache.flink.shaded.curator.org.apache.curator.shaded.com.google.common.collect.Lists; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.KeyedProcessFunction; import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor; import org.apache.flink.streaming.api.functions.windowing.WindowFunction; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.api.windowing.windows.TimeWindow; import org.apache.flink.util.Collector; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; /** * @author jack Deng * @version 1.0 * @date 2021/8/19 19:19 * * 统计一小时内的热门商品,五分钟更新一次 */ public class HotItems { public static void main(String[] args) throws Exception{ // 创建环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 设置并行度 env.setParallelism(1); // 设置时间语义 env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); SourceData SourceData = new SourceData(env); // 获取文件数据 DataStreamSource<String> inputData = SourceData.getData(ConnectDescribe.getFileProperties()); // 获取kafka数据 // DataStreamSource<String> inputData = SourceData.getData(ConnectDescribe.getKafkaProperties()); SingleOutputStreamOperator<UserBehavior> streamData = inputData.map(new MapFunction<String, UserBehavior>() { @Override public UserBehavior map(String s) throws Exception { String[] field = s.split(","); return new UserBehavior(new Long(field[0]), new Long(field[1]), new Integer(field[2]), field[3], new Long(field[4])); } }).assignTimestampsAndWatermarks(new AscendingTimestampExtractor<UserBehavior>() { @Override public long extractAscendingTimestamp(UserBehavior element) { return element.getTimeStamp() * 1000L; } }); SingleOutputStreamOperator<ItemViewCount> hotItemResult = streamData .filter(line -> "pv".equals(line.getBehavior())) // 过滤数据 .keyBy("itemsId") // 商品分组 .timeWindow(Time.hours(1), Time.minutes(5)) // 滑动窗口 .aggregate(new ItemCountAgg(), new WindowItemCountResult()); //增量聚合 全窗口函数 SingleOutputStreamOperator<String> topResult = hotItemResult .keyBy("windowEnd") .process(new MyProcess(5)); topResult.print(); env.execute("热门商品"); } public static class MyProcess extends KeyedProcessFunction<Tuple, ItemViewCount,String> { private final Integer topSize; public MyProcess(Integer topSize) { this.topSize = topSize; } ListState<ItemViewCount> hotItemTopState; @Override public void open(Configuration parameters) throws Exception { ListStateDescriptor<ItemViewCount> itemViewCountValueStateDescriptor = new ListStateDescriptor<ItemViewCount>("item-top", ItemViewCount.class); hotItemTopState = getRuntimeContext().getListState(itemViewCountValueStateDescriptor); } @Override public void close() throws Exception { super.close(); } @Override public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception { // 定时器触发 收集到当前的全部数据,进行排序 Iterator<ItemViewCount> iterator = hotItemTopState.get().iterator(); ArrayList<ItemViewCount> itemViewCounts = Lists.newArrayList(iterator); // 排序 itemViewCounts.sort(new Comparator<ItemViewCount>() { @Override public int compare(ItemViewCount o1, ItemViewCount o2) { return o2.getCount().intValue()-o1.getCount().intValue(); } }); // 将排序结果转换为String StringBuilder resultBuilder = new StringBuilder(); resultBuilder.append("===========================================\n"); resultBuilder.append("窗口结束时间:").append(new Timestamp(timestamp-1)).append("\n"); // 便利取出排序结果 for(int i = 0; i<Math.min(itemViewCounts.size(), topSize);i++){ ItemViewCount itemViewCount = itemViewCounts.get(i); resultBuilder.append("NO ") .append(i+1) .append(": 商品 = ") .append(itemViewCount.getItemId()) .append("; 热门度:").append(itemViewCount.getCount()).append("\n"); } resultBuilder.append("===========================================\n\n"); out.collect(resultBuilder.toString()); // 控制频率 // Thread.sleep(1000L); } @Override public void processElement(ItemViewCount value, Context ctx, Collector<String> out) throws Exception { hotItemTopState.add(value); ctx.timerService().registerEventTimeTimer(value.getWindowEnd() + 1); } } public static class ItemCountAgg implements AggregateFunction<UserBehavior,Long, Long> { @Override public Long createAccumulator() { return 0L; } @Override public Long add(UserBehavior userBehavior, Long aLong) { return aLong + 1; } @Override public Long getResult(Long aLong) { return aLong; } @Override public Long merge(Long aLong, Long acc1) { return aLong+acc1; } } public static class WindowItemCountResult implements WindowFunction<Long, ItemViewCount, Tuple, TimeWindow> { @Override public void apply(Tuple tuple, TimeWindow window, Iterable<Long> input, Collector<ItemViewCount> out) throws Exception { Long itemId = tuple.getField(0); Long windowEnd = window.getEnd(); Long count = input.iterator().next(); out.collect(new ItemViewCount(itemId, windowEnd, count)); } } }
package com.tencent.mm.plugin.sns.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.sns.model.r; class SnsMsgUI$6 implements OnCancelListener { final /* synthetic */ SnsMsgUI nYl; final /* synthetic */ r nYm; SnsMsgUI$6(SnsMsgUI snsMsgUI, r rVar) { this.nYl = snsMsgUI; this.nYm = rVar; } public final void onCancel(DialogInterface dialogInterface) { g.Ek(); g.Eh().dpP.c(this.nYm); } }
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.authority.concept; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.cocoon.environment.Request; import org.apache.log4j.Logger; import org.dspace.app.xmlui.aspect.administrative.FlowResult; import org.dspace.app.xmlui.aspect.authority.FlowAuthorityMetadataValueUtils; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.authorize.AuthorizeException; import org.dspace.content.authority.*; import org.dspace.core.Constants; import org.dspace.core.Context; /** * Utility methods to processes actions on EPeople. These methods are used * exclusively from the administrative flow scripts. * * @author Scott Phillips */ public class FlowConceptUtils { /** log4j category */ private static final Logger log = Logger.getLogger(FlowConceptUtils.class); /** Language Strings */ private static final Message T_add_Concept_success_notice = new Message("default","xmlui.administrative.FlowConceptUtils.add_Concept_success_notice"); private static final Message T_edit_Concept_success_notice = new Message("default","xmlui.administrative.FlowConceptUtils.edit_Concept_success_notice"); private static final Message t_add_Concept_success_notice = new Message("default","xmlui.administrative.FlowConceptUtils.reset_password_success_notice"); private static final Message t_delete_Concept_success_notice = new Message("default","xmlui.administrative.FlowConceptUtils.delete_Concept_success_notice"); private static final Message t_delete_Concept_failed_notice = new Message("default","xmlui.administrative.FlowConceptUtils.delete_Concept_failed_notice"); private static final Message t_delete_Term_success_notice = new Message("default","xmlui.administrative.FlowTermUtils.delete_Term_success_notice"); private static final Message t_delete_Term_failed_notice = new Message("default","xmlui.administrative.FlowTermUtils.delete_Term_failed_notice"); /** * Add a new Concept. This method will check that the email address, * first name, and last name are non empty. Also a check is performed * to see if the requested email address is already in use by another * user. * * @param context The current DSpace context * @param request The HTTP request parameters * @param objectModel Cocoon's object model * @return A process result's object. */ public static FlowResult processAddConcept(Context context,String schemeId, Request request, Map objectModel) throws SQLException, AuthorizeException,NoSuchAlgorithmException { FlowResult result = new FlowResult(); result.setContinue(false); // default to no continue Concept newConcept = null; Boolean topConcept = (request.getParameter("topConcept") == null) ? false : true; String language = request.getParameter("language"); String status = request.getParameter("status"); String value = request.getParameter("value"); if(value==null||value.length()==0) { result.addError("value"); } // No errors, so we try to create the Concept from the data provided if (result.getErrors() == null) { if(schemeId!=null&&schemeId.length()>0) { Scheme scheme = Scheme.find(context, Integer.parseInt(schemeId)); newConcept = scheme.createConcept(); newConcept.setStatus(status); newConcept.setLang(language); newConcept.setTopConcept(topConcept); newConcept.update(); Term newTerm = newConcept.createTerm(value,Term.prefer_term); newTerm.update(); context.commit(); // success result.setContinue(true); result.setOutcome(true); result.setMessage(T_add_Concept_success_notice); result.setParameter("ConceptID", newConcept.getID()); } else { result.addError("Please select a scheme to add a new concept"); } } return result; } /** * Edit an Concept's metadata, the email address, first name, and last name are all * required. The user's email address can be updated but it must remain unique, if * the email address already exists then the an error is produced. * * @param context The current DSpace context * @param request The HTTP request parameters * @return A process result's object. */ public static FlowResult processEditConcept(Context context, Request request, Map ObjectModel, int conceptID) throws SQLException, AuthorizeException { FlowResult result = new FlowResult(); result.setContinue(false); // default to failure // Get all our request parameters String status = request.getParameter("status"); Boolean topConcept = (request.getParameter("topConcept") == null) ? false : true; String identifier = request.getParameter("identifier"); String language = request.getParameter("lang"); //boolean certificate = (request.getParameter("certificate") != null) ? true : false; // No errors, so we edit the Concept with the data provided if (result.getErrors() == null) { // Grab the person in question Concept conceptModified = Concept.find(context, conceptID); Boolean originalTopConcept = conceptModified.getTopConcept(); if (originalTopConcept == null || !originalTopConcept.equals(topConcept)) { conceptModified.setTopConcept(topConcept); } String originalStatus = conceptModified.getStatus(); if (originalStatus == null || !originalStatus.equals(status)) { conceptModified.setStatus(status); } String originalLang = conceptModified.getLang(); if (originalLang == null || !originalLang.equals(language)) { conceptModified.setLang(language); } conceptModified.update(); context.commit(); result.setContinue(true); result.setOutcome(true); // FIXME: rename this message result.setMessage(T_edit_Concept_success_notice); } // Everything was fine return result; } /** * Delete the epeople specified by the epeopleIDs parameter. This assumes that the * deletion has been confirmed. * * @param context The current DSpace context * @param conceptIds The unique id of the Concept being edited. * @return A process result's object. */ public static FlowResult processDeleteConcept(Context context, String[] conceptIds) throws NumberFormatException, SQLException, AuthorizeException { FlowResult result = new FlowResult(); List<String> unableList = new ArrayList<String>(); for (String id : conceptIds) { Concept conceptDeleted = Concept.find(context, Integer.valueOf(id)); try { conceptDeleted.delete(); } catch (Exception epde) { int conceptDeletedId = conceptDeleted.getID(); unableList.add(Integer.toString(conceptDeletedId)); } } if (unableList.size() > 0) { result.setOutcome(false); result.setMessage(t_delete_Concept_failed_notice); String characters = null; for(String unable : unableList ) { if (characters == null) { characters = unable; } else { characters += ", " + unable; } } result.setCharacters(characters); } else { result.setOutcome(true); result.setMessage(t_delete_Concept_success_notice); } return result; } public static String[] getPreferredTerms(Context context, int groupID) throws SQLException { // New group, just return an empty list if (groupID < 0) { return new String[0]; } Concept group = Concept.find(context, groupID); if (group == null) { return new String[0]; } Term[] epeople = group.getPreferredTerms(); String[] epeopleIDs = new String[epeople.length]; for (int i=0; i < epeople.length; i++) { epeopleIDs[i] = String.valueOf(epeople[i].getID()); } return epeopleIDs; } public static String[] getParentConcepts(Context context, int groupID) throws SQLException { if (groupID < 0) { return new String[0]; } Concept group = Concept.find(context, groupID); if (group == null) { return new String[0]; } Concept[] groups = group.getParentConcepts(); String[] groupIDs = new String[groups.length]; for (int i=0; i < groups.length; i++) { groupIDs[i] = String.valueOf(groups[i].getID()); } return groupIDs; } public static FlowResult processAddTerm(Context context,int conceptId,Request request) throws SQLException, AuthorizeException { FlowResult result = new FlowResult(); result.setContinue(false); // default to failure Concept concept = (Concept) AuthorityObject.find(context, Constants.CONCEPT, conceptId); // Get all our request parameters String literalForm = request.getParameter("literalForm"); String source = request.getParameter("source"); String status = request.getParameter("status"); String lang = request.getParameter("lang"); String preferred = request.getParameter("preferred"); if (result.getErrors() == null) { if(preferred==null) { //add it as alt term preferred=Integer.toString(Term.alternate_term); } Term term = concept.createTerm(literalForm, Integer.parseInt(preferred)); java.util.Date date = new java.util.Date(); term.setCreated(date); if (literalForm == null) { term.setLiteralForm(literalForm); } if (source == null ) { term.setSource(source); } if (status == null ) { term.setStatus(status); } if (lang == null ) { term.setLang(lang); } if (lang == null ) { term.setLang(lang); } term.setLastModified(date); term.update(); context.commit(); result.setContinue(true); result.setOutcome(true); // FIXME: rename this message result.setMessage(T_edit_Concept_success_notice); } // Everything was fine return result; } public static FlowResult processEditConceptMetadata(Context context, String id,Request request){ return FlowAuthorityMetadataValueUtils.processEditMetadata(context, Constants.CONCEPT, id, request); } public static FlowResult doDeleteMetadataFromConcept(Context context, String id,Request request)throws SQLException, AuthorizeException, UIException, IOException { return FlowAuthorityMetadataValueUtils.doDeleteMetadata(context, Constants.CONCEPT,id, request); } public static FlowResult doAddMetadataToConcept(Context context, int id, Request request) throws SQLException, AuthorizeException, UIException, IOException { return FlowAuthorityMetadataValueUtils.doAddMetadata(context, Constants.CONCEPT,id, request); } public static void addTerm2Concept (Context context,String conceptId, String termId,Request request)throws SQLException,AuthorizeException{ Concept concept = Concept.find(context, Integer.parseInt(conceptId)); Term term = Term.find(context, Integer.parseInt(termId)); boolean preferred = (request.getParameter("preferred") != null) ? true : false; int role_id = 2; if(preferred) { role_id = 1; } concept.addTerm(term,role_id); concept.update(); context.commit(); } public static FlowResult processDeleteTerm(Context context, String conceptId,String[] termIds)throws SQLException,AuthorizeException{ FlowResult result = new FlowResult(); List<String> unableList = new ArrayList<String>(); for (String id : termIds) { Concept2Term relationDeleted = Concept2Term.findByConceptAndTerm(context,Integer.parseInt(conceptId), Integer.valueOf(id)); try { relationDeleted.delete(context); } catch (Exception epde) { int termDeletedId = relationDeleted.getRelationID(); unableList.add(Integer.toString(termDeletedId)); } } if (unableList.size() > 0) { result.setOutcome(false); result.setMessage(t_delete_Term_failed_notice); String characters = null; for(String unable : unableList ) { if (characters == null) { characters = unable; } else { characters += ", " + unable; } } result.setCharacters(characters); } else { result.setOutcome(true); result.setMessage(t_delete_Term_success_notice); } return result; } public static FlowResult doAddConceptToConcept(Context context,String conceptId,Request request){ FlowResult result = new FlowResult(); result.setOutcome(false); String[] conceptIds = request.getParameterValues("select_concepts"); ArrayList<String> error = new ArrayList<String>(); try{ Concept concept = (Concept)AuthorityObject.find(context,Constants.CONCEPT,Integer.parseInt(conceptId)); for(String secondConceptId : conceptIds) { if(!conceptId.equals(secondConceptId)) { Concept secondConcept = (Concept)AuthorityObject.find(context,Constants.CONCEPT,Integer.parseInt(secondConceptId)); if(secondConcept!=null){ concept.addChildConcept(secondConcept, Integer.parseInt(request.getParameter("roleId"))); context.commit(); result.setOutcome(true); result.setMessage(t_add_Concept_success_notice); } else { error.add("need to select a concept"); } } else { error.add("Please select a different concept"); } } }catch (Exception e) { } result.setErrors(error); if(error==null||error.size()==0) { result.setContinue(true); } return result; } }
package com.caboa.mctest; import java.util.Random; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import cpw.mods.fml.common.IWorldGenerator; public class mcTopazOreWorldGenerator implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world,IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { switch(world.provider.dimensionId) { case 0: generateSurface(world, random, chunkX *16, chunkZ *16); } } private void generateSurface(World world, Random random, int chunkX, int chunkZ) { for (int i=0; i<1; i++)//probabilidad de generacion { int xCoord = chunkX + random.nextInt(16); int yCoord = (random.nextInt(33)+8);//nivel de profundidad. Actual: 8-40 int zCoord = chunkZ + random.nextInt(16); new WorldGenMinable(mctestMod.topazOre.blockID, 3).generate(world, random, xCoord, yCoord, zCoord);//El numero es otra probabilidad de generacion. } } }
package aqua.blatt1.client; import java.net.InetSocketAddress; import aqua.blatt1.common.Direction; import aqua.blatt1.common.msgtypes.*; import messaging.Endpoint; import messaging.Message; import aqua.blatt1.common.FishModel; import aqua.blatt1.common.Properties; public class ClientCommunicator { private final Endpoint endpoint; public ClientCommunicator() { endpoint = new Endpoint(); } public class ClientForwarder { private final InetSocketAddress broker; private ClientForwarder() { this.broker = new InetSocketAddress(Properties.HOST, Properties.PORT); } public void register() { endpoint.send(broker, new RegisterRequest()); } public void deregister(String id) { endpoint.send(broker, new DeregisterRequest(id)); } public void handOff(FishModel fish, NeighborUpdate.Neighbors neighbors) { Direction direction = fish.getDirection(); InetSocketAddress receiver = (direction == Direction.LEFT) ? neighbors.getLeftNeighbor() : neighbors.getRightNeighbor(); endpoint.send(receiver, new HandoffRequest(fish)); } public void sendToken(NeighborUpdate.Neighbors neighbors) { endpoint.send(neighbors.getRightNeighbor(), new Token()); } public void sendMarkers(NeighborUpdate.Neighbors neighbors) { endpoint.send(neighbors.getRightNeighbor(), new SnapshotMarker()); endpoint.send(neighbors.getLeftNeighbor(), new SnapshotMarker()); } public void sendSnapshotCollectionToken(InetSocketAddress reciever, SnapshotCollectionToken snapshot) { endpoint.send(reciever, snapshot); } public void sendLocationRequest(InetSocketAddress reciever, String fishId) { endpoint.send(reciever, new LocationRequest(fishId)); } } public class ClientReceiver extends Thread { private final TankModel tankModel; private ClientReceiver(TankModel tankModel) { this.tankModel = tankModel; } @Override public void run() { while (!isInterrupted()) { Message msg = endpoint.blockingReceive(); synchronized (tankModel) { if (tankModel.mode != TankModel.Mode.IDLE) { if (tankModel.mode == TankModel.Mode.BOTH) if (tankModel.neighbors.isRightNeighbor(msg.getSender())) tankModel.backup.rightSaveList.add(msg); else tankModel.backup.leftSaveList.add(msg); else if (tankModel.mode == TankModel.Mode.RIGHT && tankModel.neighbors.isRightNeighbor(msg.getSender())) tankModel.backup.rightSaveList.add(msg); else if (tankModel.mode == TankModel.Mode.LEFT && tankModel.neighbors.isLeftNeighbor(msg.getSender())) tankModel.backup.leftSaveList.add(msg); } } if (msg.getPayload() instanceof RegisterResponse) tankModel.onRegistration((RegisterResponse) msg.getPayload()); if (msg.getPayload() instanceof HandoffRequest) tankModel.receiveFish(msg.getSender(), ((HandoffRequest) msg.getPayload()).getFish()); if (msg.getPayload() instanceof NeighborUpdate) tankModel.receiveNeighbors(((NeighborUpdate) msg.getPayload()).getNeighbors()); if (msg.getPayload() instanceof Token) tankModel.receiveToken(); if (msg.getPayload() instanceof SnapshotMarker) { tankModel.createLocalSnapshot(msg.getSender()); } if (msg.getPayload() instanceof SnapshotCollectionToken) tankModel.receiveSnapshotCollectionToken((SnapshotCollectionToken) msg.getPayload()); if (msg.getPayload() instanceof LocationRequest) tankModel.locateFishGlobally(((LocationRequest) msg.getPayload()).getFishId()); } } } public ClientForwarder newClientForwarder() { return new ClientForwarder(); } public ClientReceiver newClientReceiver(TankModel tankModel) { return new ClientReceiver(tankModel); } }
package net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao; import android.arch.lifecycle.LiveData; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Query; import android.arch.persistence.room.Update; import java.util.List; /** * Created by d4rk on 30/03/2018. */ @Dao public interface IngredientDao { @Query("SELECT * FROM Ingredient") LiveData<List<Ingredient>> getAll(); @Query("SELECT * FROM Ingredient ORDER BY Priority DESC") LiveData<List<Ingredient>> getAllSortByPriority(); @Query("SELECT * FROM Ingredient ORDER BY Priority DESC, Amount") LiveData<List<Ingredient>> getAllSortByPriorityAmount(); @Query("SELECT * FROM Ingredient where id LIKE :id") Ingredient findById(String id); @Query("SELECT * FROM Ingredient where Name LIKE :name") Ingredient findByName(String name); @Query("SELECT COUNT(*) from Ingredient") int countIngredients(); @Insert long insert(Ingredient ingredient); @Insert void insertAll(Ingredient... ingredients); // @Query("UPDATE Ingredient SET Amount = :amount WHERE id = :id") // void updateAmount(long id, long amount); @Update void updateIngredient(Ingredient ingredient); @Update void updateIngredients(Ingredient... ingredients); @Query("WITH AllPurchases AS (SELECT IngredientID, COUNT(id) AS PurchasesCount FROM Purchase GROUP BY IngredientID) UPDATE Ingredient SET Priority = (SELECT PurchasesCount FROM AllPurchases WHERE IngredientID = Ingredient.id)") void updatePriorities(); @Delete void delete(Ingredient ingredient); }
package com.tencent.mm.plugin.appbrand.jsapi.file; public final class aa extends b<as> { private static final int CTRL_INDEX = 397; private static final String NAME = "fs_rename"; public aa() { super(new as()); } }
package com.tencent.mm.g.a; public final class aa$a { public Object bHj; }
package com.bingo.code.example.design.facade.facadepartfunction; public interface FacadeApi { // ABCModule对外的接口 public void a1(); public void b1(); public void c1(); public void test(); // 组合方法 }
import java.util.Scanner; public class Somme { private static int n; private static float w; public static main void(String args[]){ w = 0; Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); System.out.println("Veuillez saisir le premier terme"); for(int i; i < n+1; i++) { w = w + (1/i); } System.out.println(w); } }
package com.cmj.rpc.handler; import com.cmj.common.message.AbstractRpcMsg; import java.util.List; /** * Created by chenminjian on 2018/4/18. */ public class RpcEntity extends AbstractRpcMsg { private String serviceName; private String methodName; private List<Object> args; public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public List<Object> getArgs() { return args; } public void setArgs(List<Object> args) { this.args = args; } }
package com.linkedbook.dto.likeDeal.selectLikeDeal; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter public class SelectLikeDealInput { private int userId; private int page; private int size; }
package de.marko.pentest.rest.handler; import de.marko.pentest.db.DatabaseJPAConnector; import de.marko.pentest.db.entity.User; import io.vertx.core.Handler; import io.vertx.ext.web.RoutingContext; import java.util.HashMap; import java.util.Map; /** * @author marko * @version 1.0.0. * @date 05.01.2018 */ public class GetTokenHandlerV3 implements Handler<RoutingContext> { private final String protectionString = "%2F1337+"; @Override public void handle(RoutingContext routingContext) { Map<String, String> params = parseBody(routingContext.getBodyAsString()); String name = params.get("name"); String password = params.get("password"); String mapPrev = params.get("noobprotection"); if(mapPrev == null) { routingContext.response().setStatusCode(500).end("noob"); } if(!mapPrev.equals(this.protectionString)) { routingContext.response().setStatusCode(500).end("noob"); } String query = "SELECT u.id, u.name, u.password, u.token, u.version" + " FROM Users u" + " WHERE name = '" + name + "' AND password = '" + password + "'"; User user = DatabaseJPAConnector.connect() .nativeSelectQuery(query, User.class) .stream() .findFirst() .orElse(null); if (user != null) { routingContext.response().setStatusCode(200).end(user.getToken()); } else { routingContext.response().setStatusCode(500).end(""); } } private Map<String, String> parseBody(String buffer) { Map<String, String> params = new HashMap<String, String>(); String[] paramSplits = buffer.toString().split("&"); String[] valueSplits; if (paramSplits.length > 1) { for (String param : paramSplits) { valueSplits = param.split("="); if (valueSplits.length > 1) { params.put(valueSplits[0], valueSplits[1]); } } } return params; } }
package cz.csas.atpcoolapp.services; import cz.csas.atpcoolapp.Common; import cz.csas.atpcoolapp.cryprography.paillier.PublicKey; import cz.csas.atpcoolapp.entity.Basket; import cz.csas.atpcoolapp.entity.BillIItem; import cz.csas.atpcoolapp.entity.Price; import cz.csas.atpcoolapp.entity.Transaction; import org.json.JSONObject; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameNotFoundException; import javax.naming.NamingException; import java.math.BigInteger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; /** * Created by cen29253 on 16.9.2017. */ public class TransactionService { private static final String SELECT_ALL_TRANSACTIONS = "select * from HPLATFORM.TRANSACTIONS order by authdate desc"; private static final String SELECT_ITEMS_FOR_TRN = "select * from HPLATFORM.BILITEMS where trnid = ?"; private static final String SELECT_PRICES_FOR_TRN = "select * from HPLATFORM.PRICES where trnid = ?"; public static List<Transaction> getTransactions() { List<Transaction> transactions = new ArrayList<>(); Connection conn = null; PreparedStatement preparedStatement; Context ctx = null; String pool_data_source = Common.POOL_DATA_SOURCE; ResultSet rs = null; try { ctx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(pool_data_source); conn = ds.getConnection(); preparedStatement = conn.prepareStatement(SELECT_ALL_TRANSACTIONS); rs = preparedStatement.executeQuery(); if (rs != null) { while (rs.next()) { Transaction trn = new Transaction(); trn.setTrnid(rs.getString("trnid")); trn.setAmount(rs.getString("amount")); trn.setCurrency(rs.getString("currency")); trn.setExpdate(rs.getString("expdate")); trn.setMpan(rs.getString("mpan")); trn.setStatus(rs.getString("status")); trn.setAuthdate(rs.getTimestamp("authdate")); //trn.setPubkey(rs.getString("pubkey")); transactions.add(trn); } } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (conn != null) { conn.close(); } if (ctx != null) { ctx.close(); } } catch (SQLException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } return transactions; } public static List<BillIItem> getBillItems(String trnid) { List<BillIItem> bills = new ArrayList<>(); Connection conn = null; PreparedStatement preparedStatement; Context ctx = null; String pool_data_source = Common.POOL_DATA_SOURCE; ResultSet rs = null; try { ctx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(pool_data_source); conn = ds.getConnection(); preparedStatement = conn.prepareStatement(SELECT_ITEMS_FOR_TRN); preparedStatement.setString(1,trnid); rs = preparedStatement.executeQuery(); if (rs != null) { while (rs.next()) { BillIItem bil = new BillIItem(); bil.setTrnid(rs.getString("trnid")); bil.setId(rs.getString("id")); bil.setName(rs.getString("name")); bil.setPrice(rs.getString("price")); bil.setType(rs.getString("type")); bills.add(bil); } } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (conn != null) { conn.close(); } if (ctx != null) { ctx.close(); } } catch (SQLException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } return bills; } public static List<Basket> getBaskets(String trnid) { JSONObject pk = new JSONObject(Common.DEMO_PAILLIER_PUB); BigInteger nSquared = new BigInteger(pk.getString("nSquared")); BigInteger n = new BigInteger(pk.getString("n")); BigInteger g = new BigInteger(pk.getString("g")); int bits = 256; PublicKey publicKey = new PublicKey(n, nSquared, g, bits); List<Basket> baskets = new ArrayList<>(); List<BillIItem> billIItems = getBillItems(trnid); BigInteger encryptedAddition = null; int idx = 0; for (BillIItem billIItem: billIItems) { if (idx == 0) { encryptedAddition = new BigInteger(billIItem.getPrice()); } else { encryptedAddition = encryptedAddition.multiply(new BigInteger(billIItem.getPrice())).mod(publicKey.getnSquared()); } idx++; } Basket basket = new Basket(); basket.setName("Main"); basket.setPrice(encryptedAddition.toString()); baskets.add(basket); Map<String, BigInteger> otherBaskets = new HashMap<String, BigInteger>(); List<Price> prices = getPrices(trnid); for (Price price:prices) { if (otherBaskets.get(price.getRegion()) == null) { otherBaskets.put(price.getRegion(), new BigInteger(price.getPrice())); } else { otherBaskets.put(price.getRegion(), otherBaskets.get(price.getRegion()).multiply(new BigInteger(price.getPrice())).mod(publicKey.getnSquared())); } } Set<String> keys = otherBaskets.keySet(); for (String key:keys) { Basket basketS = new Basket(); BigInteger price = otherBaskets.get(key); basketS.setPrice(price.toString()); if (Common.regionMap.get(key) != null) { basketS.setName(Common.regionMap.get(key)); baskets.add(basketS); } } return baskets; } public static List<Price> getPrices(String trnid) { List<Price> prices = new ArrayList(); Connection conn = null; PreparedStatement preparedStatement; Context ctx = null; String pool_data_source = Common.POOL_DATA_SOURCE; ResultSet rs = null; try { ctx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup(pool_data_source); conn = ds.getConnection(); preparedStatement = conn.prepareStatement(SELECT_PRICES_FOR_TRN); preparedStatement.setString(1,trnid); rs = preparedStatement.executeQuery(); if (rs != null) { while (rs.next()) { Price price = new Price(); price.setId(rs.getString("id")); price.setId(rs.getString("trnid")); price.setRegion(rs.getString("region")); price.setPrice(rs.getString("price")); price.setType(rs.getString("type")); prices.add(price); } } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (conn != null) { conn.close(); } if (ctx != null) { ctx.close(); } } catch (SQLException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } return prices; } }
package com.IRCTradingDataGenerator.tradingDataGenerator.Repository; import org.springframework.data.jpa.repository.JpaRepository; import com.IRCTradingDataGenerator.tradingDataGenerator.Models.Transaction; public interface TransactionDao extends JpaRepository<Transaction, Integer>{ }
package com.jiw.dudu.structure; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @Description 找到所有数组中消失的数字 * @Author pangh * @Date 2022年09月08日 * @Version v1.0.0 * * 力扣算法题:https://leetcode.cn/problems/find-all-numbers-disappeared-in-an-array/ * 解题思路: * 1. */ public class FindAllNumArray448 { @Test public void test(){ System.out.println(findDisappearedNumbers1(new int[]{4,3,2,7,8,2,3,1})); } public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> list = new ArrayList<>(); for(int num : nums){ int subscript = Math.abs(num) -1; if(nums[subscript] > 0){ nums[subscript] = -nums[subscript]; } } for(int i=0;i<nums.length;i++){ if(nums[i] > 0){ list.add(i+1); } } return list; } public List<Integer> findDisappearedNumbers1(int[] nums){ int n = nums.length; for (int num : nums) { int x = (num - 1) % n; nums[x] += n; } List<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (nums[i] <= n) { ret.add(i + 1); } } return ret; } }
package fr.alplc; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.HttpsURLConnection; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PageServlet extends HttpServlet { public static final Logger log = Logger.getLogger("fr.alplc"); public static interface Config { public String getBuild() ; public String getLocalWorkDir(); public String getByeAndBack(); } public static class Errors { public String get(String code) { return null; } } public static class URIParser { // public static void startup(ServletConfig servletConfig) throws ServletException ; protected static String loadConfig(String name, ServletContext ctx) throws ServletException{ try { InputStream is = ctx.getResourceAsStream("/WEB-INF/" + name); if (is == null) throw new Exception(""); return new String(PageServlet.bytesFromStream(is), "UTF-8"); } catch (Exception e1) { String msg1 = "BUGB - " + name + " non trouvé"; log.log(Level.SEVERE, msg1); throw new ServletException(msg1, e1); } } private String appName = null; public String appName() { return appName; } private String ext = null; public String ext() { return ext; } private String contextPath = null; public String contextPath() { return contextPath; } private String[] uri; public String[] uri() { return uri; } private String appPrefix; public String appPrefix() { return appPrefix; } private String serverBuild; public String serverBuild() { return serverBuild; } /** * Retourne le string JSON représr=entant un objet de credential pour le client * calculé depuis les données ci-dessus. {doamine:'toto', compte:12345} * @return */ public String credential() { return "null"; } } /***************************************************************/ private static final long serialVersionUID = 1L; protected ServletConfig servletConfig; protected String contextPath; private Config config; private String localWorkDir = null; private String byeAndBack = "/byeAndBack.html"; private String build = "0.0"; public String build() { return build; } private Class<?> uriParserClass; private ServletContext ctx; private Ressources ressources = new Ressources(); private Method startup = null; private void initUriParser(ServletConfig servletConfig) throws ServletException{ this.servletConfig = servletConfig; ctx = servletConfig.getServletContext(); contextPath = ctx.getContextPath(); String c = ctx.getInitParameter("URIParserClass"); if (c == null) throw new ServletException("La classe URIParserClass n'est pas donnée en paramètre du web.xml"); uriParserClass = hasClass(c, URIParser.class); try { startup = uriParserClass.getMethod("startup", ServletConfig.class); if (!Modifier.isStatic(startup.getModifiers())) throw new Exception(""); } catch (Exception e) { throw new ServletException("La classe " + uriParserClass.getSimpleName() + " donnée dans web.xml n'a pas méthode static startup(ServletConfig cfg, String build"); } } @Override public void init(ServletConfig servletConfig) throws ServletException { initUriParser(servletConfig); Properties exts = new Properties(); try { InputStream is = ctx.getResourceAsStream("/WEB-INF/ext-resources.properties"); if (is != null) exts.load(is); } catch (IOException e1) { throw new ServletException("Ressource /WEB-INF/ext-resources.properties mal formée"); } synchronized (PageServlet.class) { try { config = invokeStartup(servletConfig); build = config.getBuild(); localWorkDir = config.getLocalWorkDir(); byeAndBack = config.getByeAndBack(); preload(contextPath); preloadExt(exts); } catch (Exception e) { if (e instanceof ServletException) throw (ServletException)e; throw new ServletException(e); } } } public final InputStream resAsStream(String name){ return ctx.getResourceAsStream(name); } public Config invokeStartup(ServletConfig servletConfig) throws ServletException { try { if (startup == null) initUriParser(servletConfig); return (Config)startup.invoke(null, servletConfig); } catch (Exception e) { if (e instanceof ServletException) throw (ServletException)e; throw new ServletException(e); } } private void preloadExt(Properties exts) throws ServletException { int nb = 0; for(Entry<Object, Object> e : exts.entrySet()) { String url = (String)e.getValue(); String name = "/" + (String) e.getKey(); ressources.set(name, url); nb++; } log.info(nb + " ressources chargées"); } private void lpath(ArrayList<String> lst, String root){ Set<String> paths = ctx.getResourcePaths(root); if (paths == null) return; for(String s : paths){ if (s.startsWith("/WEB-INF/")) continue; String d = s.substring(root.length() - 1); if (s.startsWith("/bower_components/") && (d.equals("/test/") || d.equals("/demo/") || d.equals("/index.html"))) continue; if (s.startsWith("/apps/") && s.endsWith(".html")){ String appName = d.substring(1, d.length() - 5); lst.add(s); lst.add("/" + appName + ".appa"); } if (s.endsWith("/")) lpath(lst, s); else { if (!s.startsWith("bower") && !s.endsWith("/.gitignore") && !s.endsWith("/.travis.yml") && !s.endsWith(".md")) lst.add(s); } } } private void preload(String contextPath) throws ServletException{ ArrayList<String> lst = new ArrayList<String>(); lpath(lst, "/"); for(String s : lst) { if (s.endsWith(".appa")) { String u = s.substring(1, s.length()); Ressources.Ressource c = pageText(u); if (c != null) c.store(); } else ressources.set(s); } log.info(lst.size() + " ressources chargées"); } private class Ressources { private final Hashtable<String, Ressource> cache = new Hashtable<String, Ressource>(); private String[] getAllNames(){ return cache.keySet().toArray(new String[cache.size()]); } private Ressource set(String name, String u) throws ServletException { Ressource c = cache.get(name); if (c != null) return c; byte[] bytes = null; String nloc = null; InputStream is = null; try { if (localWorkDir != null) { nloc = localWorkDir + "/external" + name ; is = new FileInputStream(nloc); } else is = resAsStream("/work/external" + name); if (is != null) { bytes = PageServlet.bytesFromStream(is); is.close(); } } catch (IOException e) { } if (bytes == null) { try { URL url = new URL(u); HttpURLConnection conn = url.getProtocol().equals("https") ? (HttpsURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection(); is = conn.getInputStream(); if (is == null) err(name); bytes = is != null ? bytesFromStream(is) : null; if (bytes != null && nloc != null) { try { FileOutputStream fos = new FileOutputStream(nloc); fos.write(bytes); fos.close(); } catch (IOException e) { } } } catch (Exception ex) { err(name); } } return newRessource(name, bytes).store(); } private void err(String name) throws ServletException { throw new ServletException("La ressource [" + name + "] n'a pas été trouvée"); } private Ressource set(String name) throws ServletException{ Ressource c = cache.get(name); if (c != null) return c; byte[] bytes = null; InputStream is = servletConfig.getServletContext().getResourceAsStream(name); if (is == null) err(name); try { bytes = is != null ? bytesFromStream(is) : null; is.close(); } catch (Exception ex) { err(name); } c = newRessource(name, bytes); cache.put(name, c); log.info("Preload : " + name) ; return c; } private Ressource get(String name) { return cache.get(name); } private Ressource newRessource (String name, byte[] bytes){ Ressource r = new Ressource(); r.name = name; r.bytes = bytes; r.etag = sha1(bytes); r.mime = servletConfig.getServletContext().getMimeType(name); return r; } private class Ressource { private byte[] bytes; private String etag; private String mime; private String name; private Ressource store() { cache.put(name, this); log.info("Preload : " + name) ; return this; } public String toString() { String s = ""; try { s = new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { } return s; } private void send(HttpServletRequest req, HttpServletResponse resp) throws IOException{ String et = req.getHeader("If-None-Match"); if (et == null || !etag.equals(et)) { resp.setStatus(200); if (mime != null) resp.setContentType(mime); resp.setContentLength(bytes.length); resp.setHeader("ETag", etag); resp.getOutputStream().write(bytes); } else { resp.setStatus(304); } } } } private String buildScript(URIParser up, String cred){ StringBuffer sb = new StringBuffer(); sb.append("\n<script type=\"text/javascript\">\n"); sb.append("APPLICATIONPREFIX = \"").append(up.appPrefix).append("\";\n"); sb.append("if (!window[APPLICATIONPREFIX]) window[APPLICATIONPREFIX] = {}\n"); sb.append("window[APPLICATIONPREFIX].SERVERDATA = {\n"); sb.append("uri:["); for(int i = 0; i < up.uri.length; i++) sb.append("\"").append(up.uri[i]).append("\"") .append(i != up.uri.length - 1 ? ", " : "],\n"); sb.append("prefixeApp:\"").append(up.appPrefix).append("\",\n"); sb.append("contextPath:\"").append(contextPath).append("\",\n"); sb.append("nomApp:\"").append(up.appName).append("\",\n"); sb.append("serverBuild:\"").append(up.serverBuild).append("\",\n"); sb.append("byeAndBack:\"").append(byeAndBack).append("\",\n"); sb.append("credential:").append(cred).append("\n};\n"); Ressources.Ressource c = ressources.get("/fwk_components/init.js"); if (c != null){ String s = c.toString(); int i = s.indexOf("/*****/"); if (i == -1) i = s.length(); sb.append("appi".equals(up.ext()) ? s.substring(0, i) : s); } sb.append("\n</script>\n"); return sb.toString(); } private URIParser getURIParser(String uri) throws ServletException { URIParser up = null; try { up = (URIParser)uriParserClass.newInstance(); } catch (Exception e) { throw new ServletException("La ressource " + uri + " n'est pas disponible"); } if (uri == null) uri = ""; up.uri = uri.split("/"); String x = up.uri[up.uri.length - 1]; int k = x.lastIndexOf('.'); up.appName = k != -1 ? x.substring(0, k) : x; up.ext = k != -1 ? x.substring(k + 1) : ""; up.contextPath = contextPath + "/"; up.serverBuild = build; return up; } private static final String startGen = "\n<!-- start generated -->\n"; private static final String endGen = "\n<!-- end generated -->\n"; private static final String tagStart = "<!--APPLICATIONPREFIX=\""; private static final String tagEnd = "-->"; private static final String appHead1 = "<head>\n<base href=\""; private Ressources.Ressource pageText(String uri) throws ServletException { URIParser up = getURIParser(uri); String cred = up.credential(); if (cred == null) return null; String name = "/apps/" + up.appName + ".html"; Ressources.Ressource c = ressources.get(name); if (c == null) throw new ServletException("La ressource " + name + " n'est pas disponible"); String s = c.toString(); StringBuffer sb = new StringBuffer(); boolean ok = false; int tsl = tagStart.length(); int i = s.indexOf(tagStart); if (i != -1) { // tag APPLICATIONPREFIX trouvé - insertion du script int j = s.indexOf(tagEnd, i); if (j != -1) { String com = s.substring(i, j); int l = com.indexOf("\"", tsl); up.appPrefix = l != -1 ? com.substring(tsl, l) : "APP"; String ip = uri.endsWith(".appi") ? "/i/" : "/p/"; if ("appx".equals(up.ext())) { String p = "/" + uri.substring(0, uri.length() - "appx".length()) + "appcache"; sb.append("<html manifest=\"").append(contextPath).append(p).append("\">\n"); } else sb.append("<html>\n"); sb.append(appHead1).append(contextPath).append(ip).append(build()).append("/\">\n"); sb.append(s.substring(0, j + tagEnd.length())); sb.append(startGen); sb.append(buildScript(up, cred)); sb.append(endGen); sb.append(s.substring(j + tagEnd.length(), s.length())); ok = true; } } else { sb.append(s); ok = true; } if (!ok) throw new ServletException("La ressource " + name + " n'est pas disponible"); byte[] ret = null; try { ret = sb.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } Ressources.Ressource c2 = ressources.newRessource("/" + uri, ret); return c2; } private void serveFile(HttpServletRequest req, HttpServletResponse resp, String name) throws IOException { Ressources.Ressource c = ressources.get(name); if (c == null) resp.sendError(404, "La ressource " + name + " n'est pas disponible"); else c.send(req, resp); } private void serveSw(HttpServletRequest req, HttpServletResponse resp) throws IOException { Ressources.Ressource c = ressources.get("/fwk_components/_sw.js"); if (c == null) { resp.sendError(404, "La ressource /_sw.js n'est pas disponible"); return; } String p1 = "\"" + contextPath + "/p/" + build() ; String p2 = "\"" + contextPath ; StringBuffer sb = new StringBuffer(); sb.append("APPBUILD = \"").append(build()).append("\";\n"); sb.append("RESSOURCES = [\n"); for(String n : ressources.getAllNames()) sb.append(n.endsWith(".appa") ? p2 : p1).append(n).append("\",\n"); sb.append("];\n"); sb.append(c.toString()); Ressources.Ressource c2 = ressources.newRessource("sw.js", sb.toString().getBytes("UTF-8")); c2.send(req, resp); } private void serveAppCache(HttpServletRequest req, HttpServletResponse resp, String u) throws IOException { URIParser up = null; try { up = getURIParser(u); } catch (ServletException e) { throw new IOException(e); } String cred = up.credential(); if (cred == null) { resp.sendError(405, "Identification non reconnue pour accéder à /" + u + ".appcache"); return; } String p1 = "" + contextPath + "/p/" + build() ; String p2 = "" + contextPath + "/"; StringBuffer sb = new StringBuffer(); sb.append("CACHE MANIFEST\n\n# ").append(build()).append("\n\nCACHE:\n"); for(String n : ressources.getAllNames()) { if (n.endsWith(".appa")) sb.append(p2).append(n.substring(1, n.length() - 1)).append("x\n"); else sb.append(p1).append(n).append("\n"); } Ressources.Ressource c2 = ressources.newRessource("g.appcache", sb.toString().getBytes("UTF-8")); c2.send(req, resp); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String ctp = contextPath; String uri = req.getRequestURI().substring(ctp.length()); try { if (uri.equals("/sw_js")) { serveSw(req, resp); return; } if (uri.endsWith(".appcache")){ String u = uri.substring(1, uri.length()); // enlève le / du début serveAppCache(req, resp, u); return; } if (uri.startsWith("/p/") || uri.startsWith("/i/")) { int i = uri.indexOf('/', 3); // isoler la version : /p/1.3/xx... ou /p/xx.. String u = i == -1 ? uri.substring(2) : uri.substring(i); serveFile(req, resp, u); return; } if (uri.endsWith(".appi") || uri.endsWith(".appa") || uri.endsWith(".apps") || uri.endsWith(".appx")) { String u = uri.substring(1, uri.length()); // enleve / du début Ressources.Ressource c = pageText(u); if (c == null) resp.sendError(405, "NOTAUTH"); else c.send(req, resp); return; } ressources.newRessource("build.txt", build().getBytes("UTF-8")).send(req, resp); } catch(Exception e) { resp.sendError(404, "La ressource " + uri + " n'est pas disponible"); } } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } private static byte[] bytesFromStream(InputStream is) throws IOException { if (is == null) return null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int l = 0; while((l = is.read(buf)) > 0) bos.write(buf, 0, l); is.close(); bos.flush(); byte[] bytes = bos.toByteArray(); bos.close(); return bytes; } /** * Digest sha1 retourné en hexa d'un byte[] * @param b * @return */ private String sha1(byte[] b) { try { return b == null ? "" : bytesToHex(digestSHA1(b)); } catch (Exception e) { return ""; } } /** * Digest SHA-1 d'un byte[] retourné en byte[] * @param x * @return * @throws Exception */ private byte[] digestSHA1(byte[] x) { if (x == null) return null; try { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x); return d.digest(); } catch (Exception e) { return null; } } private static final char[] hexArray = "0123456789abcdef".toCharArray(); /** * Retourne en String la représentation en hexa d'un byte[] * @param bytes * @return */ private String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } private Class<?> hasClass(String name, Class<?> type) throws ServletException{ try { Class<?> c = Class.forName(name); if (c != type && !type.isAssignableFrom(c)) throw new Exception("x"); return c; } catch (Exception e) { String msg1 = "La classe " + name + " doit exister et étendre (ou être) la classe " + type.getCanonicalName(); log.log(Level.SEVERE, msg1); throw new ServletException(msg1, e); } } }
public class Linkedlist { Integer val; Linkedlist next; Linkedlist(Integer value){ val=value; } }
package com.mx.profuturo.bolsa.context; import com.mx.profuturo.bolsa.security.AntiSamyFilter; import com.mx.profuturo.bolsa.security.GrantingUserSettings; import com.mx.profuturo.bolsa.session.SessionListener; import com.mx.profuturo.bolsa.util.mockclient.MockClient; import com.mx.profuturo.bolsa.util.mockclient.MockClientImpl; import com.mx.profuturo.bolsa.util.mockclient.MockHelper; import com.mx.profuturo.bolsa.util.restclient.RestClient; import com.mx.profuturo.bolsa.util.restclient.RestClientImpl; import com.mx.profuturo.bolsa.util.restclient.interceptor.LoggingRestClient; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.ArrayList; import java.util.List; /** * Created by lUiSm on 4/25/16. */ @Configuration public class TestContext extends WebMvcConfigurerAdapter { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate= new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new LoggingRestClient()); restTemplate.setInterceptors(interceptors); return restTemplate; } @Bean(name ="messageSource") public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasenames("classpath:/locale/global/messages","classpath:/locale/global/messages_uri","classpath:/locale/demo/messages","classpath:/locale/payments/messages","classpath:/locale/exceptions/messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public RestClient restClient(){ return new RestClientImpl(); } @Bean public MockClient mockClient() { return new MockClientImpl(); } @Bean public MockHelper mockErrorHelper() { return new MockHelper(); } @Bean public AntiSamyFilter antiSamyFilter() { return new AntiSamyFilter(); } @Bean public GrantingUserSettings grantingUserSettings(){ return new GrantingUserSettings(); } @Bean public SessionListener sessionListener(){return new SessionListener();} }
package com.qgil.mapper; import com.qgil.pojo.QgilLvcg; import com.qgil.pojo.QgilLvcgExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface QgilLvcgMapper { int countByExample(QgilLvcgExample example); int deleteByExample(QgilLvcgExample example); int deleteByPrimaryKey(Long id); int insert(QgilLvcg record); int insertSelective(QgilLvcg record); List<QgilLvcg> selectByExample(QgilLvcgExample example); QgilLvcg selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") QgilLvcg record, @Param("example") QgilLvcgExample example); int updateByExample(@Param("record") QgilLvcg record, @Param("example") QgilLvcgExample example); int updateByPrimaryKeySelective(QgilLvcg record); int updateByPrimaryKey(QgilLvcg record); }
package com.accp.pub.pojo; import java.util.Date; public class Feedback { private Integer fid; private Integer taskid; private Integer npid; private String tname; private Integer uid; private String uname; private String fcontent; private Integer frid; private String funame; private Date futime; private String remark; public Integer getFid() { return fid; } public void setFid(Integer fid) { this.fid = fid; } public Integer getTaskid() { return taskid; } public void setTaskid(Integer taskid) { this.taskid = taskid; } public Integer getNpid() { return npid; } public void setNpid(Integer npid) { this.npid = npid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname == null ? null : tname.trim(); } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname == null ? null : uname.trim(); } public String getFcontent() { return fcontent; } public void setFcontent(String fcontent) { this.fcontent = fcontent == null ? null : fcontent.trim(); } public Integer getFrid() { return frid; } public void setFrid(Integer frid) { this.frid = frid; } public String getFuname() { return funame; } public void setFuname(String funame) { this.funame = funame == null ? null : funame.trim(); } public Date getFutime() { return futime; } public void setFutime(Date futime) { this.futime = futime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } }
package display; import javax.swing.*; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.*; public class DisplayHighScore { public static void createHighScoreWindow() { JFrame frame; String title = "HighScore"; int width = 300; int height = 200; frame = new JFrame(title); frame.setSize(width, height); frame.setVisible(true); frame.setFocusable(true); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLocationRelativeTo(null); File source = new File("resources/others/score.save"); SortedSet<Integer> scores = new TreeSet<>(); if (source.exists()) { try (ObjectInputStream inputStream = new ObjectInputStream( new BufferedInputStream( new FileInputStream( new File("resources/others/score.save"))))) { scores = (SortedSet<Integer>) inputStream.readObject(); } catch (Exception e) { e.printStackTrace(); } } StringBuilder textBuilder = new StringBuilder(); List<Integer> scoresList = new ArrayList<>(); scoresList.addAll(scores); System.out.println(scoresList.size()); for (int i = scoresList.size() - 1, j = 1; (i >= 0) && (i >= scoresList.size() - 5); i--, j++) { textBuilder.append(String.format("%d. ", j)); textBuilder.append(scoresList.get(i)); textBuilder.append((System.getProperty("line.separator"))); } JTextPane paneScoreText = new JTextPane(); paneScoreText.setText(textBuilder.toString()); frame.add(paneScoreText); } }
package bankBusiness.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import bankBusiness.src.Account; public class AccountTest { private Account account; @Before public void setUp() { account = new Account(10000); } @Test public void testAccount() throws Exception { /* 생성자 테스트 */ } @Test public void testGetBalance() throws Exception { /*if(account.getBalance() != 10000) { fail("getBalance() => " + account.getBalance() ); }*/ assertEquals("10000원으로 계좌 생성 후 잔고 조회", 10000, account.getBalance()); account = new Account(1000); assertEquals("1000원으로 계좌 생성 후 잔고 조회", 1000, account.getBalance()); account = new Account(0); assertEquals("0원으로 계좌 생성 후 잔고 조회", 0, account.getBalance()); } @Test public void testDeposit() throws Exception { account.deposit(1000); assertEquals("10000원으로 계좌 생성 후, 1000원 입금", 11000, account.getBalance()); } @Test public void testWithdraw() throws Exception { account.withdraw(1000); assertEquals("10000원으로 계좌 생성 후, 1000원 출금", 9000, account.getBalance()); } }
package cn.com.ykse.santa.web.controller.action; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by youyi on 2016/1/11. */ @Controller public class SecurityController{ @RequestMapping(value = "/login") public String loginPage(){ return "login"; } @RequestMapping(value = "/403") public String noAuthPage(){ return "403"; } @RequestMapping(value = "/503") public String serverErrPage(){ return "503"; } }
package com.codementor.android.starwarsbattlefrontcommunity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.codementor.android.starwarsbattlefrontcommunity.model.Post; import com.codementor.android.starwarsbattlefrontcommunity.model.Topic; import com.codementor.android.starwarsbattlefrontcommunity.view.PostViewAdapter; import java.util.ArrayList; import java.util.List; /** * Created by tonyk_000 on 12/18/2015. */ public class TopicFragment extends Fragment { private static final String ARGS_TOPIC = "topic"; private RecyclerView mRecyclerView; private PostViewAdapter mViewAdapter; private List<Post> mPosts; private Topic mTopic; public static TopicFragment newInstance(Topic topic){ Bundle args = new Bundle(); args.putParcelable(ARGS_TOPIC, topic); TopicFragment topicFragment = new TopicFragment(); topicFragment.setArguments(args); return topicFragment; } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); mTopic = getArguments().getParcelable(ARGS_TOPIC); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ final View v = inflater.inflate(R.layout.fragment_topic,container,false); List<Post> posts = populateTopic(); if (savedInstanceState == null) { mRecyclerView = (RecyclerView) v.findViewById(R.id.rv_thread_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity())); mViewAdapter = new PostViewAdapter(posts); mRecyclerView.setAdapter(mViewAdapter); } return v; } public List<Post> populateTopic(){ mPosts = new ArrayList<>(); for (int i = 0; i < 3; i++){ Post post = mTopic.getPost(); mPosts.add(post); // mPost = mPosts.get(i); -- not sure why this returns out of bounds } return mPosts; } }
package com.lin.paper.dao; /** * 用户信息数据操作接口 * @ * @date 2018年1月18日下午4:47:46 * @version 1.0 */ public interface UserDao { }
package com.sales.mapper; import com.sales.entity.SalesPlanMasterEntity; import java.util.List; import java.util.Map; public interface SalesPlanMasterMapper { List<SalesPlanMasterEntity> findList(Map<String, Object> params); SalesPlanMasterEntity findInfo(Map<String, Object> params); Integer doInsert(SalesPlanMasterEntity salesPlanMasterEntity); Integer doUpdate(SalesPlanMasterEntity salesPlanMasterEntity); Integer doDelete(int salesPlanId); }
package com.deltastuido.user; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; @Named @SessionScoped public class MyProjects extends UserProjectsFace implements Serializable { private static final long serialVersionUID = 1L; @Inject @Named("who") private Instance<User> user; @Override protected User getUser() { return user.get(); } }
package jp.smartcompany.job.filter; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Xiao Wenpeng */ @Order(1) @Component public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException { String origin = req.getHeader("Origin"); if(origin == null) { origin = req.getHeader("Referer"); } resp.setHeader("Access-Control-Allow-Credentials","true"); resp.setHeader("Access-Control-Allow-Origin", origin); if(RequestMethod.OPTIONS.toString().equals(req.getMethod())) { String allowMethod = req.getHeader("Access-Control-Request-Method"); String allowHeaders = req.getHeader("Access-Control-Request-Headers"); resp.setHeader("Access-Control-Allow-Methods", allowMethod); // 允许浏览器在预检请求成功之后发送的实际请求方法名 resp.setHeader("Access-Control-Allow-Headers", allowHeaders); // 允许浏览器发送的请求消息头 } chain.doFilter(req, resp); } }
package controllers; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.Stage; import tools.AuthTool; import tools.PropertyTool; import java.io.IOException; /** * Controller for loading the login page. */ public class LoginController { @FXML private AnchorPane loginPane; @FXML private PasswordField passwordField; /** * SignUpController. */ private SignUpController signUpController; /** * Parent. */ private Parent fxmlParent; /** * SignUpStage. */ private Stage signUpStage; /** * Check that password exist. */ private boolean checkPasswordIsExist = false; @FXML private void initialize() { initSignUp(); } /** * Init sign up stage. */ private void initSignUp() { try { FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(getClass().getResource("/views/NewPassword.fxml")); fxmlParent = fxmlLoader.load(); signUpController = fxmlLoader.getController(); } catch (IOException e) { e.printStackTrace(); } } /** * Creates main form. */ private void createMainForm() { try{ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getClassLoader().getResource("views/Main.fxml")); Parent root1 = (Parent) fxmlLoader.load(); Stage stage = new Stage(); stage.initModality(Modality.NONE); stage.setResizable(false); stage.setTitle("Password Storage"); stage.setScene(new Scene(root1)); passwordField.getScene().getWindow().hide(); stage.show(); } catch (Exception e) { e.printStackTrace(); showAlert(); } } /** * Login Button. * @param actionEvent actionEvent */ public void loginButton(ActionEvent actionEvent) { PropertyTool pt = new PropertyTool(); if (!pt.isPropertyExist("password")) { showSignUp(); } if (AuthTool.isPasswordCorrect(passwordField.getText())) { createMainForm(); } else { showAlert(); } } /** * Show sign up form. */ private void showSignUp() { if (signUpStage == null) { signUpStage = new Stage(); signUpStage.setTitle("Enter new password"); signUpStage.setResizable(false); signUpStage.setScene(new Scene(fxmlParent)); signUpStage.initModality(Modality.WINDOW_MODAL); signUpStage.initOwner(passwordField.getScene().getWindow()); } signUpStage.showAndWait(); } /** * Show alert window. */ private void showAlert() { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Wrong Password"); alert.setHeaderText("Password is incorrect"); alert.setContentText("Check your pass"); alert.showAndWait(); } /** * When mouse moves to Login Pane. * @param mouseEvent mouse Event */ public void onMouseMove(MouseEvent mouseEvent) { if (!checkPasswordIsExist) { PropertyTool pt = new PropertyTool(); if (!pt.isFileExist() || (!pt.isPropertyExist("password") && pt.isEmpty())) { showSignUp(); } checkPasswordIsExist = true; } } }
package com.liufeng.domian.dto.request; import com.fasterxml.jackson.annotation.JsonFormat; import com.liufeng.common.utils.DateUtils; import com.liufeng.domian.dto.base.BasePageQuery; import com.liufeng.domian.entity.Dict; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotNull; import java.util.Date; @Data @EqualsAndHashCode(callSuper = true) //生成的方法中包含父类的属性 @ApiModel(description = "查询字典表DTO") public class DictGetRequestDTO extends BasePageQuery { @ApiModelProperty(value = "字典表type值",required = true) @NotNull(message = "字典表类型属性不能为空") private String type; }
package com.revature.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.revature.controller.AuthenticationController; import com.revature.controller.Controller; import com.revature.controller.ReimbursementController; import com.revature.controller.UserController; import com.revature.exception.ExceptionMapper; import io.javalin.Javalin; import io.javalin.http.staticfiles.Location; public class ERSApplication { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(ERSApplication.class); Javalin app = Javalin.create(config -> { // 'enableCors' enabling other hosts/ports to be able to use the // server config.enableCorsForAllOrigins(); // 'addStaticFiles' to add html, css, and/orr js inside the maven // project to interact with them config.addStaticFiles("static", Location.CLASSPATH); }); app.before(ctx -> { logger.info(ctx.method() + " request recieved to the " + ctx.path() + " endpoint"); }); // mapController() take in application and multiple controllers to map // each endpoint to the 'app' mapControllers(app, new AuthenticationController(), new ReimbursementController(), new UserController()); ExceptionMapper mapper = new ExceptionMapper(); mapper.mapExceptions(app); app.start(8080); } // ... operator = zero or more String object may be passed as the // argument(s) public static void mapControllers(Javalin app, Controller... controllers) { for (int i = 0; i < controllers.length; i++) { controllers[i].mapEndpoints(app); } } }
/** * Author: obullxl@gmail.com * Copyright (c) 2004-2013 All Rights Reserved. */ package com.github.obullxl.lang.web.crawl; import com.github.obullxl.lang.utils.GroovyUtils; /** * Groovy爬虫工具类 * * @author obullxl@gmail.com * @version $Id: GroovyCrawlUtils.java, V1.0.1 2013年12月10日 下午4:40:10 $ */ public class GroovyCrawlUtils { /** * 获取Groovy脚本爬虫 */ public static WebCrawler findCrawler(String path) { try { Class<?> clz = GroovyUtils.load(path, WebCrawler.class.getClassLoader()); return (WebCrawler) clz.newInstance(); } catch (Exception e) { throw new RuntimeException("获取Web爬虫异常[" + path + "].", e); } } }
package cn.edu.hebtu.software.sharemate.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Looper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.List; import java.util.Timer; import java.util.TimerTask; import cn.edu.hebtu.software.sharemate.Bean.NoteBean; import cn.edu.hebtu.software.sharemate.Bean.UserBean; import cn.edu.hebtu.software.sharemate.R; import cn.edu.hebtu.software.sharemate.tools.TransObjectToWeb; import cn.edu.hebtu.software.sharemate.tools.UpLoadUtil1; public class FabuActivity extends AppCompatActivity { private PopupWindow window = null; private LinearLayout root = null; private String path=null; private int typeid; private int userId; private List<Integer> type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fabu); //显示图片 final Intent intent = getIntent(); final String code = intent.getStringExtra("code"); userId = intent.getIntExtra("userId",0); type = intent.getIntegerArrayListExtra("type"); ImageView imageView = findViewById(R.id.imageView); if (code != null) { if (code.equals("1")) { String picturePath=intent.getStringExtra("lujing"); path=picturePath; Bitmap bitmap1 = BitmapFactory.decodeFile(picturePath); imageView.setImageBitmap(bitmap1); } else if (code.equals("2")) { String picturePath = intent.getStringExtra("pic1"); path=picturePath; Log.e("code",code); Bitmap bitmap2 = BitmapFactory.decodeFile(picturePath); imageView.setImageBitmap(bitmap2); } else { Log.e("picture", "图片未获取到"); } } //退出发布页面 root = findViewById(R.id.fabu_root); window = new PopupWindow(root, RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT); Button btnShare = findViewById(R.id.guanbi); btnShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(window.isShowing()){ window.dismiss(); }else{ showPopupWindow(root); addBackgroundAlpha(0.7f); } } }); // Button btnShare1 = findViewById(R.id.cuncaogao); // btnShare1.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if(window.isShowing()){ // window.dismiss(); // }else{ // showPopupWindow(root); // addBackgroundAlpha(0.7f); // } // } // }); //获取话题 LinearLayout linearLayout=findViewById(R.id.btn_topic); linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTopicPopupWindow(); } }); //获取位置 LinearLayout linearLayout1=findViewById(R.id.add_position); linearLayout1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPositionPopupWindow(); } }); //发布 Button btn=findViewById(R.id.fabu); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //传内容 new Thread(new Runnable() { @Override public void run() { //获取发布内容 UserBean userbean=new UserBean(userId); EditText EDdetial=(EditText) findViewById(R.id.detial); String detial=EDdetial.getText().toString(); EditText EDtitle=(EditText)findViewById(R.id.wenzi_title); String title=EDtitle.getText().toString(); NoteBean noteBean=new NoteBean(detial,title,userbean,typeid); Log.e("detial",noteBean.getNoteDetail()); TransObjectToWeb toWeb=new TransObjectToWeb(getResources().getString(R.string.server_path)); boolean flag=toWeb.sendToWeb(noteBean); if (flag){ Looper.prepare(); Log.e("success","对象传输成功"); Looper.loop(); }else{ Looper.prepare(); Log.e("fail","网络繁忙"); } } }).start(); //传图片 TimerTask task = new TimerTask() { @Override public void run() { UpLoadImage(path); } }; Timer timer = new Timer(); timer.schedule(task, 3000); Log.e("fabu_btn",path); //发布提示 showtoast(); //显示分享界面 sharepopupWindow(path); addBackgroundAlpha(0.7f); } }); } public void showPositionPopupWindow(){ LayoutInflater inflater =getLayoutInflater(); View view = inflater.inflate(R.layout.position_popupwindow,null); window.setContentView(view); final Button btn1=view.findViewById(R.id.button1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn1.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn2=view.findViewById(R.id.button2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn2.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn3=view.findViewById(R.id.button3); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn3.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn4=view.findViewById(R.id.button4); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn4.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn5=view.findViewById(R.id.button5); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn5.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn6=view.findViewById(R.id.button6); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn6.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn7=view.findViewById(R.id.button7); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn7.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn8=view.findViewById(R.id.button8); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn8.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn9=view.findViewById(R.id.button9); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn9.getText().toString(); textView.setText(position); window.dismiss(); } }); final Button btn10=view.findViewById(R.id.button10); btn10.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_postion); String position=btn10.getText().toString(); textView.setText(position); window.dismiss(); } }); window.showAtLocation(root, Gravity.BOTTOM,0,0); } //展示topicpopupwindow private void showTopicPopupWindow(){ LayoutInflater inflater =getLayoutInflater(); View view = inflater.inflate(R.layout.topic_popupwindow,null); window.setContentView(view); final Button button1=view.findViewById(R.id.meizhuang1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button1.getText().toString(); textView.setText(tips); typeid=1; window.dismiss(); } }); final Button button2=view.findViewById(R.id.meizhuang2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button2.getText().toString(); textView.setText(tips); typeid=1; window.dismiss(); } }); final Button button3=view.findViewById(R.id.meizhuang3); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button3.getText().toString(); textView.setText(tips); typeid=1; window.dismiss(); } }); final Button button4=view.findViewById(R.id.meizhuang4); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button4.getText().toString(); textView.setText(tips); typeid=1; window.dismiss(); } }); final Button button5=view.findViewById(R.id.lvxing1); button5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button5.getText().toString(); textView.setText(tips); typeid=2; window.dismiss(); } }); final Button button6=view.findViewById(R.id.lvxing2); button6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button6.getText().toString(); textView.setText(tips); typeid=2; window.dismiss(); } }); final Button button7=view.findViewById(R.id.lvxing3); button7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button7.getText().toString(); textView.setText(tips); typeid=2; window.dismiss(); } }); final Button button8=view.findViewById(R.id.lvxing4); button8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button8.getText().toString(); textView.setText(tips); typeid=2; window.dismiss(); } }); final Button button9=view.findViewById(R.id.yundong1); button9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button9.getText().toString(); textView.setText(tips); typeid=3; window.dismiss(); } }); final Button button10=view.findViewById(R.id.yundong2); button10.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button10.getText().toString(); textView.setText(tips); typeid=3; window.dismiss(); } }); final Button button11=view.findViewById(R.id.yundong3); button11.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button11.getText().toString(); textView.setText(tips); typeid=3; window.dismiss(); } }); final Button button12=view.findViewById(R.id.meishi1); button12.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button12.getText().toString(); textView.setText(tips); typeid=4; window.dismiss(); } }); final Button button13=view.findViewById(R.id.meishi2); button13.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button13.getText().toString(); textView.setText(tips); typeid=4; window.dismiss(); } }); final Button button14=view.findViewById(R.id.meishi3); button14.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button14.getText().toString(); textView.setText(tips); typeid=4; window.dismiss(); } }); final Button button15=view.findViewById(R.id.meishi4); button15.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button15.getText().toString(); textView.setText(tips); typeid=4; window.dismiss(); } }); final Button button16=view.findViewById(R.id.keji1); button16.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button16.getText().toString(); textView.setText(tips); typeid=5; window.dismiss(); } }); final Button button17=view.findViewById(R.id.keji2); button17.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button17.getText().toString(); textView.setText(tips); typeid=5; window.dismiss(); } }); final Button button18=view.findViewById(R.id.keji3); button18.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button18.getText().toString(); textView.setText(tips); typeid=5; window.dismiss(); } }); final Button button19=view.findViewById(R.id.keji4); button19.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button19.getText().toString(); textView.setText(tips); typeid=5; window.dismiss(); } }); final Button button20=view.findViewById(R.id.dongman1); button20.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button20.getText().toString(); textView.setText(tips); typeid=6; window.dismiss(); } }); final Button button21=view.findViewById(R.id.dongman2); button21.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button21.getText().toString(); textView.setText(tips); typeid=6; window.dismiss(); } }); final Button button22=view.findViewById(R.id.dongman3); button22.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button22.getText().toString(); textView.setText(tips); typeid=6; window.dismiss(); } }); final Button button23=view.findViewById(R.id.dongman4); button23.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView textView=findViewById(R.id.wenzi_topic); String tips=button23.getText().toString(); textView.setText(tips); typeid=6; window.dismiss(); } }); window.showAtLocation(root, Gravity.BOTTOM,0,0); } //保存退出popupwindow private void showPopupWindow(LinearLayout root){ //设置显示的视图 LayoutInflater inflater =getLayoutInflater(); View view = inflater.inflate(R.layout.back_popupwindow_layout,null); Button btnCamera = view.findViewById(R.id.btn_save); Button btnPhoto = view.findViewById(R.id.btn_dissave); Button btnCancel = view.findViewById(R.id.btn_cancel1); //为弹出框中的每一个按钮 ClickListener listener = new ClickListener(); btnCamera.setOnClickListener(listener); btnPhoto.setOnClickListener(listener); btnCancel.setOnClickListener(listener); //将自定义的视图添加到 popupWindow 中 window.setContentView(view); //控制 popupwindow 再点击屏幕其他地方时自动消失 window.setFocusable(true); window.setOutsideTouchable(true); window.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //在弹窗消失时调用 addBackgroundAlpha(1f); } }); //显示 popupWindow 设置 弹出框的位置 window.showAtLocation(root, Gravity.BOTTOM,0,0); } private class ClickListener implements View.OnClickListener{ @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_save: addBackgroundAlpha(1f); Intent intent1=new Intent(); intent1.setClass(FabuActivity.this,MainActivity.class); intent1.putExtra("userId",intent1.getIntExtra("userId",0)); intent1.putIntegerArrayListExtra("type",intent1.getIntegerArrayListExtra("type")); intent1.putExtra("flag","main"); startActivity(intent1); break; case R.id.btn_dissave: addBackgroundAlpha(1f); Intent intent2=new Intent(); intent2.setClass(FabuActivity.this,MainActivity.class); intent2.putExtra("userId",intent2.getIntExtra("userId",0)); intent2.putIntegerArrayListExtra("type",intent2.getIntegerArrayListExtra("type")); intent2.putExtra("flag","main"); startActivity(intent2); break; case R.id.btn_cancel1: window.dismiss(); break; } } } // 弹出选项框时为背景加上透明度 private void addBackgroundAlpha(float alpha){ WindowManager.LayoutParams params = getWindow().getAttributes(); params.alpha = alpha; getWindow().setAttributes(params); } //向服务器端发送图片 public void UpLoadImage(String path){ String url=getResources().getString(R.string.server_path); UpLoadUtil1 upLoadUtil = new UpLoadUtil1(url); upLoadUtil.execute(path); Log.e("upLoadImage","uploadimage"); } //显示toast public void showtoast(){ final Toast toastTip1 = Toast.makeText(FabuActivity.this, "后台上传中,请稍后……", Toast.LENGTH_LONG); final Toast toastTip2 = Toast.makeText(FabuActivity.this, "笔记已成功发布喽", Toast.LENGTH_LONG); toastTip1.setGravity(Gravity.CENTER, 0, 0); toastTip2.setGravity(Gravity.CENTER, 0, 0); toastTip1.show(); toastTip2.show(); } //分享的弹出框 public void sharepopupWindow(String path){ LayoutInflater inflater =getLayoutInflater(); View view = inflater.inflate(R.layout.share_popupwindow,null); String picturePath=path; Log.e("picpath",picturePath); final ImageView imageView=view.findViewById(R.id.share_lianjie); final ImageView imageView1=view.findViewById(R.id.share_pic); Bitmap bitmap2 = BitmapFactory.decodeFile(picturePath); imageView.setImageBitmap(bitmap2); imageView1.setImageBitmap(bitmap2); window.setContentView(view);//将自定义的视图添加到 popupWindow 中 //控制 popupwindow 再点击屏幕其他地方时自动消失 window.setFocusable(true); window.setOutsideTouchable(true); addBackgroundAlpha(0.7f); final Intent intent=getIntent(); final TextView textView=view.findViewById(R.id.quxiao); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addBackgroundAlpha(1f); Intent intent1=new Intent(); intent1.setClass(FabuActivity.this,MainActivity.class); intent1.putExtra("userId",intent.getIntExtra("userId",0)); intent1.putIntegerArrayListExtra("type",intent.getIntegerArrayListExtra("type")); intent1.putExtra("flag","main"); startActivity(intent1); } }); window.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //在弹窗消失时调用 addBackgroundAlpha(1f); Intent intent1=new Intent(); intent1.setClass(FabuActivity.this,MainActivity.class); intent1.putExtra("userId",intent.getIntExtra("userId",0)); intent1.putIntegerArrayListExtra("type",intent.getIntegerArrayListExtra("type")); intent1.putExtra("flag","main"); startActivity(intent1); } }); //显示 popupWindow 设置 弹出框的位置 window.showAtLocation(root, Gravity.BOTTOM,0,0); } }
package smart.cache; import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import smart.config.AppConfig; import smart.entity.ExpressCompanyEntity; import smart.lib.Json; import smart.lib.express.FreeRule; import smart.lib.express.PriceRule; import smart.repository.ExpressCompanyRepository; import java.util.List; @Component public class ExpressCache { private static List<ExpressCompanyEntity> companies; private static ExpressCompanyRepository expressCompanyRepository; private static FreeRule freeRule; private static PriceRule priceRule; @PostConstruct public static synchronized void init() { companies = expressCompanyRepository.findAll(); var list = AppConfig.getJdbcTemplate().queryForList("select * from t_system where entity='shipping'"); String json; for (var map : list) { json = (String) map.get("value"); if (json.length() < 10) { continue; } switch ((String) map.get("attribute")) { case "freeRule" -> freeRule = Json.decode(json, FreeRule.class); case "priceRule" -> priceRule = Json.decode(json, PriceRule.class); } } if (freeRule == null) { freeRule = new FreeRule(); } if (priceRule == null) { priceRule = new PriceRule(); } } public static List<ExpressCompanyEntity> getCompanies() { return companies; } /** * 根据id获取快递公司名称 * * @param id 快递id * @return 快递公司名称 */ public static String getNameById(long id) { for (var c : companies) { if (c.getId() == id) { return c.getName(); } } return null; } public static FreeRule getFreeRule() { return freeRule; } public static PriceRule getPriceRule() { return priceRule; } @Autowired private void autowire(ExpressCompanyRepository expressCompanyRepository) { ExpressCache.expressCompanyRepository = expressCompanyRepository; } }
package smart.controller.admin.user; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import smart.entity.UserEntity; import smart.lib.AdminHelper; import smart.util.Helper; import smart.lib.Pagination; import smart.util.Validate; import smart.repository.UserRepository; import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import jakarta.transaction.Transactional; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; @Controller(value = "admin/user/user") @RequestMapping(path = "/admin/user/user") @Transactional public class User { @Resource UserRepository userRepository; @GetMapping(value = "edit") public ModelAndView getEdit(HttpServletRequest request) { long id = Helper.longValue(request.getParameter("id")); UserEntity user = userRepository.findById(id).orElse(null); if (user == null) { return AdminHelper.msgPage("用户不存在", "/admin/user/user/list", request); } ModelAndView modelAndView = Helper.newModelAndView("admin/user/user/edit", request); modelAndView.addObject("title", "用户信息"); modelAndView.addObject("user", user); return modelAndView; } @GetMapping(value = "list") public ModelAndView getIndex(HttpServletRequest request, @RequestParam(required = false) String name) { long page = Helper.longValue(request.getParameter("page"), 1); String sqlWhere = ""; Set<Object> params = new LinkedHashSet<>(); Map<String, String> query = new HashMap<>(); if (name != null) { name = name.trim(); if (name.length() > 0) { if (Validate.letterOrNumber(name, "") == null) { sqlWhere += " and name like ?"; params.add('%' + name + '%'); } else { sqlWhere += " and false"; } query.put("name", name); } } if (sqlWhere.startsWith(" and ")) { sqlWhere = " where " + sqlWhere.substring(4); } Pagination pagination = Pagination.newBuilder("select * from t_user" + sqlWhere + " order by id desc", params.toArray()) .page(request).query(query).build(); ModelAndView modelAndView = Helper.newModelAndView("admin/user/user/list", request); modelAndView.addObject("title", "会员列表"); modelAndView.addObject("name", name); modelAndView.addObject("pagination", pagination); modelAndView.addObject("rows", pagination.getRows(UserEntity.class)); return modelAndView; } }
/* * Ada Sonar Plugin * Copyright (C) 2010 Akram Ben Aissi * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.ada.gnat.metric; import java.util.ArrayList; import java.util.List; import org.sonar.plugins.ada.core.PluginAbstractExecutor; /** * The Class GnatMetricExecutor. */ public class GnatMetricExecutor extends PluginAbstractExecutor { /** The configuration. */ private GnatConfiguration configuration; /** * Instantiates a new executor. * * @param configuration * the configuration */ public GnatMetricExecutor(GnatConfiguration configuration) { this.configuration = configuration; } /** * @see org.sonar.plugins.ada.core.PluginAbstractExecutor#getCommandLine() */ @Override protected List<String> getCommandLine() { List<String> result = new ArrayList<String>(); result.add(configuration.getExecutable()); result.add(configuration.getDefaultArgument()); result.add(configuration.getDoNoteGenerateTextModifier()); result.add(configuration.getXmlOutputModifier()); result.add(configuration.getXmlOutputFileModifier()); result.add(configuration.getReportFile().toString()); String excludedPackages = configuration.getExcludedPackages(); if (excludedPackages != null) { result.add(configuration.getExcludePackagesModifier() + excludedPackages); } String ignoreDirectories = configuration.getIgnoredDirectories(); if (ignoreDirectories != null) { result.add(configuration.getIgnoreDirectoryModifier() + ignoreDirectories); } result.addAll(configuration.getSourceFiles()); addIncludesAndExtraArguments(result); return result; } /** * @param result */ private void addIncludesAndExtraArguments(List<String> result) { // Add include directories. Copy the directories to include in a ArrayList List<String> includeDirectories = new ArrayList<String>(configuration.getIncludeDirectories()); // if the option to automatically include source directories is set, we add the source directories to directories to include. if (configuration.isIncludeSourceDirectories()) { includeDirectories.addAll(configuration.getAutomaticalyIncludedDirectories()); } // The -cargs and -I option should be repeated for each directory to include. String includeDirectoryModifier = configuration.getIncludeDirectoryModifier(); for (String include : includeDirectories) { include(result, includeDirectoryModifier, include); } String includeLibraryModifier = configuration.getIncludeLibraryModifier(); for (String include : configuration.getIncludeLibraries()) { include(result, includeLibraryModifier, include); } for (String argument : configuration.getExtraArguments()) { result.add(argument); } } /** * @param result * @param includeDirectoryModifier * @param include */ private void include(List<String> result, String includeDirectoryModifier, String include) { String compilerArgumentModifier = configuration.getCompilerArgumentModifier(); result.add(compilerArgumentModifier); result.add(includeDirectoryModifier); result.add(include); } /** * @return the configuration */ public GnatConfiguration getConfiguration() { return configuration; } /** * @see org.sonar.plugins.ada.core.PluginAbstractExecutor#getExecutable() */ @Override protected String getExecutable() { return configuration.getExecutable(); } }
package dao; import java.util.List; import model.Course; public interface PlanDao { public List<Course> getCourses(String ssn); public Course getCourseByNo(String courseNo); }
package org.holoeverywhere.util; public interface PoolableManager<T extends Poolable<T>> { T newInstance(); void onAcquired(T element); void onReleased(T element); }
package com.decrypt.beeglejobsearch.ui.screens.product; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import com.decrypt.beeglejobsearch.data.storage.ProductDto; import com.decrypt.beeglejobsearch.di.DaggerService; import com.decrypt.beeglejobsearch.mvp.views.IProductView; import com.decrypt.beeglejobsearch.utils.ImageTransformation; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ProductView extends LinearLayout implements IProductView { public static final String TAG = "ProductView"; @BindView(com.decrypt.beeglejobsearch.R.id.product_name_txt) TextView mProductNameTxt; @BindView(com.decrypt.beeglejobsearch.R.id.product_description_txt) TextView mProductDescriptionTxt; @BindView(com.decrypt.beeglejobsearch.R.id.product_image) ImageView mProductImage; @BindView(com.decrypt.beeglejobsearch.R.id.product_count_txt) TextView mProductCountTxt; @BindView(com.decrypt.beeglejobsearch.R.id.product_price_txt) TextView mProductPriceTxt; @BindView(com.decrypt.beeglejobsearch.R.id.plus_btn) ImageButton mPlusBtn; @BindView(com.decrypt.beeglejobsearch.R.id.minus_btn) ImageButton mMinusBtn; @Inject ProductScreen.ProductPresenter mPresenter; @Inject Picasso mPicasso; public ProductView(Context context, AttributeSet attrs) { super(context, attrs); if(!isInEditMode()) { DaggerService.<ProductScreen.Component>getDaggerComponent(context).inject(this); } } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if(!isInEditMode()) { mPresenter.takeView(this); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if(!isInEditMode()) { mPresenter.dropView(this); } } @Override protected void onFinishInflate() { super.onFinishInflate(); ButterKnife.bind(this); // if(!isInEditMode()) { //// showViewFromState(); // } } //region =========================== IProductView ===================== @Override public void showProductView(final ProductDto product) { mProductNameTxt.setText(product.getProductName()); mProductDescriptionTxt.setText(product.getDescription()); mProductCountTxt.setText(String.valueOf(product.getCount())); if(product.getCount()>0){ mProductPriceTxt.setText(String.valueOf(product.getCount()*product.getPrice() + ".-")); } else { mProductPriceTxt.setText(String.valueOf(product.getPrice() + ".-")); } // TODO: 27.10.16 Picasso load from url Log.d(TAG, "showProductView: "+product.getImageUrl()); mPicasso.with(getContext()) .load(product.getImageUrl()) .networkPolicy(NetworkPolicy.OFFLINE) .transform(ImageTransformation.getTransformation(mProductImage)) .into(mProductImage, new Callback() { @Override public void onSuccess() { Log.e(TAG, "onSuccess: load from a cache"); } @Override public void onError() { Log.e(TAG, "onError: "); mPicasso.with(getContext()) .load(product.getImageUrl()) .transform(ImageTransformation.getTransformation(mProductImage)) // .centerCrop() .into(mProductImage); } }); } @Override public void updateProductCountView(ProductDto product) { mProductCountTxt.setText(String.valueOf(product.getCount())); if(product.getCount()>0){ Log.e(TAG, "updateProductCountView: -"+product.getCount()*product.getPrice()); mProductPriceTxt.setText(String.valueOf(product.getCount()*product.getPrice() + ".-")); } } @Override public boolean viewOnBackPressed() { return false; } //endregion //region =========================== Events ===================== @OnClick(com.decrypt.beeglejobsearch.R.id.plus_btn) public void clickPlus() { mPresenter.clickOnPlus(); } @OnClick(com.decrypt.beeglejobsearch.R.id.minus_btn) public void clickMinus() { mPresenter.clickOnMinus(); } //endregion }
package com.tencent.mm.ui.chatting.viewitems; import android.content.Intent; import android.view.View; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.s; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.storage.bd; import com.tencent.mm.storage.emotion.EmojiGroupInfo; import com.tencent.mm.storage.emotion.EmojiInfo; import com.tencent.mm.ui.chatting.c.a; import com.tencent.mm.ui.chatting.t$d; public class u$c extends t$d { public u$c(a aVar) { super(aVar); } public final void a(View view, a aVar, bd bdVar) { au auVar = (au) view.getTag(); au.HU(); if (c.isSDCardAvailable()) { EmojiInfo zi = ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zi(auVar.bXQ.field_imgPath); if (zi != null && !zi.aaq()) { Intent intent = new Intent(); intent.putExtra("custom_smiley_preview_md5", auVar.bXQ.field_imgPath); intent.putExtra("custom_to_talker_name", auVar.bXQ.field_talker); if (!(zi.field_catalog == EmojiGroupInfo.tcA || zi.field_catalog == EmojiGroupInfo.tcz || zi.field_catalog == EmojiGroupInfo.tcy)) { intent.putExtra("custom_smiley_preview_productid", zi.field_groupId); } intent.putExtra("msg_id", auVar.bXQ.field_msgSvrId); intent.putExtra("msg_content", auVar.bXQ.field_content); String str = auVar.bXQ.field_talker; intent.putExtra("msg_sender", s.fq(str) ? com.tencent.mm.model.bd.iB(auVar.bXQ.field_content) : str); d.b(this.tKy.tTq.getContext(), "emoji", ".ui.CustomSmileyPreviewUI", intent); h.mEJ.h(11592, new Object[]{Integer.valueOf(0)}); } } } }
package com.thoughtworks.data; /** * Created on 13-06-2018. */ public interface Mapper<S, D> { D map(S input); }
package com.yl.cd.web.handler; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; @Controller @Component("pushMsgHandler") public class PushMsgHandler extends TextWebSocketHandler{ // @Autowired // private SongService songService; @Override//做推送消息处理向客户端发送消息 public void afterConnectionEstablished(WebSocketSession session) throws Exception { // KuSong song= songService.pushSong(); // System.out.println(song); // session.sendMessage(new TextMessage("系统向你推荐歌曲 ===> "+song.getKuSongName())); session.sendMessage(new TextMessage("系统向你推荐 ===> ")); System.out.println("==================afterConnectionEstablished======================="); } }
package com.epam.multithreading; public class ThreadExp { public static void main(String[] args) throws InterruptedException { new Thread(()->{ try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread"); }).start(); System.out.println("Main"); } }
package com.smxknife.java2.serializable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; /** * @author smxknife * 2018/11/2 */ public class ManagerDeserializeDemo { public static void main(String[] args) { Manager e = null; try { FileInputStream fis = new FileInputStream("./manager.txt"); ObjectInputStream ois = new ObjectInputStream(fis); e = (Manager) ois.readObject(); ois.close(); fis.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (ClassNotFoundException e1) { System.out.println("manager class not found"); e1.printStackTrace(); } System.out.println("Deserialized Manager..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); System.out.println("StaticAttr: " + e.staticAttr); System.out.println("Class StaticAttr: " + Employee.staticAttr); System.out.println("identity: " + e.identity); System.out.println("position: " + e.position); } }