text
stringlengths
10
2.72M
/* * Copyright (C) 2015 Miquel Sas * * 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 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.server; import com.qtplaf.library.trading.server.feed.FeedListener; /** * Interface responsible to manage live feeds. * * @author Miquel Sas */ public interface FeedManager { /** * Add a feed listener to receive notificatios for its subscriptions. * * @param listener The feed listener to add. */ void addFeedListener(FeedListener listener); /** * Removes a feed listener from receiving notificatios for its subscriptions. * * @param listener The feed listener to remove. */ void removeFeedListener(FeedListener listener); }
/* * 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 servlet; import DataBase.DataBase; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.Customer; import util.PW5; /** * * @author wasat */ public class LogServelt extends HttpServlet { Customer user; public LogServelt() { user =new Customer(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String email = request.getParameter("customer_email"); String pwde = request.getParameter("customer_password"); String autologins = request.getParameter("auto_login"); DataBase userHandle = new DataBase(); System.out.println(email); System.out.println(pwde); try { if (userHandle.findByEmail(email) != null) { user = userHandle.findByEmail(email); String pass = PW5.getPW5(PW5.getPW5(pwde)); String i = user.getEmail(); String i1 = user.getPwd(); String i2 = user.getFname(); System.out.println("first if" + " " + i + " pwd :L" + i1 + "" + i2); if (user.getPwd().equals(pwde)) { System.out.println("2 if"); if (autologins != null && autologins.equals("on")) { System.out.println("3 if"); Cookie cookiE = new Cookie("LOGIN_EMAIL", email); cookiE.setMaxAge(60 * 60 * 24 * 7); response.addCookie(cookiE); } HttpSession session = request.getSession(); session.setAttribute("session", session); session.setAttribute("loginUser", user); session.setAttribute("isLogined", true); session.setAttribute("email", i); request.getRequestDispatcher("index.jsp").forward(request, response); } else { request.setAttribute("isLoginOk", "false"); request.getRequestDispatcher("userlogin.jsp").forward(request, response); } } else { request.setAttribute("isLoginOk", "false"); request.getRequestDispatcher("userlogin.jsp").forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.importer.repository; import static com.hedera.mirror.common.domain.entity.EntityType.CONTRACT; import static org.assertj.core.api.Assertions.assertThat; import com.google.protobuf.ByteString; import com.hedera.mirror.common.domain.entity.Entity; import com.hederahashgraph.api.proto.java.Key; import java.util.List; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; @RequiredArgsConstructor(onConstructor = @__(@Autowired)) class EntityRepositoryTest extends AbstractRepositoryTest { private static final RowMapper<Entity> ROW_MAPPER = rowMapper(Entity.class); private final EntityRepository entityRepository; @Test void nullCharacter() { Entity entity = domainBuilder.entity().customize(e -> e.memo("abc" + (char) 0)).persist(); assertThat(entityRepository.findById(entity.getId())).get().isEqualTo(entity); } @Test void publicKeyUpdates() { Entity entity = domainBuilder.entity().customize(b -> b.key(null)).persist(); // unset key should result in null public key assertThat(entityRepository.findById(entity.getId())) .get() .extracting(Entity::getPublicKey) .isNull(); // default proto key of single byte should result in empty public key entity.setKey(Key.getDefaultInstance().toByteArray()); entityRepository.save(entity); assertThat(entityRepository.findById(entity.getId())) .get() .extracting(Entity::getPublicKey) .isEqualTo(""); // invalid key should be null entity.setKey("123".getBytes()); entityRepository.save(entity); assertThat(entityRepository.findById(entity.getId())) .get() .extracting(Entity::getPublicKey) .isNull(); // valid key should not be null entity.setKey(Key.newBuilder() .setEd25519(ByteString.copyFromUtf8("123")) .build() .toByteArray()); entityRepository.save(entity); assertThat(entityRepository.findById(entity.getId())) .get() .extracting(Entity::getPublicKey) .isNotNull(); // null key like unset should result in null public key entity.setKey(null); entityRepository.save(entity); assertThat(entityRepository.findById(entity.getId())) .get() .extracting(Entity::getPublicKey) .isNull(); } /** * This test verifies that the Entity domain object and table definition are in sync with the entity_history table. */ @Test void history() { Entity entity = domainBuilder.entity().persist(); jdbcOperations.update("insert into entity_history select * from entity"); List<Entity> entityHistory = jdbcOperations.query("select * from entity_history", ROW_MAPPER); assertThat(entityRepository.findAll()).containsExactly(entity); assertThat(entityHistory).containsExactly(entity); } @Test void findByAlias() { Entity entity = domainBuilder.entity().persist(); byte[] alias = entity.getAlias(); assertThat(entityRepository.findByAlias(alias)).get().isEqualTo(entity.getId()); } @Test void findByEvmAddress() { Entity entity = domainBuilder.entity().persist(); Entity entityDeleted = domainBuilder.entity().customize((b) -> b.deleted(true)).persist(); assertThat(entityRepository.findByEvmAddress(entity.getEvmAddress())) .get() .isEqualTo(entity.getId()); assertThat(entityRepository.findByEvmAddress(entityDeleted.getEvmAddress())) .isEmpty(); assertThat(entityRepository.findByEvmAddress(new byte[] {1, 2, 3})).isEmpty(); } @Test void updateContractType() { Entity entity = domainBuilder.entity().persist(); Entity entity2 = domainBuilder.entity().persist(); entityRepository.updateContractType(List.of(entity.getId(), entity2.getId())); assertThat(entityRepository.findAll()) .hasSize(2) .extracting(Entity::getType) .allMatch(e -> e == CONTRACT); } }
package com.pineapple.mobilecraft.tumcca.server; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.pineapple.mobilecraft.tumcca.data.Account; import com.pineapple.mobilecraft.tumcca.data.Profile; import org.json.JSONException; import org.json.JSONObject; /** * Created by yihao on 15/5/26. */ public interface IUserServer { public static final String COMMON_SUCCESS = "success"; public static final String COMMON_FAILED = "failed"; public static final String REGISTER_SUCCESS = "register_success"; public static final String REGISTER_FAILED = "register_failed"; public static final String REGISTER_ACCOUNT_EXIST = "register_account_exist"; //public static final String REGISTER_ACCOUNT_EXIST = "register_account_exist"; public static class RegisterResult{ public String uid; public String message = REGISTER_FAILED; public static RegisterResult getFailResult(){ return new RegisterResult(); } } public static class LoginResult{ public String uid = "-1"; public String token = ""; public static LoginResult NULL = new LoginResult(); public static LoginResult fromJSON(String jsonObject){ Gson gson = new Gson(); LoginResult result = NULL; try{ result = gson.fromJson(jsonObject, LoginResult.class); } catch (JsonSyntaxException exception){ exception.printStackTrace(); } if(result.uid.equals("-1")){ result = NULL; } return result; } public static JSONObject toJSON(LoginResult loginResult){ Gson gson = new Gson(); try { return new JSONObject(gson.toJson(loginResult)); } catch (JSONException e) { e.printStackTrace(); return null; } } } public void sendPhoneCheckCode(String phoneNumber); public RegisterResult register(String mobile, String email, String password); public Account getAccount(String token); public LoginResult login(String username, String password); public Profile getUser(String uid, String token); public String updateUser(Profile profile, String token); public String logout(int uid, String token); public boolean isEmailExist(String email); public boolean isPhoneExist(String phone); public String deleteUser(String id); public String getAvatarUrl(int avatarId); }
package pl.whirly.recruitment.payment.model; import java.util.Random; public class Payment { private String id; private String userId; private String productId; private double amountGross; private String currency; public Payment(String id, String userId, String productId, double amountGross, String currency) { this.id = id; this.userId = userId; this.productId = productId; this.amountGross = amountGross; this.currency = currency; } public String getId() { return id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public double getAmountGross() { return amountGross; } public void setAmountGross(double amountGross) { this.amountGross = amountGross; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } @Override public int hashCode() { Random random = new Random(); return random.nextInt(); } }
package com.legalzoom.api.test.OrdersServiceResponseParser; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.client.ClientResponseContext; import javax.ws.rs.core.MultivaluedMap; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.legalzoom.api.ResponseFilter; import com.legalzoom.api.test.client.ResponseData; public class OrdersServiceJSONParser { Logger logger = LoggerFactory.getLogger(OrdersServiceJSONParser.class); public ResponseData responseData; // private Order order = new Order(); // private OrderItem orderIterms = new OrderItem(); public OrdersServiceJSONParser(ResponseData responseData){ this.responseData = responseData; } public List<OrderItem> getOrderItems() { // ResponseData responseData = new ResponseData(); String responseBody = responseData.getResponseBody(); JSONObject json = new JSONObject(responseBody); JSONObject jsonOrder = json.getJSONObject("order"); Gson gson = new Gson(); Order order = gson.fromJson(jsonOrder.toString(), Order.class); List<OrderItem> orderItems = order.getOrderItems(); // Boolean result = orderitems.get(0).getProductConfiguration().getProductComponent().getProductComponentFlags().getAllowExpediteOnPackage(); return orderItems; } }
public class Calculator { private float left; private float right; private String operation = ""; private float result; public void setLeft(float left) { this.left = left; } public void setRight(float right) { this.right = right; } public void setOperation(String operation) { this.operation = operation; } public void doOperation() { switch(operation) { case "+": add(left, right); break; case "-": sub(left, right); break; case "*": mul(left, right); break; case "/": div(left, right); break; case "^": pow(left, right); break; default: System.out.println("Неверный символ"); } } public void add(float left, float right) { result = left + right; } public void sub(float left, float right) { result = left - right; } public void mul(float left, float right) { result = left * right; } public void div(float left, float right) { result = left / right; } public void pow(float left, float right) { float temp = left; for(int i = 0; i < (int) right - 1; i++) { left *= temp; } result = left; } public float getResult() { return result; } public void cleanResult() { result = 0.0f; } }
/** * 23. Merge k Sorted Lists * 使用归并方法,利用Priority Queue小顶堆特性会更简单 */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; int f = 1; while (f < lists.length) { // 归并逻辑 for (int i = 0; i < lists.length - f; i += f) { lists[i] = mergeTwoLists(lists[i], lists[i+f]); } f *= 2; } return lists[0]; } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode r = null; if (l1.val < l2.val) { r = new ListNode(l1.val); l1 = l1.next; } else { r = new ListNode(l2.val); l2 = l2.next; } ListNode t = r; while (l1 != null && l2 != null) { while (l1 != null && l2 != null && l1.val <= l2.val) { t.next = new ListNode(l1.val); l1 = l1.next; t = t.next; } while (l1 != null && l2 != null && l1.val > l2.val) { t.next = new ListNode(l2.val); l2 = l2.next; t = t.next; } } t.next = l1 != null ? l1 : l2; return r; } public static void main(String[] args) { Solution s = new Solution(); int[] a = {1, 3, 4}; int[] b = {2, 3, 4}; int[] c = {2, 3, 4, 9, 11}; ListNode[] list = new ListNode[3]; list[0] = new ListNode(a); list[1] = new ListNode(b); list[2] = new ListNode(c); for (int i = 0; i < list.length; i++) { list[i].printList(); } ListNode r = s.mergeKLists(list); r.printList(); } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } ListNode(int[] a) { this.val = a[0]; ListNode t = null; if (a.length > 1) { this.next = new ListNode(a[1]); t = this.next; } int i = 2; while (i < a.length) { t.next = new ListNode(a[i++]); t = t.next; } } public void printList() { ListNode t = this; while (t != null) { System.out.print(t.val + " "); t = t.next; } System.out.println(); } }
package org.alienideology.jcord.event.channel.group.update; import org.alienideology.jcord.event.channel.group.GroupUpdateEvent; import org.alienideology.jcord.internal.object.IdentityImpl; import org.alienideology.jcord.internal.object.channel.Channel; import org.alienideology.jcord.internal.rest.HttpPath; /** * @author AlienIdeology */ public class GroupIconUpdateEvent extends GroupUpdateEvent { private final String oldIcon; public GroupIconUpdateEvent(IdentityImpl identity, int sequence, Channel channel, String icon) { super(identity, sequence, channel); this.oldIcon = icon; } public String getOldIconHash() { return oldIcon; } public String getOldIconUrl() { return String.format(HttpPath.EndPoint.GROUP_ICON, getChannel().getId(), getOldIconHash()); } public String getNewIconHash() { return getGroup().getIconHash(); } public String getNewIconurl() { return getGroup().getIconUrl(); } }
/* * StatisticEntities.java * This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin. * $Id$ * This is free and unencumbered software released into the public domain. * For more information, please refer to <http://unlicense.org> */ package ru.otus.models; import lombok.Data; import lombok.EqualsAndHashCode; import javax.json.bind.annotation.JsonbProperty; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Data @EqualsAndHashCode @XmlRootElement(name = "registrations") @XmlAccessorType(XmlAccessType.FIELD) public class StatisticEntities implements Serializable, Entities<StatisticEntity> { @XmlElement(name = "registration") @JsonbProperty("registrations") private List<StatisticEntity> registrations = new ArrayList<>(); public StatisticEntities() { /* None */ } public StatisticEntities(List<StatisticEntity> registrations) { this.registrations = registrations; } public List<StatisticEntity> getRegistrations() { return registrations; } public void setRegistrations(List<StatisticEntity> registrations) { this.registrations = registrations; } @Override public void add(StatisticEntity department) { registrations.add(department); } @Override public List<StatisticEntity> asList() { return getRegistrations(); } } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package pages; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; import java.util.Random; import static junit.framework.Assert.assertEquals; public class SearchAndBasketPage extends PageBase { public SearchAndBasketPage(WebDriver driver, WebDriverWait wait) { super(driver, wait); } String StringPrice; String StringBasketPrice; By searchBox = By.xpath(" //input [@class='search-box']"); By searchResult = By.xpath("//div [@class = 'p-card-chldrn-cntnr']/a"); By addItem = By.className("add-to-bs"); By goBasket = By.className("goBasket"); By basketPrice = By.xpath("//div[@class='pb-basket-item-price']"); By itemPieceAdd = By.xpath("//button [@class='ty-numeric-counter-button']"); By itemPiece = By.xpath("//input [@class='counter-content']"); By trash = By.className("i-trash"); By trashOk = By.xpath("//div[ @class='btn-box-remove-item']//span"); By trashCheck = By.xpath("//a [@class='btn shoppingStart']"); public void SearchBox(String search){ driver.findElement(searchBox).sendKeys(search+Keys.ENTER); } public void searchPageResult(){ List<WebElement> PageResult; PageResult = driver.findElements(searchResult); int maxResult = PageResult.size(); Random random = new Random(); int randomProduct = random.nextInt(maxResult); PageResult.get(randomProduct).click(); } public void ItemPriceAndClear(){ StringPrice = driver.findElement(By.className("pr-in-cn")).findElement(By.className("prc-slg")).getText(); StringPrice = StringPrice.replaceAll("\n", " "); StringPrice = StringPrice.replaceAll("TL", " "); StringPrice = StringPrice.replaceAll("\\.", ""); StringPrice = StringPrice.replaceAll(",", ""); StringPrice = StringPrice.trim(); } public void AddItem(){ driver.findElement(addItem).click(); } public void GoBasket(){ driver.findElement(By.className("productPriceBox")).findElement(goBasket).click(); } public boolean BasketPriceAndCheck(){ StringBasketPrice = driver.findElement(basketPrice).getText(); StringBasketPrice = StringBasketPrice.replaceAll("\n", ""); StringBasketPrice = StringBasketPrice.replaceAll("TL", ""); StringBasketPrice = StringBasketPrice.replaceAll(",", ""); StringBasketPrice = StringBasketPrice.replaceAll("\\.", ""); String[] BasketPriceSplit = StringBasketPrice.split(" "); String BasketPrice; String str; if (BasketPriceSplit.length == 2){ str = BasketPriceSplit[1]; } else { str = BasketPriceSplit[0]; } BasketPrice = str.trim(); return BasketPrice.equals(StringPrice); } public boolean Itempiece () throws InterruptedException { driver.findElement(itemPieceAdd).click(); Thread.sleep(3000); String pieceString = driver.findElement(itemPiece).getAttribute("value"); return pieceString.equals("2"); } public boolean CheckRemove() throws InterruptedException { driver.findElement(trash).click(); Thread.sleep(1000); driver.findElement(trashOk).click(); String link= "https://www.trendyol.com/"; String BasketLink = driver.findElement(trashCheck).getAttribute("href"); return BasketLink.equals(link); } }
package com.tencent.mm.e.b; import com.tencent.mm.ab.i.a; import com.tencent.mm.modelvoice.q; import com.tencent.mm.sdk.platformtools.x; class h$3 implements a { final /* synthetic */ h bFa; h$3(h hVar) { this.bFa = hVar; } public final void onError() { this.bFa.bEL.zY(); x.e("MicroMsg.SceneVoice.Recorder", "Record Failed file:" + this.bFa.mFileName); q.op(this.bFa.mFileName); if (this.bFa.bEX != null) { this.bFa.bEX.onError(); } } }
/******************************************************************************* * Copyright 2020 Grégoire Martinetti * * 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.gmart.devtools.java.serdes.codeGen.javaGen.modelExtraction; import java.io.File; import java.io.FileNotFoundException; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.PackageSetSpec; public class PackagesSetFactory { public static PackageSetSpec makePackageSet(String yamlFilePath) throws FileNotFoundException { return makePackageSet(new File(yamlFilePath)); } public static PackageSetSpec makePackageSet(File yamlFile) throws FileNotFoundException { YamlToModel yamlReader = new YamlToModel(); PackageSetSpec packagesSet = yamlReader.read(yamlFile); return packagesSet; } }
package assemAssist.model.option; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import assemAssist.TestInit; import assemAssist.model.operations.TaskSpecification; /** * A test class for the Option class * * @author SWOP Group 3 * @version 2.0 */ public class OptionTest { private VehicleOption option; private List<TaskSpecification> taskSpecifications; private VehicleOptionCategory category, categoryDifferent; private String name; @Before public void initialise() { category = VehicleOptionCategory.AIRCO; categoryDifferent = VehicleOptionCategory.BODY; taskSpecifications = TestInit.getTaskSpecifications(category); name = "name"; option = new VehicleOption(name, taskSpecifications); } @Test public void testValidConstructor() { assertEquals(option.getName(), name); assertEquals(option.getTaskSpecifications(), taskSpecifications); } @Test(expected = IllegalArgumentException.class) public void testInvalidConstructorName() { option = new VehicleOption(null, TestInit.getTaskSpecifications()); } @Test(expected = IllegalArgumentException.class) public void testInvalidConstructorTaskSpecifications() { option = new VehicleOption(name, null); } @Test public void testIsValidNameTrue() { assertTrue(option.isValidName(name)); } @Test public void testIsValidNameFalse() { assertFalse(option.isValidName(null)); } @Test public void testIsValidTaskSpecificationsTrue() { assertTrue(option.isValidTaskSpecifications(TestInit.getTaskSpecifications())); } @Test public void testIsValidTaskSpecificationsFalseNull() { assertFalse(option.isValidTaskSpecifications(null)); } @Test public void testIsValidTaskSpecificationsFalseEmpty() { assertFalse(option.isValidTaskSpecifications(new ArrayList<TaskSpecification>())); } @Test public void testIsValidTaskSpecificationsFalseElement() { taskSpecifications.add(null); assertFalse(option.isValidTaskSpecifications(taskSpecifications)); } @Test public void testIsValidTaskSpecificationsFalseOtherSpec() { taskSpecifications.add(TestInit.getTaskSpecification(categoryDifferent)); assertFalse(option.isValidTaskSpecifications(taskSpecifications)); } @Test public void testIsValidTaskSpecificationTrue() { TaskSpecification spec = TestInit.getTaskSpecification(); assertTrue(option.isValidTaskSpecification(spec, spec.getOptionCategory())); } @Test public void testIsValidTaskSpecificationFalse() { assertFalse(option.isValidTaskSpecification(null, null)); } @Test public void testGetOptionCategory() { assertEquals(option.getOptionCategory(), category); } @Test(expected = UnsupportedOperationException.class) public void testUnmodifiableList() { option.getTaskSpecifications().add(null); } @Test public void testCreateNoneOption() { VehicleOption option = VehicleOption.createNoneOption(TestInit.getOptionCategory()); assertEquals(option.getName(), VehicleOption.noneName); assertTrue(option.getTaskSpecifications().isEmpty()); } @Test public void testIsNoneTrue() { assertTrue(VehicleOption.createNoneOption(TestInit.getOptionCategory()).isNone()); } @Test public void testIsNoneFalse() { assertFalse(option.isNone()); } @Test public void testHashCodeTrue() { assertEquals(option.hashCode(), new VehicleOption(name, taskSpecifications).hashCode()); } @Test public void testHashCodeFalse() { assertFalse(option.hashCode() == new VehicleOption("othername", taskSpecifications) .hashCode()); } @Test public void testEqualsTrueSame() { assertTrue(option.equals(option)); } @Test public void testEqualsTrueOther() { assertTrue(option.equals(new VehicleOption(name, taskSpecifications))); } @Test public void testEqualsFalseNull() { assertFalse(option.equals(null)); } @Test public void testEqualsFalseClass() { assertFalse(option.equals(TestInit.getAction())); } @Test public void testEqualsFalseName() { assertFalse(option.equals(new VehicleOption("othername", taskSpecifications))); } @Test public void testEqualsFalseSpecifications() { assertFalse(option.equals(new VehicleOption(name, TestInit.getTaskSpecifications()))); } @Test public void testEqualsFalseCategory() { assertFalse(VehicleOption.createNoneOption(category).equals( VehicleOption.createNoneOption(categoryDifferent))); } @Test public void testToString() { assertEquals(option.toString(), category + ": " + name); } }
package com.trey.fitnesstools; import android.app.Dialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; 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 android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class DialogFragmentPlates extends DialogFragment { private RecyclerView plateRecyclerView; private EditText txtEnterNewPlate; private EditText txtDeletePlate; private ImageButton addPlateImageButton; private ImageButton deletePlateImageButton; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_fragment_plates,null); plateRecyclerView = v.findViewById(R.id.recyclerView_plate); plateRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); PlateAdapter adapter = new PlateAdapter(); plateRecyclerView.setAdapter(adapter); txtEnterNewPlate = v.findViewById(R.id.editTextEnterNewPlate); txtDeletePlate = v.findViewById(R.id.editTextDeleteCustomPlate); addPlateImageButton = v.findViewById(R.id.imageButton_addPlates); deletePlateImageButton = v.findViewById(R.id.btnDeletePlate); View.OnClickListener buttonListener = new View.OnClickListener() { @Override public void onClick(View view) { int clickedId = view.getId(); if(clickedId == addPlateImageButton.getId()) { addCustomPlate(); } else if(clickedId == deletePlateImageButton.getId()) { deleteCustomPlate(); } } }; addPlateImageButton.setOnClickListener(buttonListener); deletePlateImageButton.setOnClickListener(buttonListener); return new AlertDialog.Builder(getActivity()) .setView(v) .setTitle(R.string.text_plate_type_label) .setPositiveButton(android.R.string.ok,null) .create(); } //retrieve the user's input from the edit text //store this as a plate in FragmentPlateCalculator.calculationPlates private void addCustomPlate() { try { double newPlateInput = Double.parseDouble(txtEnterNewPlate.getText().toString()); //new plate with the input weight. second param is true because it will be enabled. third param is true because it's a custom plate. Plate newPlate = new Plate(newPlateInput,true,true); int insertIndex = FragmentPlateCalculator.calculationPlates.findPlateIndex(newPlate); if(insertIndex > -1) { FragmentPlateCalculator.calculationPlates.add(insertIndex, newPlate); plateRecyclerView.getAdapter().notifyItemInserted(insertIndex); } } catch(Exception e) { Toast.makeText(getActivity(),"Enter a valid plate value",Toast.LENGTH_SHORT); } } //delete a custom plate that the user has added (does nothing if the plate is a default plate). private void deleteCustomPlate() { try { double deletePlateInput = Double.parseDouble(txtDeletePlate.getText().toString()); //attempt to remove the plate if it's in the list. (returns boolean indicating if it was found) boolean plateFound = FragmentPlateCalculator.calculationPlates.removeCustomPlate(deletePlateInput); if(!plateFound) { Toast.makeText(getActivity(),"A plate with this value could not be found",Toast.LENGTH_SHORT); } //notify item changed would improve performance plateRecyclerView.getAdapter().notifyDataSetChanged(); } catch(Exception e) { Toast.makeText(getActivity(),"Enter a valid plate value",Toast.LENGTH_SHORT); } } private class PlateHolder extends RecyclerView.ViewHolder { private TextView weightText; private CheckBox checkPlateUsed; private Plate plate; public PlateHolder(View v) { super(v); weightText = v.findViewById(R.id.weight_text_plate_holder); checkPlateUsed = v.findViewById(R.id.check_plate_selected); checkPlateUsed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { //if the box becomes checked, enable the plate so it can be used in calculations. if(isChecked) { plate.setEnabled(true); } //disable it if unchecked else { plate.setEnabled(false); } } }); } public void bind(Plate p) { plate = p; weightText.setText(LiftingCalculations.desiredFormat(plate.getWeight())); checkPlateUsed.setChecked(p.isEnabled()); } } private class PlateAdapter extends RecyclerView.Adapter<PlateHolder> { @Override public PlateHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.view_holder_plate,parent,false); PlateHolder holder = new PlateHolder(view); return holder; } @Override public void onBindViewHolder(PlateHolder holder, int position) { holder.bind(FragmentPlateCalculator.calculationPlates.get(position)); } @Override public int getItemCount() { return FragmentPlateCalculator.calculationPlates.size(); } } public static DialogFragmentPlates newInstance() { return new DialogFragmentPlates(); } }
package org.proyectofinal.gestorpacientes.modelo.entidades; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.NamedQuery; @Entity @NamedQuery(name = "Usuario.getAll", query = "from Usuario") public class Usuario { @Id @GenericGenerator(name="persona" , strategy="increment") @GeneratedValue(generator="persona") private int idUsuario; private String usuario; private String clave; private String rango; public Usuario(){ } public Usuario(String usuario, String clave,String rango) { super(); this.usuario = usuario; this.clave = clave; this.rango=rango; } public int getIdUsuario() { return idUsuario; } public String getUsuario() { return usuario; } public String getClave() { return clave; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public void setClave(String clave) { this.clave = clave; } public String getRango() { return rango; } public void setRango(String rango) { this.rango = rango; } }
package com.polsl.edziennik.desktopclient.view.common.panels.tablePanels; import javax.swing.JPanel; import com.polsl.edziennik.desktopclient.controller.utils.filters.ReportFilter; import com.polsl.edziennik.desktopclient.model.tables.ReportTableModel; import com.polsl.edziennik.desktopclient.view.common.panels.button.ButtonPanel; import com.polsl.edziennik.desktopclient.view.common.panels.filter.DateFilterPanel; public class ReportTablePanel extends TablePanel { private DateFilterPanel filter; public ReportTablePanel(ReportTableModel tableModel, DateFilterPanel filter, ButtonPanel buttonPanel, JPanel preview) { super(bundle.getString("ReportTitle"), tableModel, filter, buttonPanel, preview); setColumnWidths(); } public void setColumnWidths() { if (table.getColumnModel() == null) return; table.getColumnModel().getColumn(0).setPreferredWidth(25); table.getColumnModel().getColumn(1).setPreferredWidth(140); table.getColumnModel().getColumn(2).setPreferredWidth(165); table.getColumnModel().getColumn(3).setPreferredWidth(64); table.getColumnModel().getColumn(4).setPreferredWidth(65); } @Override public int getComboSelectedIndex() { return filter.getComboSelectedIndex(); } @Override public void runFilter(Long min, Long max) { } @Override public void runFilter(Long min, Long max, String s, String s2) { ReportFilter rf = new ReportFilter(min, max, s, s2); sorter.setRowFilter(rf); } @Override public void runFilter(Long min, Long max, String s) { // TODO Auto-generated method stub } }
package mvc_demo.interfaces; import java.util.HashMap; import java.util.List; public interface ModelInterface { public String getTblName(); public String getTblName(String className); public void set(String name, String val); public String get(String name); public HashMap<String, String> get(); public List<HashMap<String, String>> all(); public void save(); public void delete(); public boolean fetch(int id); public List<HashMap<String, String>> select(String columns); }
/*! * Copyright 2002 - 2017 Webdetails, a Pentaho company. All rights reserved. * * This software was developed by Webdetails and is provided under the terms * of the Mozilla Public License, Version 2.0, or any later version. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails. * * Software distributed under the Mozilla Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. */ package pt.webdetails.cdf.dd.model.meta; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import pt.webdetails.cdf.dd.model.core.KnownThingKind; import pt.webdetails.cdf.dd.model.core.validation.ValidationException; public class DashboardType extends MetaObject { private static final Log _logger = LogFactory.getLog( DashboardType.class ); private static final DashboardType _instance; static { DashboardType instance; try { instance = new DashboardType.Builder().build(); } catch ( ValidationException ex ) { // Should never happen (Would be FATAL!) _logger.error( "Error creating DashboardType instance", ex ); instance = null; } _instance = instance; } public static DashboardType getInstance() { return _instance; } protected DashboardType( Builder builder ) throws ValidationException { super( builder ); } @Override public String getKind() { return KnownThingKind.DashboardType; } /** * Class to create and modify DashboardType instances. */ public static class Builder extends MetaObject.Builder { public DashboardType build() throws ValidationException { return new DashboardType( this ); } } }
package com.sdl.webapp.tridion.contextengine; import com.tridion.ambientdata.AmbientDataContext; import com.tridion.ambientdata.claimstore.ClaimStore; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.net.URI; import java.util.Collections; import java.util.Map; @Component @Slf4j public class AdfContextClaimsProvider extends AbstractAdfContextClaimsProvider { /** * {@inheritDoc} */ @Override protected Map<URI, Object> getCurrentClaims() { ClaimStore currentClaimStore = AmbientDataContext.getCurrentClaimStore(); return currentClaimStore == null ? Collections.<URI, Object>emptyMap() : currentClaimStore.getAll(); } }
package com.goldgov.dygl.module.partyMemberDuty.duty.service.impl; import java.util.Calendar; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.goldgov.dygl.module.partyMemberDuty.duty.dao.IDutyDao; import com.goldgov.dygl.module.partyMemberDuty.duty.domain.Duty; import com.goldgov.dygl.module.partyMemberDuty.duty.domain.PartyMemberInfoDuty; import com.goldgov.dygl.module.partyMemberDuty.duty.service.DutyQuery; import com.goldgov.dygl.module.partyMemberDuty.duty.service.IDutyService; import com.goldgov.dygl.module.partyMemberDuty.duty.service.PartyMemberInfoDutyQuery; import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException; import com.goldgov.dygl.module.partymemberrated.rated.services.IPartyMemberRatedService; import com.goldgov.dygl.module.partymemberrated.rated.services.PartyMemberRated; @Service("dutyServiceImpl") public class DutyServiceImpl implements IDutyService { @Autowired @Qualifier("dutyDao") private IDutyDao dutyDao; @Autowired @Qualifier("partyMemberRatedService") private IPartyMemberRatedService partyMemberRatedService; @Override public void addInfo(Duty duty) throws NoAuthorizedFieldException { dutyDao.addInfo(duty); } @Override public void updateInfo(Duty duty) throws NoAuthorizedFieldException { dutyDao.updateInfo(duty); } @Override public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException { dutyDao.deleteInfo(entityIDs); } @Override public List<Duty> findInfoList(DutyQuery query) throws NoAuthorizedFieldException { return dutyDao.findInfoListByPage(query); } @Override public Duty findInfoById(String entityID) throws NoAuthorizedFieldException { return dutyDao.findInfoById(entityID); } @Override public List<PartyMemberInfoDuty> findinfoListMemberInfo(PartyMemberInfoDutyQuery query) throws NoAuthorizedFieldException { return dutyDao.findinfoListMemberInfo(query); } @Override public PartyMemberInfoDuty findInfoMemberInfo(String id) throws NoAuthorizedFieldException { return dutyDao.findInfoMemberInfo(id); } @Override public float getPerformDutyScore(String userID, String ratedId) { String dutyId=getPerformDuty(userID, ratedId); if(dutyId!=null){ Object obj = dutyDao.getScoreByDutyId(dutyId,userID); if(obj==null){ return 0f; }else{ return Float.valueOf(obj.toString()); } } return 0f; } //获取当前履职率则id @Override public String getPerformDuty(String userID, String ratedId) { PartyMemberRated rated = partyMemberRatedService.findInfo(ratedId); int rateYear = Integer.parseInt(rated.getRatedYear());//评价年份 Calendar cal = Calendar.getInstance(); cal.setTime(rated.getRatedTimeEnd());//取结束月份 int rateMonth = cal.get(Calendar.MONTH)+1;//评价月份 String monthStr = ""; if(rateMonth<10){ monthStr = "0"+rateMonth; }else{ monthStr = ""+rateMonth; } String[] orgIds = dutyDao.findOrgId(userID); String orgId = null; if(orgIds!=null){ orgId = orgIds[0]; } if(orgId!=null){ //2016-06-15 履职履则只考虑以月份为周期 //查询与评价对应年份和月份的履职履则 String cycleId = "1003";//周期 月份 String monthCode = "CD_MONTH_"+monthStr; String cycleDateId = dutyDao.getCycleDateId(cycleId,monthCode);//周期日期 //根据年份、考评类型(周期 cycleId) 考评时间(cycleDateId) 来查询履职履则 DutyQuery query = new DutyQuery(); query.setSearchYear(rateYear); query.setSearchEvaluationType(cycleId); query.setSearchEvaluationTime(cycleDateId); query.setPartyOrganizationID(orgId); List<Duty> list = dutyDao.getPublishedDutyList(query); if(list!=null && list.size()>0){ return list.get(0).getDutyId(); } } return null; } }
package org.newdawn.slick.util; import java.io.InputStream; import java.net.URL; public interface ResourceLocation { InputStream getResourceAsStream(String paramString); URL getResource(String paramString); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slic\\util\ResourceLocation.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * created 14.03.2005 * * $Id: IDataType.java 567 2006-11-06 23:24:39Z cse $ */ package com.byterefinery.rmbench.external.model; /** * specification of a datatype that is associated with a database column * * @author cse */ public interface IDataType { public static final String SIZE_NOT_SUPPORTED = "notsupported.size"; public static final String SCALE_NOT_SUPPORTED = "notsupported.scale"; public static final long UNSPECIFIED_SIZE = 0L; public static final int UNSPECIFIED_SCALE = 0; public static final long INVALID_SIZE = Long.MIN_VALUE; public static final int INVALID_SCALE = Integer.MIN_VALUE; public static final long GIGABYTE = 1024*1024*1024; public static final long UNLIMITED_SIZE = Long.MAX_VALUE; public static final int UNLIMITED_SCALE = Integer.MAX_VALUE; /** * @return the primary name of this type */ public String getPrimaryName(); /** * @return <code>true</code> if the given name is equal to any of the possibly * alternative names of this type */ public boolean hasName(String name); /** * @return the type name as appropriate in a DDL statement, i.e. including size/scale */ public String getDDLName(); /** * @return the size value, or {@link INVALID_VALUE} if the type does not * accept a size value */ public long getSize(); /** * @return the maximum size value, or {@link INVALID_VALUE} if the type does not * accept a size value */ public long getMaxSize(); /** * @param size the new size value * @throws UnsupportedOperationException if this type does not accept size values * @throws IllegalArgumentException if size exceeds the maximum size of this type, */ public void setSize(long size); /** * @return the scale value, or {@link INVALID_VALUE} if the type does not * accept a scale value */ public int getScale(); /** * @return the maximum scale value, or {@link INVALID_VALUE} if the type does not * accept a scale value */ public int getMaxScale(); /** * @param scale the new scale value * @throws UnsupportedOperationException if this type does not accept scale values * @throws IllegalArgumentException if scale exceeds the maximum scale of this type, */ public void setScale(int scale); /** * @return true if this type carries a size property */ boolean acceptsSize(); /** * @return true if this type carries a scale property */ boolean acceptsScale(); /** * @param size an imported size value * @return true if this type accepts size values and the given value is not equal to the * implicit default value (i.e. the one implied when the type is used without a size parameter) */ public boolean isExplicitSize(long size); /** * @param scale an imported scale value * @return true if this type accepts scale values and the given value is not equal to the * implicit default value (i.e. the one implied when the type is used without a scale parameter) */ public boolean isExplicitScale(int scale); /** * @return true if a size value must be specified (there is no implicit default) */ boolean requiresSize(); /** * @return true if a scale value must be specified (there is no implicit default) */ boolean requiresScale(); /** * @param size a size value to be assigned * @return null if the given size is acceptable, an error token otherwise. If the type * does not support the size property, the value will be {@link #SIZE_NOT_SUPPORTED} for * any size value */ String validateSize(long size); /** * @param scale a scale value to be assigned * @return null if the given scale is acceptable, an error token otherwise. If the type * does not support the scale property, the value will be {@link #SCALE_NOT_SUPPORTED} for * any scale value */ String validateScale(int scale); /** * @return true if this type carries extra information, which is typically maintained through a type * extension editor and whose internal structure is unknown to RMBench core. */ public boolean hasExtra(); /** * @return the extra information for this type, which is typically maintained through a type * extension editor and whose internal structure is unknown to RMBench core. * <code>null</code> if not applicable */ public String getExtra(); /** * @param extra the extra information for this type, as returned by a previous call to {@link #getExtra()} * @throws IllegalArgumentException if not applicable to this type */ public void setExtra(String extra); /** * @return an instance that is equivalent to this object, but may be specialized * with size and/or scale values if applicable. The returned object will be initialized * with default values if applicable */ public IDataType concreteInstance(); }
package com.lec.ex08robot; public class RobotOrder { public void action(Robot robot) { // 이 안에 있는 robot만 일시킬 수 있다 //Dance타입이면 Dance 시킴 if (robot instanceof DanceRobot) { // instance of- checks whether an object is an instance of a specific class // or an interface. ((DanceRobot) robot).dance(); // DanceRobot dRobot =(DanceRobot)robot; // dRobot.dance(); } else if (robot instanceof SingRobot) { ((SingRobot) robot).sing(); // SingRobot sRobot = (SingRobot)robot; // sRobot.sing(); } else if (robot instanceof DrawRobot) { ((DrawRobot) robot).draw(); // DrawRobot dRobot = (DrawRobot)robot; // dRobot.draw(); } } }
package one.kii.summer.beans.utils; import one.kii.summer.beans.annotations.Commit; import org.junit.Assert; import org.junit.Test; import static one.kii.summer.beans.utils.HashTools.NULL_HEX; /** * Created by WangYanJiong on 04/05/2017. */ public class TestHashTools { @Test public void testHashHex() { String hash1 = HashTools.hashHex(""); Assert.assertEquals(NULL_HEX, hash1); String hash2 = HashTools.hashHex((String) null); Assert.assertEquals(NULL_HEX, hash2); } @Test public void testHashHexObject() { String hash1 = HashTools.hashHex(new TestNoFactorObject()); Assert.assertEquals(NULL_HEX, hash1); String hash2 = HashTools.hashHex(new TestSingleFactorObject()); Assert.assertNotNull(hash2); Assert.assertNotEquals(NULL_HEX, hash2); String hash3 = HashTools.hashHex(new TestDoubleFactorObject()); Assert.assertNotNull(hash2); Assert.assertNotEquals(NULL_HEX, hash3); Assert.assertNotEquals(hash2, hash3); String hash4 = HashTools.hashHex(new TestPartFactorObject()); Assert.assertNotNull(hash4); Assert.assertNotEquals(NULL_HEX, hash4); Assert.assertEquals(hash4, hash3); String hash5 = HashTools.hashHex(new TestPartFactorPrimitiveObject()); Assert.assertNotNull(hash4); Assert.assertNotEquals(NULL_HEX, hash4); Assert.assertNotEquals(hash4, hash5); } public static class TestNoFactorObject { String field = "abc"; } public static class TestSingleFactorObject { @Commit String field = "abc"; } public static class TestDoubleFactorObject { @Commit String field1 = "abc"; @Commit String field2 = "def"; } public static class TestPartFactorObject { @Commit String field1 = "abc"; @Commit String field2 = "def"; String field3 = "ghi"; } public static class TestPartFactorPrimitiveObject { @Commit String field1 = "abc"; @Commit String field2 = "def"; String field3 = "ghi"; @Commit int field4 = 1000; @Commit boolean field5 = true; } }
package OOPS; public class Test2OverRiding { public static void main(String[] args) { OverRiding2 obj = new OverRiding2(); obj.m1(); } }
package pje14.git.test; public class C4 { }
package com.jim.multipos.ui.mainpospage.view; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SimpleItemAnimator; import android.text.InputType; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.jim.mpviews.MpList; import com.jim.mpviews.MpNumPad; import com.jim.mpviews.MpNumPadSecond; import com.jim.mpviews.MpSecondSwticher; import com.jim.mpviews.model.PaymentTypeWithService; import com.jim.multipos.R; import com.jim.multipos.config.common.BaseAppModule; import com.jim.multipos.core.BaseFragment; import com.jim.multipos.data.DatabaseManager; import com.jim.multipos.data.db.model.customer.Customer; import com.jim.multipos.data.db.model.customer.Debt; import com.jim.multipos.data.db.model.order.Order; import com.jim.multipos.data.db.model.order.PayedPartitions; import com.jim.multipos.data.prefs.PreferencesHelper; import com.jim.multipos.ui.mainpospage.MainPosPageActivity; import com.jim.multipos.ui.mainpospage.adapter.PaymentPartsAdapter; import com.jim.multipos.ui.mainpospage.connection.MainPageConnection; import com.jim.multipos.ui.mainpospage.dialogs.AddDebtDialog; import com.jim.multipos.ui.mainpospage.dialogs.TipsDialog; import com.jim.multipos.ui.mainpospage.presenter.PaymentPresenter; import com.jim.multipos.utils.NumberTextWatcherPaymentFragment; import com.jim.multipos.utils.UIUtils; import com.jim.multipos.utils.printer.CheckPrinter; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import butterknife.BindView; /** * Created by developer on 22.08.2017. */ public class PaymentFragment extends BaseFragment implements PaymentView { @Inject PaymentPresenter presenter; @Inject DatabaseManager databaseManager; DecimalFormat decimalFormat; @Inject PreferencesHelper preferencesHelper; @Inject MainPageConnection mainPageConnection; @BindView(R.id.llDebtBorrow) LinearLayout llDebtBorrow; @BindView(R.id.tvPay) TextView tvPay; @BindView(R.id.mpLPaymentTypeList) MpList mpList; @BindView(R.id.mpSSwitcher) MpSecondSwticher mpSSwitcher; @BindView(R.id.flPaymentList) FrameLayout flPaymentList; @BindView(R.id.rvPaymentsListHistory) RecyclerView rvPaymentsListHistory; @BindView(R.id.llPrintCheck) LinearLayout llPrintCheck; @BindView(R.id.etPaymentAmount) EditText etPaymentAmount; @BindView(R.id.tvBalanceDue) TextView tvBalanceDue; @BindView(R.id.tvChange) TextView tvChange; @BindView(R.id.tvBalanceOrChange) TextView tvBalanceOrChange; @BindView(R.id.ivDebt) ImageView ivDebt; @BindView(R.id.tvDebt) TextView tvDebt; @BindView(R.id.llTips) LinearLayout llTips; @BindView(R.id.tvTips) TextView tvTips; @BindView(R.id.ivTips) ImageView ivTips; @BindView(R.id.ivPrint) ImageView ivPrint; @BindView(R.id.tvPrint) TextView tvPrint; @BindView(R.id.tvChangeCurrency) TextView tvChangeCurrency; @BindView(R.id.tvBalanceDueCurrency) TextView tvBalanceDueCurrency; @BindView(R.id.tvPaymentCurrency) TextView tvPaymentCurrency; CheckPrinter checkPrinter; DecimalFormat df; DecimalFormat dfnd; PaymentPartsAdapter paymentPartsAdapter; private AddDebtDialog dialog; TextWatcher watcher; @Inject @Named(value = "without_grouping_two_decimal") DecimalFormat dfe; @Override protected int getLayout() { return R.layout.main_page_payment_fragment; } @Override protected void init(Bundle savedInstanceState) { if (checkPrinter == null) { checkPrinter = new CheckPrinter(getActivity(), preferencesHelper, databaseManager); checkPrinter.connectDevice(); } presenter.onCreateView(savedInstanceState); df = BaseAppModule.getFormatterWithoutGroupingTwoDecimal(); df.setRoundingMode(RoundingMode.DOWN); df.setDecimalSeparatorAlwaysShown(true); dfnd = BaseAppModule.getFormatterGroupingWithoutDecimalPart(); dfnd.setRoundingMode(RoundingMode.DOWN); decimalFormat = BaseAppModule.getFormatterGrouping(); //decimal format with space // DecimalFormat formatter; // NumberFormat numberFormat = NumberFormat.getNumberInstance(new Locale("RU")); // numberFormat.setMaximumFractionDigits(2); // formatter = (DecimalFormat) numberFormat; // DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols(); // symbols.setGroupingSeparator(' '); // formatter.setDecimalFormatSymbols(symbols); // decimalFormat = formatter; //edit text for input with custom buttons etPaymentAmount.setRawInputType(InputType.TYPE_CLASS_TEXT); etPaymentAmount.setTextIsSelectable(true); //sending event press pay button to presenter. In presenter have 2 state : PAY (payment part), DONE (collect and save) tvPay.setOnClickListener(view1 -> { presenter.payButtonPressed(); }); //switcher for change views: left PAYMENT TYPES (mpList), right PAYMENT LIST (flPaymentList) mpSSwitcher.setClickListener(new MpSecondSwticher.CallbackFromMpSecondSwitcher() { @Override public void onLeftSideClick() { mpList.setVisibility(View.VISIBLE); flPaymentList.setVisibility(View.GONE); } @Override public void onRightSideClick() { mpList.setVisibility(View.GONE); flPaymentList.setVisibility(View.VISIBLE); } }); //sending event press ToBorrow to presenter. llDebtBorrow.setOnClickListener(view12 -> { presenter.onDebtBorrowClicked(); }); if (preferencesHelper.isPrintCheck()) { ivPrint.setColorFilter(Color.parseColor("#419fd9")); tvPrint.setTextColor(Color.parseColor("#419fd9")); tvPrint.setText(R.string.print_check_on_off); } else { ivPrint.setColorFilter(Color.parseColor("#999999")); tvPrint.setTextColor(Color.parseColor("#999999")); tvPrint.setText(R.string.print_check); } //print state dialog, automatic print check or not automatic. Custom print llPrintCheck.setOnClickListener(view -> { if (preferencesHelper.isPrintCheck()) { ivPrint.setColorFilter(Color.parseColor("#999999")); tvPrint.setTextColor(Color.parseColor("#999999")); tvPrint.setText(R.string.print_check); preferencesHelper.setPrintCheck(false); } else { ivPrint.setColorFilter(Color.parseColor("#419fd9")); tvPrint.setTextColor(Color.parseColor("#419fd9")); tvPrint.setText(R.string.print_check_on_off); preferencesHelper.setPrintCheck(true); } }); //edit text change listner used for parsing value in real time, and sending to presenter etPaymentAmount.addTextChangedListener(new NumberTextWatcherPaymentFragment(etPaymentAmount, presenter)); llTips.setOnClickListener(view -> { presenter.onClickedTips(); }); //init number and opertion square buttons: 1 2 3 4 5 6 7 8 9 0 00 < , op1 op2 initButtons(); //get request for order and payed partition list data to OrderListFragment mainPageConnection.setPaymentView(this); mainPageConnection.giveToPaymentFragmentOrderAndPaymentsList(); } /** * refresh data when fragment after hide show * get request for order and payed partition list data to OrderListFragment * this function called from activity, management fragments */ public void refreshData() { mainPageConnection.setPaymentView(this); mainPageConnection.giveToPaymentFragmentOrderAndPaymentsList(); } /** * show ToDebt dialog, to constructor should give Customer and Order data */ @Override public void openAddDebtDialog(DatabaseManager databaseManager, Order order, Customer customer, double toPay) { dialog = new AddDebtDialog(getContext(), customer, databaseManager, order, new AddDebtDialog.onDebtSaveClickListener() { @Override public void onDebtSave(Debt debt) { presenter.onDebtSave(debt); } @Override public void onScanBarcode() { initScan(); } }, toPay, decimalFormat); dialog.show(); } /** * this method for scanning barcode */ public void initScan() { IntentIntegrator.forSupportFragment(this).initiateScan(); } /** * in this method we will take scan result **/ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (intentResult != null) { if (intentResult.getContents() != null) { if (dialog != null) dialog.setScanResult(intentResult.getContents()); } } } /** * init Payment types list to view, and set on item click listener, mpList it is stateable positional list */ @Override public void initPaymentTypes(List<PaymentTypeWithService> paymentTypeWithServices) { mpList.setPayments(paymentTypeWithServices); mpList.setOnPaymentClickListner(position -> { presenter.changePayment(position); }); } /** * this method used for init or update payed parts list */ @Override public void updatePaymentList(List<PayedPartitions> payedPartitions) { if (paymentPartsAdapter == null) { //init paymentPartsAdapter = new PaymentPartsAdapter(payedPartitions, position -> { //sending remove payment part event to presenter presenter.removePayedPart(position); }, decimalFormat); rvPaymentsListHistory.setLayoutManager(new LinearLayoutManager(getContext())); rvPaymentsListHistory.setAdapter(paymentPartsAdapter); ((SimpleItemAnimator) rvPaymentsListHistory.getItemAnimator()).setSupportsChangeAnimations(false); } else { //refresh updatePaymentList(); } } /** * refresh payed parts list */ @Override public void updatePaymentList() { paymentPartsAdapter.notifyDataSetChanged(); } /** * find actually balanceDue, if it is very small value - balance due equals to zero */ @Override public void updateViews(Order order, double totalPayed) { double number = order.getForPayAmmount() - totalPayed; if (number < 0.01) { number = 0; } tvBalanceDue.setText(decimalFormat.format(number)); etPaymentAmount.requestFocus(); } /** * getting new data from OrderList Fragment via MainpageConnector (dagger 2) */ @Override public void getDataFromListOrder(Order order, List<PayedPartitions> payedPartitions) { presenter.incomeNewData(order, payedPartitions); } /** * it method will work when payment amount bigger than balance due * Update views to it done and show Change amount */ @Override public void updateChangeView(double change) { tvBalanceOrChange.setText(getContext().getString(R.string.change)); tvBalanceOrChange.setTextColor(Color.parseColor("#4ac21b")); tvChange.setText(decimalFormat.format(change)); tvChange.setTextColor(Color.parseColor("#4ac21b")); tvPay.setText(getContext().getString(R.string.done)); } /** * it method will work when payment amount smaller than balance due * Update views to it payment and show Balance amount */ @Override public void updateBalanceView(double change) { tvBalanceOrChange.setText(getContext().getString(R.string.balance)); tvBalanceOrChange.setTextColor(Color.parseColor("#df595a")); tvChange.setText(decimalFormat.format(change)); tvChange.setTextColor(Color.parseColor("#df595a")); tvPay.setText(getContext().getString(R.string.pay)); } /** * it method will work when payment amount equals balance due * Update views to it done and show Change amount */ @Override public void updateBalanceZeroText() { tvBalanceOrChange.setText(getContext().getString(R.string.balance)); tvBalanceOrChange.setTextColor(Color.parseColor("#4ac21b")); tvChange.setText(decimalFormat.format(0)); tvChange.setTextColor(Color.parseColor("#4ac21b")); tvPay.setText(getContext().getString(R.string.done)); } /** * it method will work when payment amount is zero * Close payment fragment view */ @Override public void updateCloseText() { tvBalanceOrChange.setText(getContext().getString(R.string.balance)); tvBalanceOrChange.setTextColor(Color.parseColor("#4ac21b")); tvChange.setText(decimalFormat.format(0)); tvChange.setTextColor(Color.parseColor("#4ac21b")); tvPay.setText(getContext().getString(R.string.close)); } /** * Close payment fragment (Self) */ @Override public void closeSelf() { ((MainPosPageActivity) getActivity()).hidePaymentFragment(); } /** * clear payment amount when click pay button * sending event "OrderPayed" (ever payment operation will send) */ @Override public void onPayedPartition() { etPaymentAmount.setText(""); mainPageConnection.onPayedPartition(); } @Override public void closeOrder(Order order, List<PayedPartitions> payedPartitions, Debt debt) { closeSelf(); mainPageConnection.onCloseOrder(order, payedPartitions, debt); } @Override public void updateCustomer(Customer customer) { mainPageConnection.updateCustomer(customer); } @Override public void showDebtDialog() { ivDebt.setImageResource(R.drawable.borrow); tvDebt.setText(getContext().getString(R.string.loan)); } @Override public void hideDebtDialog() { ivDebt.setImageResource(R.drawable.cancel_customer); tvDebt.setText(getContext().getString(R.string.cancel_barrow)); } @Override public void openTipsDialog(TipsDialog.OnClickListener listener, double change) { TipsDialog tipsDialog = new TipsDialog(getContext(), listener, change, databaseManager); tipsDialog.show(); } @Override public void enableTipsButton() { ivTips.setImageResource(R.drawable.ic_coin_stack); tvTips.setText(getContext().getString(R.string.coin)); } @Override public void disableTipsButton() { ivTips.setImageResource(R.drawable.cancel_customer); tvTips.setText(getContext().getString(R.string.cancel_tips)); } @Override public void updateOrderListDetialsPanel() { mainPageConnection.onPayedPartition(); } @Override public void onNewOrder() { presenter.onNewOrder(); } @Override public void sendDataToPaymentFragmentWhenEdit(Order order, List<PayedPartitions> payedPartitions, Debt debt) { presenter.sendDataToPaymentFragmentWhenEdit(order, payedPartitions, debt); } @Override public void onHoldOrderClicked() { presenter.onHoldOrderClicked(); } @Override public void onHoldOrderSendingData(Order order, List<PayedPartitions> payedPartitions, Debt debt) { mainPageConnection.onHoldOrderSendingData(order, payedPartitions, debt); } @Override public void openWarningDialog(String text) { UIUtils.showAlert(getContext(), getContext().getString(R.string.ok), getContext().getString(R.string.warning), text, () -> { }); } @Override public void setCustomer(Customer customer) { presenter.setCustomer(customer); } /** * setting payment to Payment amount text view * it used when payment amount set from pragmatically */ @Override public void updatePaymentText(double payment) { etPaymentAmount.setText(dfe.format(payment)); etPaymentAmount.setSelection(etPaymentAmount.getText().length()); } @BindView(R.id.btnDot) MpNumPad btnDot; @BindView(R.id.btnDoubleZero) MpNumPad btnDoubleZero; @BindView(R.id.btnZero) MpNumPad btnZero; @BindView(R.id.btnOne) MpNumPad btnOne; @BindView(R.id.btnTwo) MpNumPad btnTwo; @BindView(R.id.btnThree) MpNumPad btnThree; @BindView(R.id.btnFour) MpNumPad btnFour; @BindView(R.id.btnFive) MpNumPad btnFive; @BindView(R.id.btnSix) MpNumPad btnSix; @BindView(R.id.btnSeven) MpNumPad btnSeven; @BindView(R.id.btnEight) MpNumPad btnEight; @BindView(R.id.btnNine) MpNumPad btnNine; @BindView(R.id.btnBackSpace) LinearLayout btnBackSpace; @BindView(R.id.btnFirstOptional) MpNumPadSecond btnFirstOptional; @BindView(R.id.btnSecondOptional) MpNumPadSecond btnSecondOptional; @BindView(R.id.btnAllInOne) MpNumPadSecond btnAllInOne; /** * initialization keypad buttons */ private void initButtons() { //getting optional buttons from Shared Preference //It is used for flexible setting optional buttons from settings activity btnFirstOptional.setCurrency(databaseManager.getMainCurrency().getAbbr()); btnFirstOptional.setValue(decimalFormat.format(preferencesHelper.getFirstOptionalPaymentButton())); btnSecondOptional.setCurrency(databaseManager.getMainCurrency().getAbbr()); btnSecondOptional.setValue(decimalFormat.format(preferencesHelper.getSecondOptionalPaymentButton())); tvBalanceDueCurrency.setText(databaseManager.getMainCurrency().getAbbr()); tvChangeCurrency.setText(databaseManager.getMainCurrency().getAbbr()); tvPaymentCurrency.setText(databaseManager.getMainCurrency().getAbbr()); btnFirstOptional.setOnClickListener(view -> { //this part of code used for clearing text when some text part selected if (etPaymentAmount.getSelectionStart() != etPaymentAmount.getSelectionEnd()) { etPaymentAmount.getText().clear(); } presenter.pressFirstOptional(); }); btnSecondOptional.setOnClickListener(view -> { if (etPaymentAmount.getSelectionStart() != etPaymentAmount.getSelectionEnd()) { etPaymentAmount.getText().clear(); } presenter.pressSecondOptional(); }); //this button used for input all balance due value in one btnAllInOne.setOnClickListener(view -> { presenter.pressAllAmount(); }); //sending input key to method btnOne.setOnClickListener(view -> { pressedKey("1"); }); btnTwo.setOnClickListener(view -> { pressedKey("2"); }); btnThree.setOnClickListener(view -> { pressedKey("3"); }); btnFour.setOnClickListener(view -> { pressedKey("4"); }); btnFive.setOnClickListener(view -> { pressedKey("5"); }); btnSix.setOnClickListener(view -> { pressedKey("6"); }); btnSeven.setOnClickListener(view -> { pressedKey("7"); }); btnEight.setOnClickListener(view -> { pressedKey("8"); }); btnNine.setOnClickListener(view -> { pressedKey("9"); }); btnZero.setOnClickListener(view -> { pressedKey("0"); }); btnDoubleZero.setOnClickListener(view -> { pressedKey("00"); }); btnDot.setOnClickListener(view -> { pressedKey(decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() + ""); }); btnBackSpace.setOnLongClickListener(view -> { etPaymentAmount.getText().clear(); return true; }); btnBackSpace.setOnClickListener(view -> { if (etPaymentAmount.getSelectionStart() != etPaymentAmount.getSelectionEnd()) { etPaymentAmount.getText().clear(); } else { etPaymentAmount.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)); } }); } /** * checking for not input when comma have one more */ private void pressedKey(String key) { if (key.equals(decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() + "")) { if (etPaymentAmount.getText().toString().contains(decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() + "")) return; } if (etPaymentAmount.getSelectionStart() != etPaymentAmount.getSelectionEnd()) { etPaymentAmount.getText().clear(); } etPaymentAmount.getText().insert(etPaymentAmount.getSelectionStart(), key); if (key.equals(decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() + "")) { etPaymentAmount.setSelection(etPaymentAmount.getText().length()); } } /** * de initialization view from mainpageConnection */ @Override public void onDestroy() { mainPageConnection.setPaymentView(null); super.onDestroy(); } }
package com.greenglobal.eoffice.domain.application.congvandi.commands; import static java.util.Collections.singletonList; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import com.greenglobal.eoffice.domain.application.congvandi.commands.create.CreateCongVanDiCmd; import com.greenglobal.eoffice.domain.application.congvandi.commands.update.HuyDuyetCongVanDiCmd; import com.greenglobal.eoffice.domain.application.congvandi.commands.update.KyDuyetCongVanDiCmd; import com.greenglobal.eoffice.domain.application.congvandi.commands.update.TrinhCongVanDiCmd; import com.greenglobal.eoffice.domain.application.congvandi.events.entities.CongVanDiApproved; import com.greenglobal.eoffice.domain.application.congvandi.events.entities.CongVanDiCreated; import com.greenglobal.eoffice.domain.application.congvandi.events.entities.CongVanDiDenied; import com.greenglobal.eoffice.domain.application.congvandi.events.entities.CongVanDiRequestSent; import com.greenglobal.eoffice.domain.core.entities.CongVanDi; import com.greenglobal.eoffice.domain.core.events.DomainEvent; import com.greenglobal.eoffice.infrastructure.broker.EventProducer; import com.greenglobal.eoffice.infrastructure.repository.CongVanDiRepository; import org.springframework.beans.factory.annotation.Autowired; public class CongVanDiCmdHandlerImpl implements CongVanDiCmdHandler { @Autowired private EventProducer producer; @Autowired private CongVanDiRepository congVanDiRepo; /** * Tạo mới CongVanDi command. */ public void handle(CreateCongVanDiCmd cmd) { var now = new Date(); var entity = new CongVanDi(); entity.setSoCongVan(cmd.getSoCongVan()); entity.setNgayCongVan(cmd.getNgayCongVan()); entity.setNoiDung(cmd.getNoiDung()); entity.setTrichYeu(cmd.getTrichYeu()); entity.setTrangThai(0); entity.setCreatedAt(now); entity.setModifiedAt(now); entity.setIsDeleted(false); this.congVanDiRepo.create(entity); producer.publish(new CongVanDiCreated(entity)); System.out.printf("Publish event %s: %s\n", CongVanDiCreated.class.getSimpleName(), new SimpleDateFormat("dd-mm-yyyy hh:mm:ss.SSS").format(new Date())); } /** * Trình CongVanDi command */ public void handle(TrinhCongVanDiCmd cmd) { var now = new Date(); var entity = this.congVanDiRepo.get(cmd.getId()); entity.setTrangThai(cmd.getTrangThai()); entity.setModifiedAt(now); this.congVanDiRepo.update(entity); var event = new CongVanDiRequestSent(cmd.getId(), cmd.getTrangThai()); producer.publish(event); System.out.printf("Publish event %s: %s\n", CongVanDiRequestSent.class.getSimpleName(), new SimpleDateFormat("dd-mm-yyyy hh:mm:ss.SSS").format(new Date())); } /** * Ký duyệt CongVanDi command */ public void handle(KyDuyetCongVanDiCmd cmd) { var now = new Date(); var entity = this.congVanDiRepo.get(cmd.getId()); entity.setTrangThai(cmd.getTrangThai()); entity.setModifiedAt(now); this.congVanDiRepo.update(entity); var event = new CongVanDiApproved(cmd.getId(), cmd.getTrangThai()); producer.publish(event); System.out.printf("Publish event %s: %s\n", CongVanDiApproved.class.getSimpleName(), new SimpleDateFormat("dd-mm-yyyy hh:mm:ss.SSS").format(new Date())); } /** * Huỷ duyệt CongVanDi command */ public void handle(HuyDuyetCongVanDiCmd cmd) { var now = new Date(); var entity = this.congVanDiRepo.get(cmd.getId()); entity.setTrangThai(0); entity.setModifiedAt(now); this.congVanDiRepo.update(entity); var event = new CongVanDiDenied(cmd.getId(), cmd.getNoiDung()); producer.publish(event); System.out.printf("Publish event %s: %s\n", CongVanDiDenied.class.getSimpleName(), new SimpleDateFormat("dd-mm-yyyy hh:mm:ss.SSS").format(new Date())); } private List<DomainEvent> validate(final CongVanDi entity) { return singletonList(new CongVanDiCreated(entity)); } }
/* * Copyright (C) 2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.importer.migration; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.importer.MirrorProperties; import com.hedera.mirror.importer.db.DBProperties; import com.hederahashgraph.api.proto.java.Key; import jakarta.inject.Named; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import lombok.Data; import lombok.Getter; import org.flywaydb.core.api.MigrationVersion; import org.springframework.context.annotation.Lazy; import org.springframework.jdbc.core.DataClassRowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.transaction.support.TransactionOperations; @Named public class SyntheticCryptoTransferApprovalMigration extends AsyncJavaMigration<Long> { // The contract id of the first synthetic transfer that could have exhibited this problem private static final long GRANDFATHERED_ID = 2119900L; // The created timestamp of the grandfathered id contract static final long LOWER_BOUND_TIMESTAMP = 1680284879342064922L; // This problem was fixed by services release 0.38.10, this is last timestamp before that release static final long UPPER_BOUND_TIMESTAMP = 1686243920981874002L; private static final long TIMESTAMP_INCREMENT = Duration.ofDays(1).toNanos(); // 1 day in nanoseconds which will yield 69 async iterations private static final String TRANSFER_SQL = """ with contractresults as ( select consensus_timestamp, contract_id from contract_result where consensus_timestamp > :lower_bound and consensus_timestamp <= :upper_bound and contract_id >= :grandfathered_id ), cryptotransfers as ( select ct.consensus_timestamp, cast(null as int) as index, entity_id as sender, cr.contract_id, cast(null as bigint) as token_id, 'CRYPTO_TRANSFER' as transfer_type from crypto_transfer ct join contractresults cr on cr.consensus_timestamp = ct.consensus_timestamp where cr.contract_id <> ct.entity_id and ct.is_approval = false and ct.amount < 0 ), tokentransfers as ( select t.consensus_timestamp, cast(null as int) as index, account_id as sender, cr.contract_id, token_id, 'TOKEN_TRANSFER' as transfer_type from token_transfer t join contractresults cr on cr.consensus_timestamp = t.consensus_timestamp where cr.contract_id <> account_id and is_approval = false and t.amount < 0 ), nfttransfers as ( select t.consensus_timestamp, arr.index - 1 as index, (arr.item->>'sender_account_id')::bigint as sender, cr.contract_id, cast(null as bigint) as token_id, 'NFT_TRANSFER' as transfer_type from transaction t join contractresults cr on cr.consensus_timestamp = t.consensus_timestamp, jsonb_array_elements(nft_transfer) with ordinality arr(item, index) where cr.contract_id <> (arr.item->>'sender_account_id')::bigint and (arr.item->>'is_approval')::boolean = false ), entity as ( select key, id, timestamp_range from entity where key is not null union all select key, id, timestamp_range from entity_history where key is not null ), cryptoentities as ( select ct.*, e.key from cryptotransfers ct join entity e on e.timestamp_range @> ct.consensus_timestamp::bigint where e.id = ct.sender ), tokenentities as ( select t.*, e.key from tokentransfers t join entity e on e.timestamp_range @> t.consensus_timestamp::bigint where e.id = t.sender ), nftentities as ( select nft.*, e.key from nfttransfers nft join entity e on e.timestamp_range @> nft.consensus_timestamp::bigint where e.id = nft.sender ) select * from cryptoentities union all select * from tokenentities union all select * from nftentities order by consensus_timestamp asc """; private static final String UPDATE_CRYPTO_TRANSFER_SQL = """ update crypto_transfer set is_approval = true where consensus_timestamp = :consensus_timestamp and entity_id = :sender """; private static final String UPDATE_NFT_TRANSFER_SQL = """ update transaction set nft_transfer = jsonb_set(nft_transfer, array[:index::text, 'is_approval'], 'true', false) where consensus_timestamp = :consensus_timestamp """; private static final String UPDATE_TOKEN_TRANSFER_SQL = """ update token_transfer set is_approval = true where consensus_timestamp = :consensus_timestamp and token_id = :token_id and account_id = :sender """; private enum TRANSFER_TYPE { CRYPTO_TRANSFER, NFT_TRANSFER, TOKEN_TRANSFER } private static final DataClassRowMapper<SyntheticCryptoTransferApprovalMigration.ApprovalTransfer> resultRowMapper = new DataClassRowMapper<>(ApprovalTransfer.class); private final MirrorProperties mirrorProperties; private final NamedParameterJdbcTemplate transferJdbcTemplate; @Getter private final TransactionOperations transactionOperations; @Lazy public SyntheticCryptoTransferApprovalMigration( DBProperties dbProperties, MirrorProperties mirrorProperties, NamedParameterJdbcTemplate transferJdbcTemplate, TransactionOperations transactionOperations) { super(mirrorProperties.getMigration(), transferJdbcTemplate, dbProperties.getSchema()); this.mirrorProperties = mirrorProperties; this.transferJdbcTemplate = transferJdbcTemplate; this.transactionOperations = transactionOperations; } @Override public String getDescription() { return "Update the is_approval value for synthetic transfers"; } @Override protected MigrationVersion getMinimumVersion() { // The version where the nft_transfer table was migrated to the transaction table return MigrationVersion.fromVersion("1.81.0"); } @Override protected Long getInitial() { return LOWER_BOUND_TIMESTAMP; } @Override protected Optional<Long> migratePartial(Long lowerBound) { if (!MirrorProperties.HederaNetwork.MAINNET.equalsIgnoreCase(mirrorProperties.getNetwork())) { log.info("Skipping migration since it only applies to mainnet"); return Optional.empty(); } long count = 0; var migrationErrors = new ArrayList<String>(); long upperBound = Math.min(lowerBound + TIMESTAMP_INCREMENT, UPPER_BOUND_TIMESTAMP); Map<String, Long> queryParamMap = Map.of("lower_bound", lowerBound, "upper_bound", upperBound, "grandfathered_id", GRANDFATHERED_ID); try { var transfers = transferJdbcTemplate.query(TRANSFER_SQL, queryParamMap, resultRowMapper); for (ApprovalTransfer transfer : transfers) { if (!isAuthorizedByContractKey(transfer, migrationErrors)) { // set is_approval to true String updateSql; var updateParamMap = new HashMap<String, Number>(); updateParamMap.put("consensus_timestamp", transfer.consensusTimestamp); if (transfer.transferType == TRANSFER_TYPE.CRYPTO_TRANSFER) { updateSql = UPDATE_CRYPTO_TRANSFER_SQL; updateParamMap.put("sender", transfer.sender); } else if (transfer.transferType == TRANSFER_TYPE.NFT_TRANSFER) { updateSql = UPDATE_NFT_TRANSFER_SQL; updateParamMap.put("index", transfer.index); } else { updateSql = UPDATE_TOKEN_TRANSFER_SQL; updateParamMap.put("sender", transfer.sender); updateParamMap.put("token_id", transfer.tokenId); } transferJdbcTemplate.update(updateSql, updateParamMap); count++; } } } catch (Exception e) { log.error("Error migrating synthetic transfer approvals", e); return Optional.empty(); } log.info("Updated {} synthetic transfer approvals", count); migrationErrors.forEach(log::error); return upperBound == UPPER_BOUND_TIMESTAMP ? Optional.empty() : Optional.of(upperBound); } /** * A return value of false denotes that the transfer's isApproval value should be set to true */ private boolean isAuthorizedByContractKey(ApprovalTransfer transfer, List<String> migrationErrors) { Key parsedKey; try { parsedKey = Key.parseFrom(transfer.key); } catch (Exception e) { migrationErrors.add(String.format( "Unable to determine if transfer should be migrated. Entity id %d at %d: %s", transfer.sender, transfer.consensusTimestamp, e.getMessage())); // Do not update the isApproval value return true; } // If the threshold is greater than one ignore it if (!parsedKey.hasThresholdKey() || parsedKey.getThresholdKey().getThreshold() > 1) { // Update the isApproval value to true return false; } return isAuthorizedByThresholdKey(parsedKey, transfer.contractId); } private boolean isAuthorizedByThresholdKey(Key parsedKey, long contractId) { var keys = parsedKey.getThresholdKey().getKeys().getKeysList(); for (var key : keys) { if (key.hasContractID() && EntityId.of(key.getContractID()).getId() == contractId) { // Do not update the isApproval value return true; } } // Update the isApproval value to true return false; } @Data static class ApprovalTransfer { private Long consensusTimestamp; private Long contractId; private Integer index; private byte[] key; private Long sender; private Long tokenId; private TRANSFER_TYPE transferType; } }
package lab_11_x3; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; @SuppressWarnings("serial") public class Stuff extends JFrame implements ActionListener{ public static final int WIDTH=600; public static final int HEIGHT=300; private JTextArea theText; private String memo1="No memo1"; private String memo2="No memo2"; public Stuff() { setSize(WIDTH,HEIGHT); setTitle("Memo Saver"); Container contentPane=getContentPane(); contentPane.setLayout(new BorderLayout()); JPanel buttonPanel=new JPanel(); buttonPanel.setBackground(Color.WHITE); buttonPanel.setLayout(new FlowLayout()); JButton memo1Button=new JButton("Save memo1"); memo1Button.addActionListener(this); buttonPanel.add(memo1Button); JButton memo2Button=new JButton("Save memo2"); memo2Button.addActionListener(this); buttonPanel.add(memo2Button); JButton clearButton=new JButton("Clear"); clearButton.addActionListener(this); buttonPanel.add(clearButton); JButton get1Button=new JButton("Get Memo1"); get1Button.addActionListener(this); buttonPanel.add(get1Button); JButton get2Button=new JButton("Get Memo2"); get2Button.addActionListener(this); buttonPanel.add(get2Button); contentPane.add(buttonPanel,BorderLayout.SOUTH); JPanel textPanel=new JPanel(); textPanel.setBackground(Color.BLUE); theText=new JTextArea(10,40); theText.setBackground(Color.WHITE); textPanel.add(theText); contentPane.add(textPanel,BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String actionCommand=e.getActionCommand(); if(actionCommand.equals("Save memo1")) memo1=theText.getText(); else if(actionCommand.equals("Save memo2")) memo2=theText.getText(); else if(actionCommand.equals("Clear")) theText.setText(""); else if(actionCommand.equals("Get Memo1")) theText.setText(memo1); else if(actionCommand.equals("Get Memo2")) theText.setText(memo2); } public static void main(String[] args) { Stuff guiMemo=new Stuff(); guiMemo.setVisible(true); } }
package pe.edu.upeu.hotel.dao; import java.util.List; import pe.edu.upeu.hotel.entity.Login; import pe.edu.upeu.hotel.entity.Usuario; public interface LoginDao { Login usuario (Usuario usuario); }
package com.google.android.gms.common.api; import android.os.Looper; import android.util.Pair; import com.google.android.gms.common.internal.q; import com.google.android.gms.common.internal.w; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public abstract class j<R extends g> implements e<R> { private volatile R aKA; private volatile boolean aKB; private boolean aKC; private boolean aKD; private q aKE; private final Object aKv = new Object(); protected final a<R> aKw; private final CountDownLatch aKx = new CountDownLatch(1); private final ArrayList<Object> aKy = new ArrayList(); private h<R> aKz; protected j(Looper looper) { this.aKw = new a(looper); } private void b(R r) { this.aKA = r; this.aKE = null; this.aKx.countDown(); g gVar = this.aKA; if (this.aKz != null) { this.aKw.removeMessages(2); if (!this.aKC) { a aVar = this.aKw; aVar.sendMessage(aVar.obtainMessage(1, new Pair(this.aKz, oH()))); } } Iterator it = this.aKy.iterator(); while (it.hasNext()) { it.next(); } this.aKy.clear(); } private static void c(g gVar) { if (gVar instanceof f) { try { ((f) gVar).release(); } catch (RuntimeException e) { new StringBuilder("Unable to release ").append(gVar); } } } private boolean hv() { return this.aKx.getCount() == 0; } private R oH() { R r; boolean z = true; synchronized (this.aKv) { if (this.aKB) { z = false; } w.d(z, "Result has already been consumed."); w.d(hv(), "Result is not ready."); r = this.aKA; this.aKA = null; this.aKz = null; this.aKB = true; } oG(); return r; } public final void a(Status status) { synchronized (this.aKv) { if (!hv()) { a(b(status)); this.aKD = true; } } } public final void a(R r) { boolean z = true; synchronized (this.aKv) { if (this.aKD || this.aKC) { c(r); return; } w.d(!hv(), "Results have already been set"); if (this.aKB) { z = false; } w.d(z, "Result has already been consumed"); b((g) r); } } public abstract R b(Status status); public final R b(TimeUnit timeUnit) { boolean z = true; boolean z2 = 2 <= 0 || Looper.myLooper() != Looper.getMainLooper(); w.d(z2, "await must not be called on the UI thread when time is greater than zero."); if (this.aKB) { z = false; } w.d(z, "Result has already been consumed."); try { if (!this.aKx.await(2, timeUnit)) { a(Status.aKs); } } catch (InterruptedException e) { a(Status.aKq); } w.d(hv(), "Result is not ready."); return oH(); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final void cancel() { /* r2 = this; r1 = r2.aKv; monitor-enter(r1); r0 = r2.aKC; Catch:{ all -> 0x0023 } if (r0 != 0) goto L_0x000b; L_0x0007: r0 = r2.aKB; Catch:{ all -> 0x0023 } if (r0 == 0) goto L_0x000d; L_0x000b: monitor-exit(r1); Catch:{ all -> 0x0023 } L_0x000c: return; L_0x000d: r0 = r2.aKA; Catch:{ all -> 0x0023 } c(r0); Catch:{ all -> 0x0023 } r0 = 0; r2.aKz = r0; Catch:{ all -> 0x0023 } r0 = 1; r2.aKC = r0; Catch:{ all -> 0x0023 } r0 = com.google.android.gms.common.api.Status.aKt; Catch:{ all -> 0x0023 } r0 = r2.b(r0); Catch:{ all -> 0x0023 } r2.b(r0); Catch:{ all -> 0x0023 } monitor-exit(r1); Catch:{ all -> 0x0023 } goto L_0x000c; L_0x0023: r0 = move-exception; monitor-exit(r1); Catch:{ all -> 0x0023 } throw r0; */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.common.api.j.cancel():void"); } public final R oE() { boolean z = true; w.d(Looper.myLooper() != Looper.getMainLooper(), "await must not be called on the UI thread"); if (this.aKB) { z = false; } w.d(z, "Result has already been consumed"); try { this.aKx.await(); } catch (InterruptedException e) { a(Status.aKq); } w.d(hv(), "Result is not ready."); return oH(); } protected void oG() { } }
// Sun Certified Java Programmer // Chapter 2, P125 // Object Orientation interface Vroom extends Fi, Baz { }
package net.crunchdroid.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; @Data @NoArgsConstructor @AllArgsConstructor @Entity public class ProduitFacture { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) private Abonne abonne; @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) private Produit produit; }
package com.fleet.webssh.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import javax.annotation.Resource; /** * @author April Han */ @Configuration @EnableWebSocket public class WebSSHWebSocketConfig implements WebSocketConfigurer { @Resource WebSSHWebSocketHandler webSSHWebSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSSHWebSocketHandler, "/webssh") .setAllowedOrigins("*"); } }
public class Main { public static void main(String[] args) { Test a=new Test(); a.jar_test(); System.out.println("Main class test success!"); } }
package compilador.estruturas; import java.util.Arrays; import compilador.helper.ArrayHelper; public class String { /** * A sequncia de caracteres que comp›em a string. */ private char[] chars; public String(char[] chars) { this.chars = new char[chars.length]; System.arraycopy(chars, 0, this.chars, 0, this.chars.length); } /** * @return o tamanho da string. */ public int tamanho() { return this.chars.length; } /** * @return o array de chars que representa a string. */ public char[] toCharArray() { return this.chars; } public void imprimir() { for(int i = 0; i < this.chars.length; i++) System.out.print(this.chars[i]); } public void imprimirln() { this.imprimir(); System.out.println(); } public String append(char[] ch) { return new String(ArrayHelper.concatenarVetoresChar(this.chars, ch)); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; String other = (String) obj; if (!ArrayHelper.compararVetoresChar(this.chars, other.toCharArray())) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(chars); return result; } @Override public java.lang.String toString() { java.lang.String s = ""; for(int i = 0; i < this.chars.length; i++) s += this.chars[i]; return s; } }
/** * Created by lzj on 2016/11/2. * 二分检索 */ public class BiSearch { /** * 二分检索查找数组a中是否有found值,有返回found在a中的下标,无返回-1 * @param a 数组a(已排序) * @param low 查找低位 * @param high 查找高位 * @param found 带查找的值 * @return found在a中的下标(从0开始)或-1 */ public static int bisearch(int[] a, int low, int high, int found) { if (low > high) return -1; int m = (low + high) / 2; if (m >= a.length) return -1; if (a[m] == found) return m; int f = bisearch(a, low, m - 1, found); if (f > -1) return f; else return bisearch(a, m + 1, high, found); } public static void main(String[] args) { System.out.println(bisearch(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 0, 10, 5)); ; } }
package com.udacity.hnoct.stockhawk.graph; import com.github.mikephil.charting.components.AxisBase; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.udacity.hnoct.stockhawk.data.PrefUtils; /** * Created by hnoct on 1/24/2017. */ public class DateAxisValueFormatter implements IAxisValueFormatter { int scale; public DateAxisValueFormatter(int scale) { this.scale = scale; } @Override public String getFormattedValue(float value, AxisBase axis) { if (scale == 2) { return PrefUtils.getFormattedMonthDay((long) value); } else if (scale == 1) { return PrefUtils.getFormattedMonthYear((long) value); } return null; } public void setScale(int scale) { this.scale = scale; } public int getScale() { return scale; } }
package com.polsl.edziennik.desktopclient.controller.teacher.students; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import com.polsl.edziennik.desktopclient.controller.teacher.TeacherAction; import com.polsl.edziennik.desktopclient.view.teacher.StudentsManagementForTeacher; import com.polsl.edziennik.desktopclient.view.teacher.TeacherMainView; /** * * Klasa odpowiedzialna za wykonanie akcji uruchomienia modułu studentów na * poziomie prowadzącego * * @author Mateusz Gołąb * */ public class StudentManagementAction extends TeacherAction { private static String title = menu.getString("view"); public StudentManagementAction(TeacherMainView parent) { super(title); this.parent = parent; } @Override public void actionPerformed(ActionEvent e) { StudentsManagementForTeacher studenciPanel = new StudentsManagementForTeacher(); parent.addTab(menu.getString("Students") + " ", studenciPanel, new ImageIcon(bundle.getString("StudentsIcon"))); parent.invalidate(); parent.validate(); } }
package com.ifisolution.cmsmanagerment.entities; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name = "cms_topic") public class Topic { @Id private int id; @Column(name="name") @NotEmpty(message = "name not be empty") private String name; @Column(name="parent_ref_id") @NotEmpty(message = "parent ref id not be empty") private int parentRefId; @Column(name="created_at") private Timestamp createdAt; // one to many "topic_tracking" @JsonIgnore @OneToMany(fetch = FetchType.LAZY, mappedBy = "topic") private List<TopicTracking> listTopic = new ArrayList<>(); // one to many "cms_news_header" @JsonIgnore @OneToMany(fetch = FetchType.LAZY, mappedBy = "topic") private List<NewsHeader> newsHeader = new ArrayList<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getParentRefId() { return parentRefId; } public void setParentRefId(int parentRefId) { this.parentRefId = parentRefId; } public Timestamp getCreatedAt() { return createdAt; } public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; } public List<TopicTracking> getListTopic() { return listTopic; } public void setListTopic(List<TopicTracking> listTopic) { this.listTopic = listTopic; } public List<NewsHeader> getNewsHeader() { return newsHeader; } public void setNewsHeader(List<NewsHeader> newsheader) { this.newsHeader = newsheader; } }
package com.gcteam.yandextranslate; import com.gcteam.yandextranslate.domain.Direction; import com.gcteam.yandextranslate.domain.Language; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; /** * Created by turist on 17.04.2017. */ public class DirectionTests { private Direction direction; @Before public void setUp() throws Exception { direction = new Direction(new Language("en", "Eng"), new Language("ru", "Rus")); } @Test public void direction_field() throws Exception { assertEquals(direction.from.code, "en"); assertEquals(direction.to.code, "ru"); } @Test public void direction_toString() throws Exception { assertEquals(direction.toString(), "en-ru"); } @Test public void direction_inverse() throws Exception { Direction inv = direction.inverse(); assertEquals(inv.from.code, "ru"); assertEquals(inv.to.code, "en"); } @Test public void direction_changeFrom() throws Exception { Direction inv = direction.changeFrom(new Language("fr", "Fr")); assertEquals(inv.from.code, "fr"); assertEquals(inv.to.code, "ru"); } @Test public void direction_changeTo() throws Exception { Direction inv = direction.changeTo(new Language("fr", "Fr")); assertEquals(inv.to.code, "fr"); assertEquals(inv.from.code, "en"); } }
package pro.eddiecache.utils.props; import java.io.InputStream; import java.util.Properties; public abstract class PropertyLoader { private static final String SUFFIX = ".conf"; private static final String SUFFIX_PROPERTIES = ".properties"; public static Properties loadProperties(String name, ClassLoader loader) { boolean isConfSuffix = true; if (name == null) { throw new IllegalArgumentException("null input: name"); } ClassLoader classLoader = (loader == null) ? ClassLoader.getSystemClassLoader() : loader; String fileName = name.startsWith("/") ? name.substring(1) : name; if (fileName.endsWith(SUFFIX)) { fileName = fileName.substring(0, fileName.length() - SUFFIX.length()); } if (fileName.endsWith(SUFFIX_PROPERTIES)) { fileName = fileName.substring(0, fileName.length() - SUFFIX_PROPERTIES.length()); isConfSuffix = false; } Properties result = null; InputStream in = null; try { fileName = fileName.replace('.', '/'); if (!fileName.endsWith(SUFFIX) && isConfSuffix) { fileName = fileName.concat(SUFFIX); } else if (!fileName.endsWith(SUFFIX_PROPERTIES) && !isConfSuffix) { fileName = fileName.concat(SUFFIX_PROPERTIES); } in = classLoader.getResourceAsStream(fileName); if (in != null) { result = new Properties(); result.load(in); } } catch (Exception e) { result = null; } finally { if (in != null) try { in.close(); } catch (Throwable ignore) { } } if (result == null) { throw new IllegalArgumentException("Could not load [" + fileName + "]."); } return result; } public static Properties loadProperties(final String name) { return loadProperties(name, Thread.currentThread().getContextClassLoader()); } private PropertyLoader() { super(); } }
package de.lise.terradoc.core.report.elements; import de.lise.terradoc.core.report.ReportDocument; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; public class TableOfContents implements ReportElement { private final ReportDocument reportDocument; public TableOfContents(ReportDocument reportDocument) { this.reportDocument = reportDocument; } private void getHeadings(List<HeadingElement> result, TraversableElement element) { for(ReportElement child : element.getAllChildren()) { if(child instanceof HeadingElement) { result.add((HeadingElement) child); } else if(child instanceof TraversableElement) { getHeadings(result, (TraversableElement) child); } } } @Override public void appendHtml(StringWriter writer) { List<HeadingElement> headings = new ArrayList<>(); getHeadings(headings, reportDocument); writer.append("<div id=\"toc\" class=\"toc\"><div id=\"toctitle\">Table of Contents</div><ul>"); for(HeadingElement e : headings) { writer.append(String.format("<li style=\"padding-left: %dem\"><a href=\"#%s\">", e.getLevel() * 2, e.getIdentifier())).append(e.getPrefix()).append(" ").append(e.getTextElement().getText()).append("</a></li>"); } writer.append("</div></ul>"); } @Override public void appendAsciidoc(StringWriter writer) { writer.append(":toc:"); writer.append(NEW_LINE).append(NEW_LINE); } }
package kh.picsell.dao; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import kh.picsell.dto.NoticeFileDTO; import kh.picsell.dto.PieceNoticeFileDTO; @Repository public class PieceNoticeFileDAO { @Autowired private SqlSessionTemplate jdbc; public void fileUpload(PieceNoticeFileDTO pieceFileDto) { jdbc.insert("PieceNoticeFile.fileUpload", pieceFileDto); } public List<PieceNoticeFileDTO> selectAll(int pieceNoticeFile_parentSeq ){ return jdbc.selectList("PieceNoticeFile.selectAll", pieceNoticeFile_parentSeq); } public List<String> getFileSysName(int pieceNoticeFile_parentSeq){ return jdbc.selectList("PieceNoticeFile.getFileSysName", pieceNoticeFile_parentSeq); } public void delete(int pieceNoticeFile_parentSeq) { jdbc.delete("PieceNoticeFile.delete", pieceNoticeFile_parentSeq); } public void deleteFile(int pieceNoticeFile_seq) { jdbc.delete("PieceNoticeFile.deleteFile", pieceNoticeFile_seq); } }
package br.inf.ufg.mddsm.controller.img; import java.util.ArrayList; public class AlloyValidator implements Validator { @Override public ArrayList<IntentModel> validateModels(ArrayList<IntentModel> models, Object... params) { DSC dsc = (DSC) params[0]; ArrayList<IntentModel> validModels = new ArrayList<IntentModel>(); for (int i = 0; i < models.size(); i++){ IntentModel model = returnIfValid(models.get(i), dsc); if (model != null) validModels.add(model); } return validModels; } public IntentModel returnIfValid(IntentModel model, DSC dsc){ return model; } }
package com.tencent.mm.g.a; public final class qs$b { public boolean bJm = false; }
package com.sporsimdi.model.entity; import javax.persistence.Entity; import javax.persistence.Table; import com.sporsimdi.model.base.ExtendedModel; @Table @Entity public class TesisTipi extends ExtendedModel { private static final long serialVersionUID = 8986161490957095179L; private String adi; public String getAdi() { return adi; } public void setAdi(String adi) { this.adi = adi; } }
package com.tencent.mm.plugin.aa; import android.widget.Toast; import com.tencent.mm.g.a.bp; import com.tencent.mm.plugin.aa.b.4; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.protocal.c.c; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.vending.c.a; class b$4$1 implements a<Void, com.tencent.mm.ab.a.a<c>> { final /* synthetic */ bp ezA; final /* synthetic */ 4 ezB; b$4$1(4 4, bp bpVar) { this.ezB = 4; this.ezA = bpVar; } public final /* synthetic */ Object call(Object obj) { com.tencent.mm.ab.a.a aVar = (com.tencent.mm.ab.a.a) obj; x.i("MicroMsg.SubCoreAA", "close aa urge notify cgiback, errType: %s, errCode: %s", new Object[]{Integer.valueOf(aVar.errType), Integer.valueOf(aVar.errCode)}); if (aVar.errType == 0 && aVar.errCode == 0) { x.i("MicroMsg.SubCoreAA", "close aa urge notify success"); if (((c) aVar.dIv).hUm > 0 && !bi.oW(((c) aVar.dIv).hUn)) { Toast.makeText(ad.getContext(), ((c) aVar.dIv).hUn, 0).show(); h.mEJ.a(407, 29, 1, false); } else if (((c) aVar.dIv).hUm == 0) { Toast.makeText(ad.getContext(), i.close_aa_notify_tips, 0).show(); h.mEJ.a(407, 27, 1, false); if (!bi.oW(((c) aVar.dIv).qYe)) { com.tencent.mm.plugin.aa.a.h.g(this.ezA.bJa.bIZ, ((c) aVar.dIv).qYe); } } else { x.i("MicroMsg.SubCoreAA", "illegal resp"); h.mEJ.a(407, 29, 1, false); } } else { x.i("MicroMsg.SubCoreAA", "close aa urge notify failed"); Toast.makeText(ad.getContext(), i.close_aa_notify_fail_tips, 1).show(); h.mEJ.a(407, 28, 1, false); } return uQG; } }
/* * 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.agfa.dach.support.internal.atms.controller; import com.agfa.dach.support.internal.atms.data.AggregateAppointment; import com.agfa.dach.support.internal.atms.entity.Appointment; import com.agfa.dach.support.internal.atms.entity.Resource; import com.agfa.dach.support.internal.atms.security.SessionInformationController; import com.agfa.dach.support.internal.atms.service.ATMSMBean; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; import java.time.LocalDate; import java.time.Month; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.LocalBean; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import org.primefaces.component.datatable.DataTable; import org.primefaces.event.CellEditEvent; /** * * @author leandros */ @Named(value = "aTMSController") @SessionScoped public class ATMSController implements Serializable { @Inject ATMSMBean backend; private String errorMessage = ""; private String successMessage = ""; private List<AggregateAppointment> appointments; private List<Resource> resources; public String getErrorMessage() { return errorMessage; } public String getSuccessMessage() { return successMessage; } public List<AggregateAppointment> getAppointments() { return appointments; } public List<Resource> getResources() { return resources; } @PostConstruct public void init() { //testfetchAggregateAppointments(); } public void initDB() { try { backend.initDB(); putSuccess("Initialized DB"); } catch (Exception e) { putError("Init DB failed!: " + e.getMessage()); } } public void populateDB() { try { backend.populateDB(); putSuccess("Populated DB"); } catch (Exception e) { putError("Populate DB failed!: " + e.getMessage()); } } public void populateMore() { try { backend.populateMore(13); putSuccess("Populated more..."); } catch (Exception e) { putError("Populate more failed!: " + e.getMessage()); } } public void testfetchAggregateAppointments() { resources = backend.getResources(); appointments = backend.getAggregateAppointments(LocalDate.of(2016, Month.NOVEMBER, 1), LocalDate.of(2016, Month.NOVEMBER, 30), null); } private void putSuccess(String message) { successMessage = message; errorMessage = ""; } private void putError(String message) { successMessage = ""; errorMessage = message; } public void onCellEdit(CellEditEvent event) { String oldValue = (String) event.getOldValue(); String newValue = (String) event.getNewValue(); DataTable dt = (DataTable) event.getComponent(); //AggregateAppointment listEdited = (AggregateAppointment) dt.getRowData(); AggregateAppointment listEdited = appointments.get(event.getRowIndex()); String headerText = event.getColumn().getHeaderText(); if (headerText == null) { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Edit failed!", null); FacesContext.getCurrentInstance().addMessage(null, msg); System.out.println("Header text could not be read :("); return; } // find edited item in list...this is a bit fuzzy but we only know the edited column based on its header Appointment itemEdited = null; for (Appointment a : listEdited.getAppointments()) { if (a.getResource().getName().matches(headerText)) { itemEdited = a; } } if (itemEdited == null) { // TODO: throw exception? System.out.println("Item not found :("); return; } String msgSummary; String msgText; // process update itemEdited.setText(newValue); if(itemEdited.getId() == null) { // insert new itemEdited.setType(Appointment.Type.TERMIN); backend.createAppointment(itemEdited); msgSummary = "Termin erstellt"; } else if (newValue.length() > 0) { // update existing backend.updateAppointment(itemEdited); msgSummary = "Termin bearbeitet"; } else { // delete backend.deleteAppointment(itemEdited); msgSummary = "Termin gelöscht"; } msgText = itemEdited.getResource().getName(); msgText += itemEdited.getWorkday() + "\n"; if (oldValue == null || oldValue.length() > 0) { msgText += "Alt:" + "\n"; msgText += oldValue + "\n"; } if (newValue.length() > 0) { msgText += "Neu:" + "\n"; msgText += newValue; } FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, msgSummary, msgText); FacesContext.getCurrentInstance().addMessage(null, msg); } }
package com.yuta.clocktime.adapter; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.yuta.clocktime.R; import com.yuta.clocktime.model.District; public class CityAdapter extends BaseAdapter{ private List<District> data = new ArrayList<District>(); private LayoutInflater inflater; private ViewHolder viewHolder; private Context context; public CityAdapter() { super(); } public CityAdapter(List<District> data, Context context){ this.data = data; inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; viewHolder = new ViewHolder(); if(convertView==null){ view = inflater.inflate(R.layout.add_clock_item, null); viewHolder.flagImageView = (ImageView)view.findViewById(R.id.flag_id); viewHolder.cityTextView = (TextView)view.findViewById(R.id.city_name); viewHolder.zoneTextView = (TextView)view.findViewById(R.id.timezone); view.setTag(viewHolder); }else{ view = convertView; viewHolder = (ViewHolder) view.getTag(); } District city = data.get(position); viewHolder.flagImageView.setImageBitmap(getBitmap(context, city.getFlag())); viewHolder.cityTextView.setText(city.getCity()); viewHolder.zoneTextView.setText(city.getTimezone()); return view; } private Bitmap getBitmap(Context context, int resId){ BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(resId); return BitmapFactory.decodeStream(is, null, opt); } class ViewHolder{ ImageView flagImageView; TextView cityTextView; TextView zoneTextView; } @Override public int getCount() { // TODO Auto-generated method stub return data.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } }
package com.sinata.rwxchina.component_home.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.LinearLayout; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.sinata.rwxchina.basiclib.HttpPath; import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils; import com.sinata.rwxchina.component_home.R; import com.sinata.rwxchina.component_home.entity.IconMoreEntity; import java.util.ArrayList; import java.util.List; /** * @author:wj * @datetime:2017/12/29 * @describe:周边查询适配器 * @modifyRecord: */ public class PerimeterAdapter extends RecyclerView.Adapter<PerimeterAdapter.PerimeterViewHolder> { private Context mC; private List<IconMoreEntity.ListBean> list; private LayoutInflater layoutInflater; private OnItemActionListener mOnItemActionListener; public interface OnItemActionListener{ void onItemClickListener(View v, int pos,String key); } public PerimeterAdapter(Context mC) { this.mC = mC; this.list = new ArrayList<>(); this.layoutInflater = LayoutInflater.from(mC); } public List<IconMoreEntity.ListBean> getList() { return list; } public void setList(List<IconMoreEntity.ListBean> list) { this.list = list; } @Override public PerimeterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View viewOne = layoutInflater.inflate(R.layout.item_icon_more_perimeter, parent, false); PerimeterViewHolder perimeterViewHolder = new PerimeterViewHolder(viewOne); return perimeterViewHolder; } @Override public void onBindViewHolder(PerimeterViewHolder holder, final int position) { final PerimeterViewHolder perimeterViewHolder = (PerimeterViewHolder) holder; perimeterViewHolder.name.setText(list.get(position).getTitle()); ImageUtils.showImage(mC, HttpPath.IMAGEURL+list.get(position).getImg(),perimeterViewHolder.image); perimeterViewHolder.perimeter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOnItemActionListener.onItemClickListener(v,perimeterViewHolder.getPosition(),list.get(position).getTitle()); } }); } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } public OnItemActionListener getmOnItemActionListener() { return mOnItemActionListener; } public void setmOnItemActionListener(OnItemActionListener mOnItemActionListener) { this.mOnItemActionListener = mOnItemActionListener; } @Override public int getItemCount() { return list.size(); } public class PerimeterViewHolder extends RecyclerView.ViewHolder { private TextView name; private ImageView image; private LinearLayout perimeter; public PerimeterViewHolder(View itemView) { super(itemView); name = itemView.findViewById(R.id.item_icon_more_perimeter_tv); image = itemView.findViewById(R.id.item_icon_more_perimeter_img); perimeter = itemView.findViewById(R.id.item_icon_more_perimeter_linear); } } }
package com.weigs.PrototypePattern; /** * @author weigs * @date 2017/7/2 0002 */ public class Rectangle extends Shape { public Rectangle() { type = "Rectangel"; } @Override public void draw() { System.out.println("Rectangle::draw()"); } }
package com.example.week5; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import java.time.Month; import java.util.ArrayList; import java.util.Calendar; public class MonthViewActivity extends AppCompatActivity { int year; int month; int dayOfWeek; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView gridView = findViewById(R.id.gridview); GridView day_of_the_week = findViewById(R.id.day_of_the_week); Button prevBtn = findViewById(R.id.previous_button); Button nextBtn = findViewById(R.id.next_button); final String[] dayOfTheWeek = new String[]{"일", "월", "화", "수", "목", "금", "토"}; ArrayList<String> days = new ArrayList<String>(); TextView yearMonthTV = findViewById(R.id.year_month); Calendar cal = Calendar.getInstance(); Intent intent = getIntent(); year = intent.getIntExtra("year", -1); month = intent.getIntExtra("month", -1); if (year == -1 || month == -1){ year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); } cal.set(year, month, 1); dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1; // 첫날 요일구하기, 0부터 시작하기 위해 1을 빼주었다. for (int i = 0; i < dayOfWeek; i++) days.add(""); // 1일의 요일을 구해서 그 값만큼 격자 앞쪽에 빈칸 만들어줌 if (month == 1 && year % 4 != 0) for(int i = 1; i <= 28; i++) days.add("" + i); // 2월 - 28일 if (month == 1 && year % 4 == 0) for(int i = 1; i <= 29; i++) days.add("" + i); // 2월/윤달 - 29일 if (month == 3 || month == 5 || month == 8 || month == 10) for(int i = 1; i <= 30; i++) days.add("" + i); // 4,6,9,11월 - 30일 if (month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11) for(int i = 1; i <= 31; i++) days.add("" + i); // 1,3,5,7,8,10,12월 - 31일 yearMonthTV.setText(year + "년 " + (month+1) + "월"); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.day_of_the_week, dayOfTheWeek); ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, R.layout.day, days); day_of_the_week.setAdapter(adapter); gridView.setAdapter(adapter2); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { if(position>=dayOfWeek) { // 1의 요일보다 앞에 있을 때에는 클릭에 반응하지 않음 Toast.makeText(MonthViewActivity.this, year + "." + (month + 1) + "." + (position - dayOfWeek + 1), Toast.LENGTH_SHORT).show(); } } }); prevBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bt_Intent = new Intent(getApplicationContext(), MonthViewActivity.class); if(month<1) { bt_Intent.putExtra("year", year-1); bt_Intent.putExtra("month", 11); } else { bt_Intent.putExtra("year", year); bt_Intent.putExtra("month", (month-1)); } startActivity(bt_Intent); finish(); } }); nextBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bt_Intent = new Intent(getApplicationContext(), MonthViewActivity.class); if(month>10) { bt_Intent.putExtra("year", year+1); bt_Intent.putExtra("month", 0); } else { bt_Intent.putExtra("year", year); bt_Intent.putExtra("month", (month+1)); } startActivity(bt_Intent); finish(); } }); } }
package edu.kit.pse.osip.core.utils.language; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * This class is the interface to load menu texts in different languages. * * @author Maximilian Schwarzmann * @version 1.0 */ public final class Translator { /** * ResourceBundle saving the translations. */ private ResourceBundle bundle; /** * Saves the sole accessible instance. */ private static Translator singleton; /** * true when the keys shall always be returned and false otherwise. */ private boolean localizationDisabled = false; /** * Creates a new translator. Private because it is a singleton. */ private Translator() { setLocale(new Locale("en", "US")); } /** * Gets the single instance of the Translator. It is newly created at the first call of the method. * * @return The single instance of Translator. */ public static Translator getInstance() { if (singleton == null) { singleton = new Translator(); } return singleton; } /** * Gets the word that is associated with key in the current locale. * * @param key The key to use for translation lookup. * @return The translation for key or key if there is no such entry. * Also returns key if bundle is null. */ public String getString(String key) { if (key == null) { throw new NullPointerException("Key is null"); } if (localizationDisabled) { return key; } if (bundle == null) { return key; } try { return bundle.getString(key); } catch (MissingResourceException e) { return key; } } /** * Sets the locale to be used when translating. * * @param locale The locale to be set. */ public void setLocale(Locale locale) { if (locale == null) { throw new NullPointerException("Locale is null"); } try { bundle = ResourceBundle.getBundle("Bundle", locale); } catch (MissingResourceException e) { System.err.println(); bundle = null; } } /** * Disables localization: Always shows IDs. * * @param localizationDisabled true if localization should be disabled. */ public void setLocalizationDisabled(boolean localizationDisabled) { this.localizationDisabled = localizationDisabled; } }
package com.xhs.property.enumClass; public enum PropertyContentEnum { wait_review("待审核", 0), review_pass("审核通过", 1), not_pass("未审核通过", 2); private String type; private int state; PropertyContentEnum(String type, int state) { this.type = type; this.state = state; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getState() { return state; } public void setState(int state) { this.state = state; } }
package com.e6soft.activiti.controllers; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.activiti.engine.RepositoryService; import org.activiti.engine.impl.RepositoryServiceImpl; import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.repository.ProcessDefinitionQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; 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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.e6soft.activiti.ActivitiController; import com.e6soft.activiti.ActivitiFactory; import com.e6soft.activiti.model.NodeTemplate; import com.e6soft.activiti.model.ProcessForm; import com.e6soft.activiti.service.NodeTemplateService; import com.e6soft.activiti.service.ProcessFormService; import com.e6soft.activiti.vo.grid.NodeTemplateGrid; import com.e6soft.activiti.vo.grid.ProcessDefGrid; import com.e6soft.core.util.StringUtil; import com.e6soft.core.views.PageFilter; import com.e6soft.core.views.PageGrid; import com.e6soft.core.views.ViewMsg; /** * 流程部署controller * @author 陈福忠 * */ @Controller @RequestMapping(value=ActivitiFactory.module+"/processdef") public class ProcessDefController extends ActivitiController{ @Autowired private RepositoryService repositoryService; @Autowired private ProcessFormService processFormService; @Autowired private NodeTemplateService nodeTemplateService; /** * activti-modeler配置表单页面 * @param deploymentId * @param model * @return */ @RequestMapping(value="config_form/{deploymentId}") public String configForm(@PathVariable("deploymentId") String deploymentId,Model model) { model.addAttribute("deploymentId", deploymentId); model.addAttribute("defaultForm", this.processFormService.getDefaultProcessForm(deploymentId)); return viewModel("/processdef/config_form"); } /** * 流程部署grid * @param key * @param pageFilter * @return */ @RequestMapping(value="deployment_grid") @ResponseBody public String grid(String key,@ModelAttribute PageFilter pageFilter) { PageGrid<ProcessDefGrid> pageGrid = new PageGrid<ProcessDefGrid>(ProcessDefGrid.class); ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key); List<ProcessDefinition> list = query.listPage(pageFilter.getStart(),pageFilter.getStart()+ pageFilter.getLimit()); pageGrid.setTotalCount(query.count()); List<ProcessDefGrid> res = new ArrayList<ProcessDefGrid>(); for(ProcessDefinition t:list){ ProcessDefGrid p = new ProcessDefGrid(); p.setId(t.getId()); p.setDeploymentId(t.getDeploymentId()); p.setName(t.getName()); p.setVersion(t.getVersion()); p.setStatus(t.isSuspended()?0:1); res.add(p); } pageGrid.setGrid(res); return this.toJson(pageGrid); } /** * 流程-表单模板grid * @param deploymentId * @param formId * @return */ @RequestMapping(value="nodetemplate_grid") @ResponseBody public String grid(String deploymentId,String formId) { PageGrid<NodeTemplateGrid> pageGrid = new PageGrid<NodeTemplateGrid>(NodeTemplateGrid.class); List<NodeTemplateGrid> list = new ArrayList<NodeTemplateGrid>(); pageGrid.setGrid(list); pageGrid.setTotalCount(0L); ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult(); if(definition!=null){ ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService) .getDeployedProcessDefinition(definition.getId()); List<ActivityImpl> activitiList = processDefinition.getActivities(); Map<String,NodeTemplate> nodeTemplateMap = new HashMap<String,NodeTemplate>(); if(!StringUtil.isNullOrEmpty(formId)){ nodeTemplateMap = this.nodeTemplateService.mapKeyByNodeId(deploymentId, formId); } for (ActivityImpl activity : activitiList) { Map<String, Object> properties = activity.getProperties(); String type = properties.get("type").toString(); if (type.equals("userTask")||"startEvent".equals(type)) { NodeTemplateGrid node = new NodeTemplateGrid(); node.setId(activity.getId()); node.setNodeId(activity.getId()); if(StringUtil.isNullOrEmpty(properties.get("name"))){ node.setNodeName(activity.getId()); }else{ node.setNodeName(properties.get("name").toString()); } NodeTemplate t = nodeTemplateMap.get(activity.getId()); if(t!=null){ node.setTemplateId(t.getTemplateId()); } list.add(node); } } } Comparator<NodeTemplateGrid> com = new Comparator<NodeTemplateGrid>() { public int compare(NodeTemplateGrid o1, NodeTemplateGrid o2) { return o1.getNodeName().compareTo(o2.getNodeName()); } }; Collections.sort(list, com); pageGrid.setTotalCount(Long.parseLong(list.size()+"")); return this.toJson(pageGrid); } /** * 保存流程-表单配置 * @param processForm * @param br * @param nodeTemplateList * @return */ @RequestMapping(value="save_config_form",method=RequestMethod.POST) @ResponseBody public String save(@ModelAttribute ProcessForm processForm,BindingResult br,String nodeTemplateList){ if(br.hasErrors()){ return new ViewMsg(-1,br.getGlobalError().getDefaultMessage()).toString(); }else{ List<NodeTemplate> list = JSONArray.parseArray(nodeTemplateList,NodeTemplate.class); processFormService.save(processForm,list); return new ViewMsg(1).toString(); } } /** * 启用流程 * @param processDefId * @return */ @RequestMapping(value="start/{processDefId}") @ResponseBody public String start(@PathVariable("processDefId") String processDefId){ repositoryService.activateProcessDefinitionById(processDefId); return new ViewMsg(1).toString(); } /** * 停用流程 * @param processDefId * @return */ @RequestMapping(value="stop/{processDefId}") @ResponseBody public String stop(@PathVariable("processDefId") String processDefId){ repositoryService.suspendProcessDefinitionById(processDefId); return new ViewMsg(1).toString(); } /** * 删除流程 * @param deploymentId * @return */ @RequestMapping(value="delete/{deploymentId}") @ResponseBody public String delete(@PathVariable("deploymentId") String deploymentId){ repositoryService.deleteDeployment(deploymentId); return new ViewMsg(1).toString(); } /** * 查询流程默认表单 * @param deploymentId * @return */ @RequestMapping(value="query_default_form/{deploymentId}") @ResponseBody public String queryDefaultForm(@PathVariable("deploymentId") String deploymentId){ ProcessForm form = this.processFormService.getDefaultProcessForm(deploymentId); return new ViewMsg(1,JSONObject.toJSONString(form)).toString(); } /** * 显示流程图 * @param deploymentId * @param response * @throws Exception */ @RequestMapping(value = "img/{deploymentId}") public void loadByDeployment(@PathVariable("deploymentId") String deploymentId, HttpServletResponse response) throws Exception { ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult(); String resourceName = processDefinition.getDiagramResourceName(); InputStream resourceAsStream = repositoryService.getResourceAsStream(deploymentId, resourceName); byte[] b = new byte[1024]; int len = -1; while ((len = resourceAsStream.read(b, 0, 1024)) != -1) { response.getOutputStream().write(b, 0, len); } } }
package com.project.service; import java.util.HashMap; import java.util.List; import com.project.dto.DefaultData; public interface DashboardService { public List<HashMap<String, Object>> getDashboardRecords(DefaultData data); }
package org.fuserleer.crypto.bls.group; import java.util.Collection; import java.util.Objects; import org.apache.milagro.amcl.BLS381.BIG; import org.apache.milagro.amcl.BLS381.ECP; import org.fuserleer.utils.Numbers; /** * Forked from https://github.com/ConsenSys/mikuli/tree/master/src/main/java/net/consensys/mikuli/crypto * * Modified for use with Cassandra as internal code not a dependency * * Original repo source has no license headers. */ public final class G1Point implements Group<G1Point> { final ECP point; private static final int fpPointSize = BIG.MODBYTES; public G1Point(final G1Point point) { Objects.requireNonNull(point, "Point is null"); this.point = new ECP(point.ecpPoint()); } public G1Point(final ECP point) { Objects.requireNonNull(point, "ECP point is null"); this.point = new ECP(point); } public G1Point add(final G1Point other) { Objects.requireNonNull(other, "Point to add is null"); ECP sum = new ECP(this.point); sum.add(other.point); sum.affine(); return new G1Point(sum); } public G1Point add(final Collection<G1Point> others) { Objects.requireNonNull(others, "Points to add is null"); ECP sum = new ECP(this.point); for (G1Point other : others) sum.add(other.point); sum.affine(); return new G1Point(sum); } public G1Point sub(final G1Point other) { Objects.requireNonNull(other, "Point to subtract is null"); ECP sum = new ECP(this.point); sum.sub(other.point); sum.affine(); return new G1Point(sum); } public G1Point neg() { ECP newPoint = new ECP(this.point); newPoint.neg(); return new G1Point(newPoint); } public G1Point mul(final Scalar scalar) { Objects.requireNonNull(scalar, "Scalar is null"); ECP newPoint = this.point.mul(scalar.value()); return new G1Point(newPoint); } /** * @return byte[] the byte array representation of compressed point in G1 */ public byte[] toBytes() { // Size of the byte array representing compressed ECP point for BLS12-381 is // 49 bytes in milagro // size of the point = 48 bytes // meta information (parity bit, curve type etc) = 1 byte byte[] bytes = new byte[fpPointSize + 1]; this.point.toBytes(bytes, true); return bytes; } public static G1Point fromBytes(final byte[] bytes) { Objects.requireNonNull(bytes, "Point bytes is null"); Numbers.equals(bytes.length, fpPointSize +1, "Point bytes is invalid size"); return new G1Point(ECP.fromBytes(bytes)); } ECP ecpPoint() { return this.point; } @Override public int hashCode() { final int prime = 31; int result = 1; long x = this.point.getX().norm(); long y = this.point.getY().norm(); result = prime * result + (int) (x ^ (x >>> 32)); result = prime * result + (int) (y ^ (y >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; G1Point other = (G1Point) obj; if (this.point == null) { if (other.point != null) return false; } else if (this.point.equals(other.point) == false) return false; return true; } }
package ninja.littleed.swing.watermark; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.io.IOException; import java.io.InputStream; import java.net.URI; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; import org.jdesktop.swingx.JXTextField; import com.kitfox.svg.SVGCache; import com.kitfox.svg.app.beans.SVGIcon; public class WatermarkTextField extends JXTextField { private SVGIcon search; public WatermarkTextField() { loadSearchIcon(); } private void loadSearchIcon() { setPrompt("Search..."); InputStream is = null; try { is = getClass().getResourceAsStream("/search.svg"); URI searchURI = SVGCache.getSVGUniverse().loadSVG(is, "search"); // SVGElement element = // SVGCache.getSVGUniverse().getElement(searchURI); search = new SVGIcon(); search.setSvgURI(searchURI); search.setPreferredSize(new Dimension(getPreferredSize().height, getPreferredSize().height)); search.setScaleToFit(true); } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // int x = getWidth()-search.getIconWidth(); // search.paintIcon(this, g, 0, 0); } public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); panel.add(new WatermarkTextField(), BorderLayout.NORTH); panel.add(new JButton(),BorderLayout.WEST); // Set up components JFrame testFrame = new JFrame(); testFrame.setSize(800, 600); testFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); testFrame.setContentPane(panel); // Add to frame testFrame.setVisible(true); } }
package br.edu.unidavi.cities; import android.Manifest; import android.arch.lifecycle.ViewModelProviders; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.location.Location; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; public class NewCityActivity extends AppCompatActivity { private CityViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_city); viewModel = ViewModelProviders.of(this).get(CityViewModel.class); viewModel.success.observe(this, success -> { if (Boolean.TRUE.equals(success)) { finish(); } }); Button buttonSave = findViewById(R.id.button_save); buttonSave.setOnClickListener(v -> { EditText input_city_name = findViewById(R.id.input_city_name); EditText input_city_cep = findViewById(R.id.input_city_cep); EditText input_city_uf = findViewById(R.id.input_city_uf); EditText input_city_latitude = findViewById(R.id.input_city_latitude); EditText input_city_longitude = findViewById(R.id.input_city_longitude); if ( !input_city_name.getText().toString().isEmpty() && !input_city_cep.getText().toString().isEmpty() && !input_city_uf.getText().toString().isEmpty() && !input_city_latitude.getText().toString().isEmpty() && !input_city_longitude.getText().toString().isEmpty() ) { viewModel.saveCity(new City( input_city_name.getText().toString(), input_city_cep.getText().toString(), input_city_uf.getText().toString(), input_city_latitude.getText().toString(), input_city_longitude.getText().toString() )); } }); Button buttonLocation = findViewById(R.id.button_location); buttonLocation.setOnClickListener(v -> { Log.i("Permissão: ", String.valueOf(hasFineLocationPermission())); if (hasFineLocationPermission()) { setLocation(); return; } if (ActivityCompat.shouldShowRequestPermissionRationale( NewCityActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) { new AlertDialog.Builder(NewCityActivity.this) .setTitle("Por favor, não negue a permissão dessa vez!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { requestPermission(); } }) .show(); } else { requestPermission(); } }); } public void requestPermission() { ActivityCompat.requestPermissions( NewCityActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1000 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) { if (grantResults[0] == PackageManager.PERMISSION_DENIED) { Toast.makeText(this, "Localização Negada", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Localização Concedida!", Toast.LENGTH_SHORT).show(); setLocation(); } } } boolean hasFineLocationPermission() { return ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private void setLocation() { FusedLocationProviderClient local = LocationServices.getFusedLocationProviderClient(this); local.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { Log.i("Latitude: ", String.valueOf(location.getLatitude())); Log.i("Longitude: ", String.valueOf(location.getLongitude())); ((EditText) findViewById(R.id.input_city_latitude)).setText(String.valueOf(location.getLatitude())); ((EditText) findViewById(R.id.input_city_longitude)).setText(String.valueOf(location.getLongitude())); } }); } }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Maryam Athar Khan // Lab 03 // September 11, 2015 // This program will determine how much each person in a group has to spend in order to pay the check after a restaurant meal // // import Scanner Class from outside import java.util.Scanner; // define a class public class Check{ // main method required for every Java program public static void main(String[] args) { // declare an instance of the Scanner object Scanner myScanner= new Scanner( System.in ); // Prompt user for the original cost of the chek System.out.print(" Enter the original cost of the check in the form xx.xx: "); // Accept user input double checkCost= myScanner.nextDouble(); // Accept the input from the user that is the tip percentage they wish to pay System.out.print(" Enter the percentage tip that you wish to pay as a whole number (in the form xx): "); // Accept user unput double tipPercent= myScanner.nextDouble(); // We want to convert the percentage to into a decimal value tipPercent/= 100; // Prompt the user for how many people went to dinner System.out.print(" Enter the number of people who went out to dinner: "); // Accept the input int numPeople= myScanner.nextInt(); // declare variables double totalCost; double costPerPerson; int dollars, pennies, dimes ; // whole dollar amount of cost dimes, pennies; // for storing digits to the right of the decimal point for the cost$ totalCost=checkCost*(1+tipPercent); // What is the cost per person costPerPerson=totalCost/numPeople; // get the whole amount, dropping decimal fraction dollars=(int)costPerPerson; // get dimes amount e.g. // (int)(6.73*10) % 10 -> 67 % 10 -> 7 // where the % (mod) operator returns the remainder // after the division: 583%100 -> 83, 27%5 -> 2 dimes=(int)(costPerPerson*10) % 10; pennies=(int)(costPerPerson*100) % 10; System.out.println("Each person in the group owes $" + dollars + '.' + dimes + pennies); } // end of main method } // end of class
package com.alexngai.moxieappv2.tabs; import com.alexngai.moxieappv2.tabs.exercise.ActivityFragment; import com.alexngai.moxieappv2.tabs.exercise.ExerciseFragment; import android.app.Activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class TabPageAdapter_Exercise extends FragmentPagerAdapter { Activity activity; ActivityFragment activityFragment; ExerciseFragment exerciseFragment; public TabPageAdapter_Exercise(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int index) { switch (index) { case 0: activityFragment = new ActivityFragment(); return activityFragment; case 1: exerciseFragment = new ExerciseFragment(); return exerciseFragment; } return null; } public ActivityFragment getActivityFragment(){ return activityFragment; } public ExerciseFragment getExerciseFragment(){ return exerciseFragment; } @Override public int getCount() { // get item count - equal to number of tabs return 2; } }
package com.tencent.tencentmap.mapsdk.a; import com.tencent.tencentmap.mapsdk.a.ld.b; /* synthetic */ class lj$4 { static final /* synthetic */ int[] a = new int[b.values().length]; static { try { a[b.a.ordinal()] = 1; } catch (NoSuchFieldError e) { } try { a[b.b.ordinal()] = 2; } catch (NoSuchFieldError e2) { } try { a[b.c.ordinal()] = 3; } catch (NoSuchFieldError e3) { } try { a[b.d.ordinal()] = 4; } catch (NoSuchFieldError e4) { } try { a[b.e.ordinal()] = 5; } catch (NoSuchFieldError e5) { } try { a[b.f.ordinal()] = 6; } catch (NoSuchFieldError e6) { } } }
package com.poker.lobby; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.engine.event.EventManager; import com.player.Player; import com.player.TablePlayer; import com.poker.table.Blinds; import com.poker.table.Table; /** * The lobby controller, contains methods for finding a game * * * @author Zack Davidson <zackdavidson2014@outlook.com> */ public class Lobby { /** * Lobby Singleton Object */ public static Lobby get = new Lobby(); /** * Private Constructor */ private Lobby() { } /** * All the tables */ private List<Table> tables = new ArrayList<>(); /** * Initialises the tables */ public void initialise() { tables.add(new Table("Testing 1", new Blinds(15, 30), 6)); for (Table t : tables) { t.initialiseTable(); EventManager.get.submitEvent(t); } } /** * Finds a table with a specified name * * @param name * - the name of the table * @return - optional table */ public Optional<Table> find(String name) { for (Table t : tables) { if (t.getTableName().equalsIgnoreCase(name)) { return Optional.of(t); } } return null; } /** * Joins a table with a name * * @param name * - the name of the table * @param player * - the player joining the table */ public void joinTable(String name, Player player) { Optional<Table> table = find(name); table.get().addPlayer(TablePlayer.convert(player, 10000)); } }
package com.espendwise.manta.auth; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.GrantedAuthorityImpl; import java.util.Arrays; public class AuthConst { public static final String ROLE_UNDEFINED = "ROLE_UNDEFINED"; public static final String NONE_PROVIDED = "NONE_PROVIDED"; public static final String GUEST = "GUEST"; public static final String ROLE_ANONUMOUS = "ROLE_ANONUMOUS"; public static final AuthUser ANONYMOUS = new AuthUser( new AuthUserDetails(null, null, null, Arrays.asList(new GrantedAuthority[]{new GrantedAuthorityImpl(ROLE_ANONUMOUS)}), NONE_PROVIDED, GUEST, true, true, true, true ), null, null); }
package com.technology.share.mapper; import com.technology.share.domain.view.VExtCss; public interface VExtCssMapper extends MyMapper<VExtCss> { }
package com.example.Calculator.model; public class Doctorinfo { String name; int id; String section; float timmimg; //peramiterised constructor public Doctorinfo(String name, int id, String section, float timmimg) { this.name = name; this.id = id; this.section = section; this.timmimg = timmimg; } //getter and setter public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public float getTimmimg() { return timmimg; } public void setTimmimg(float timmimg) { this.timmimg = timmimg; } }
package subjects.sample.string; /** * @description: “气球” 的最大数量balloon * https://leetcode-cn.com/problems/maximum-number-of-balloons/ * @author: dsy * @date: 2020/11/27 17:26 */ public class S1189 { public static int maxNumberOfBalloons(String text) { int[] nums = new int[5]; for (char c : text.toCharArray()) { switch (c) { case 'b': nums[0]++; break; case 'a': nums[1]++; break; case 'l': nums[2]++; break; case 'o': nums[3]++; break; case 'n': nums[4]++; break; default: break; } } int result = nums[0]; for (int i = 0; i < 5; i++) { int num = nums[i]; if (i == 2 || i == 3) { num = nums[i] / 2; } if (result > num) { result = num; } } return result; } public static void main(String[] args) { System.out.println(maxNumberOfBalloons("nlaebolko")); } }
package org.sodeja.functional; public interface Function4<R, P1, P2, P3, P4> { public R execute(P1 p1, P2 p2, P3 p3, P4 p4); }
package com.ebupt.portal.canyon.common.annotation; import com.ebupt.portal.canyon.common.enums.LogEnum; import java.lang.annotation.*; /** * 日志注解 * * @author chy * @date 2019-03-08 15:23 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface EBLog { String value() default ""; // 操作描述 LogEnum type() default LogEnum.LOG; // 操作类型 }
package com.fpmislata.banco.negocio.dominio; public enum Rol { ADMINISTRADOR, USUARIO }
package org.bashemera.openfarm.repository; import org.bashemera.openfarm.model.AnimalType; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "animaltype", path = "animalTypes") public interface AnimalTypeRepository extends MongoRepository<AnimalType, String> { }
package com.company; import java.util.Random; public class basic_array_2 { public static void main(String[] args) { Random random = new Random(); int[] number= new int[10]; for(int i=0; i<number.length; i++){ number[i]=1+random.nextInt(100); System.out.println("Slot "+i+" contains a "+number[i]); } } }
package newgame; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.*; import javafx.stage.Stage; import mainmenu.ButtonOneHandlerObject; import matches.MatchOpponents; import java.io.FileInputStream; public class ButtonHandlerNewGame extends ButtonsNewGame { private Stage primaryStage; public void buttonNewGameObject(){ try{ GroupStageRand groupStageRand = new GroupStageRand(); GroupShuffle groupShuffle = new GroupShuffle(); button6(); raffleStyle(); groupStyle(); // when button is pressed button6.setOnAction(event6); groups.setOnAction(eventSimulate); raffle.setOnAction(eventRaffleGroups); Pane root = new Pane(); root.getChildren().addAll(button6, groups, raffle, groupStageRand.printGroup(),groupStageRand.printGroupSecond(),groupStageRand.printGroupThird(), groupStageRand.printGroupFourth(),groupStageRand.printGroupFivth(),groupStageRand.printGroupSixth(), groupStageRand.printGroupSeventh(),groupStageRand.printGroupEighth()); // groupShuffle.setArrayList(groupStageRand.iDS); // create a scene Scene scene = new Scene(root, 1650, 928); FileInputStream inputBackground = new FileInputStream("C:\\Users\\Asus\\WorldCupSimulator\\src\\main\\resources\\groups.jpg"); // create a image Image image = new Image(inputBackground); // create a background image BackgroundImage backgroundimage = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); // create Background Background background = new Background(backgroundimage); // set background root.setBackground(background); //set the scene primaryStage.setScene(scene); primaryStage.show(); }catch(Exception r){ r.printStackTrace(); } } public EventHandler<ActionEvent> eventGroups = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { if(TeamsList.iDS.size() == 32) { GroupShuffle groupShuffle = new GroupShuffle(); groupShuffle.setArrayList(TeamsList.iDS); ButtonHandlerNewGameShuffle bhnwgs = new ButtonHandlerNewGameShuffle(); bhnwgs.setScene(primaryStage); bhnwgs.buttonNewGameObjectShuffle(); }else if(TeamsList.iDS.size() == 0){ ButtonHandlerNewGame bhnw = new ButtonHandlerNewGame(); bhnw.setScene(primaryStage); bhnw.buttonNewGameObject(); }else{ LessThan32Teams lessThan32Teams = new LessThan32Teams(); lessThan32Teams.setArrayList(TeamsList.iDS); HandlerLessThan32Teams handlerLessThan32Teams = new HandlerLessThan32Teams(); handlerLessThan32Teams.setScene(primaryStage); handlerLessThan32Teams.buttonHandlerLesThan32Teams(); } } }; private EventHandler<ActionEvent> event6 = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ButtonOneHandlerObject boho = new ButtonOneHandlerObject(); boho.setScene(primaryStage); boho.buttonOneObject(); } }; private EventHandler<ActionEvent> eventSimulate = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { MatchOpponents matchOpponents = new MatchOpponents(); matchOpponents.setArrayList(GroupStageRand.teamsMainList); matchOpponents.chooseWinner(); GroupSimulated.teamsMainList = matchOpponents.teamsMainList; ButtonHandlerSimulateGame bhsg = new ButtonHandlerSimulateGame(); bhsg.setScene(primaryStage); bhsg.buttonSimulateObject(); } }; public EventHandler<ActionEvent> eventRaffle = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ButtonHandlerNewGame bhnw = new ButtonHandlerNewGame(); bhnw.setScene(primaryStage); bhnw.buttonNewGameObject(); } }; private EventHandler<ActionEvent> eventRaffleGroups = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { ButtonHandlerNewGameShuffle bhnwgs = new ButtonHandlerNewGameShuffle(); bhnwgs.setScene(primaryStage); bhnwgs.buttonNewGameObjectShuffle(); } }; public void setScene(Stage primaryStage){ this.primaryStage = primaryStage; } }
package woc.assignment.one; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class StringDuplicateCount { public static void main(String[] args) { String key = "Ram is a good boy Ram good"; String[] strARR = key.split(" "); System.out.println("Word coumt : "+strARR.length); HashMap<String,Integer> map = new HashMap<String, Integer>(); for (String i : strARR){ if(map.containsKey(i)) { map.put(i,map.get(i)+1); }else{ map.put(i,1); } } System.out.println(map); } }
package com.sinata.rwxchina.aichediandian.wxapi; /** * @author HRR * @datetime 2017/12/29 * @describe * @modifyRecord */ public class Constants { public static final String APP_ID = "wx62b43c4dd762da48"; }
package it.com.aop.dao; import it.com.aop.entity.User; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.UUID; @Slf4j @SpringBootTest @RunWith(SpringRunner.class) public class UserMapperTest { @Autowired UserMapper userMapper; @Test public void insert() { User user = new User(); user.setUserName(UUID.randomUUID().toString().substring(0,10)); user.setAge(20); userMapper.insert(user); log.info("{}",user); } @Test public void update() { User user = new User(); user.setId(1); user.setUserName(UUID.randomUUID().toString().substring(0,10)); user.setAge(22); userMapper.update(user); log.info("{}",user); } @Test public void delete() { userMapper.delete(11); } @Test public void countByUserName(){ User user = new User(); user.setUserName("aa"); int count = userMapper.countByUserName(user); log.info("{}",count); } }
package service; import dto.Page; import dto.StuTea; import dto.Student; import java.util.HashMap; /** * Created by Esther on 2016/8/20. */ public interface StudentService { /** * 列出学生 * @return 学生列表 */ HashMap<String, Object> list(Page page); /** * 添加学生 * @param name * @param password * @return */ Long addStudent(String name,String password); /** * 删除学生 * @param studentid * @return */ Boolean deleteStudent(Long studentid); /** * 登陆 * @param student * @return */ Student login(Student student); /** * 更改密码 * @param student * @return */ Boolean updatePassword(Student student); /** * 更新学生基本信息 * @param student */ Boolean updateInformation(Student student); /** * 通过id查找学生基本信息 * @param id * @return */ Student selectById(Long id); /** * 添加一个学生的志愿 * @param stuTea */ Boolean selectTeacher(StuTea stuTea); /** * 列出学生选择的导师列表 * @param studentid * @param page * @return */ HashMap<String, Object> teachers(Long studentid,Page page); /** * 导师上升 * @param studentid * @param listnumber */ void upTeacher(Long studentid,int listnumber,Long teacherid); /** * 删除导师 * @param studentid * @param listnumber */ void deleteTea(Long studentid,int listnumber); /** * 添加cvid * @param cvid * @param id * @return */ int updateCvid(Long cvid,Long id); HashMap<String, Object> selectTeas(Long studentid,Page page); /** * 学生选择与否 * @param id * @return */ Boolean isselect(Long id); /** * 更新isselect * @param id */ void updateIsselect(Long id); }
package com.mahirkole.walkure.model; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.util.Date; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Entity public class Season extends CoreModel { @Id @GeneratedValue private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "tv_show_id") private TVShow tvShow; private String name; private Integer seasonNo; @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY ) @JoinTable( name = "season_image", joinColumns = @JoinColumn(name = "season_id"), inverseJoinColumns = @JoinColumn(name = "image_id") ) private Set<Image> images; @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY ) @JoinTable( name = "season_video", joinColumns = @JoinColumn(name = "season_id"), inverseJoinColumns = @JoinColumn(name = "video_id") ) private Set<Video> videos; @OneToMany(mappedBy = "season") private Set<SeasonOverview> overviews; @Temporal(TemporalType.DATE) private Date airDate; @OneToMany(mappedBy = "season") private Set<SeasonCast> cast; @OneToMany(mappedBy = "season") private Set<SeasonCrew> crew; @OneToMany(mappedBy = "season") private Set<Episode> episodes; }
package com.pine.template.mvvm.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.databinding.DataBindingUtil; import com.pine.template.base.recycle_view.BaseListViewHolder; import com.pine.template.base.recycle_view.adapter.BasePaginationTreeListAdapter; import com.pine.template.base.recycle_view.bean.BaseListAdapterItemEntity; import com.pine.template.base.recycle_view.bean.BaseListAdapterItemProperty; import com.pine.template.mvvm.R; import com.pine.template.mvvm.bean.MvvmShopAndProductEntity; import com.pine.template.mvvm.databinding.MvvmShopProductItemBinding; import com.pine.template.mvvm.databinding.MvvmShopTreeItemBinding; import com.pine.template.mvvm.ui.activity.MvvmShopDetailActivity; import java.util.ArrayList; import java.util.List; /** * Created by tanghongfeng on 2018/9/28 */ public class MvvmShopListPaginationTreeAdapter extends BasePaginationTreeListAdapter<MvvmShopAndProductEntity> { public static final int SHOP_VIEW_HOLDER = 1; public static final int SHOP_PRODUCT_VIEW_HOLDER = 2; @Override public List<BaseListAdapterItemEntity<MvvmShopAndProductEntity>> parseTreeData(List<MvvmShopAndProductEntity> data, boolean reset) { List<BaseListAdapterItemEntity<MvvmShopAndProductEntity>> adapterData = new ArrayList<>(); if (data != null) { BaseListAdapterItemEntity adapterEntity; for (int i = 0; i < data.size(); i++) { MvvmShopAndProductEntity entity = data.get(i); adapterEntity = new BaseListAdapterItemEntity(); adapterEntity.setData(entity); adapterEntity.getPropertyEntity().setItemViewType(SHOP_VIEW_HOLDER); List<MvvmShopAndProductEntity.ProductsBean> productList = entity.getProducts(); adapterEntity.getPropertyEntity().setSubItemViewCount(productList == null ? 0 : productList.size()); adapterData.add(adapterEntity); if (productList != null) { for (int j = 0; j < productList.size(); j++) { adapterEntity = new BaseListAdapterItemEntity(); adapterEntity.setData(productList.get(j)); adapterEntity.getPropertyEntity().setItemViewType(SHOP_PRODUCT_VIEW_HOLDER); adapterData.add(adapterEntity); } } } } return adapterData; } @Override public BaseListViewHolder getViewHolder(ViewGroup parent, int viewType) { BaseListViewHolder viewHolder = null; switch (viewType) { case SHOP_VIEW_HOLDER: viewHolder = new ShopViewHolder(parent.getContext(), LayoutInflater.from(parent.getContext()) .inflate(R.layout.mvvm_item_shop_tree, parent, false)); break; case SHOP_PRODUCT_VIEW_HOLDER: viewHolder = new ShopProductViewHolder(parent.getContext(), LayoutInflater.from(parent.getContext()) .inflate(R.layout.mvvm_item_shop_product, parent, false)); break; } return viewHolder; } public class ShopViewHolder extends BaseListViewHolder<MvvmShopAndProductEntity> { private Context mContext; private MvvmShopTreeItemBinding mBinding; public ShopViewHolder(Context context, View itemView) { super(itemView); mContext = context; mBinding = DataBindingUtil.bind(itemView); } @Override public void updateData(final MvvmShopAndProductEntity content, final BaseListAdapterItemProperty propertyEntity, final int position) { mBinding.setShop(content); mBinding.setShopProperty(propertyEntity); mBinding.setPosition(position); mBinding.toggleBtnTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean subWillShow = !propertyEntity.isItemViewSpread(); propertyEntity.setItemViewSpread(subWillShow); for (int i = position + 1; i < propertyEntity.getSubItemViewCount() + position + 1; i++) { mData.get(i).getPropertyEntity().setItemViewNeedShow(subWillShow); } notifyItemRangeChanged(position + getHeadViewCount(), propertyEntity.getSubItemViewCount() + 1); } }); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, MvvmShopDetailActivity.class); intent.putExtra("id", content.getId()); mContext.startActivity(intent); } }); // 数据改变时立即刷新数据,解决DataBinding导致的刷新闪烁问题 mBinding.executePendingBindings(); } } public class ShopProductViewHolder extends BaseListViewHolder<MvvmShopAndProductEntity.ProductsBean> { private Context mContext; private MvvmShopProductItemBinding mBinding; public ShopProductViewHolder(Context context, View itemView) { super(itemView); mContext = context; mBinding = DataBindingUtil.bind(itemView); } @Override public void updateData(final MvvmShopAndProductEntity.ProductsBean content, BaseListAdapterItemProperty propertyEntity, int position) { if (!propertyEntity.isItemViewNeedShow()) { mBinding.container.setVisibility(View.GONE); return; } mBinding.container.setVisibility(View.VISIBLE); mBinding.setProduct(content); mBinding.setShopProperty(propertyEntity); // 数据改变时立即刷新数据,解决DataBinding导致的刷新闪烁问题 mBinding.executePendingBindings(); } } }
package igra; public enum Stanje { BELI_NA_POTEZI, CRNI_NA_POTEZI, ZMAGA_CRNI, ZMAGA_BELI, NEODLOCENO; public Stanje zamenjaj() { if ( this == BELI_NA_POTEZI) { return CRNI_NA_POTEZI; } else if ( this == CRNI_NA_POTEZI ) { return BELI_NA_POTEZI; } else { return this; } } }
package com.beiyelin.addressservice.controller; import com.beiyelin.addressservice.entity.City; import com.beiyelin.addressservice.service.CityService; import com.beiyelin.common.resbody.ResultBody; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @Description: * @Author: newmann * @Date: Created in 9:26 2018-02-25 */ @RestController @RequestMapping("/api/address/city") public class CityController { public final static String PERMISSION_ADDRESS_CITYMODULE_NAME="城市"; private CityService cityService; @Autowired public void setCityService(CityService service){ this.cityService = service; } @GetMapping("/find-all") public ResultBody<List<City>> findAll(){ return new ResultBody<>(cityService.findAll()); } @GetMapping("/find-by-provinceid/{provinceid}") public ResultBody<List<City>> findByProvinceId(@PathVariable("provinceid") String provinceId){ return new ResultBody<>(cityService.findAllByProvinceIdOrderByCode(provinceId)); } }
package cn.edu.jsu.cyz.vo; import java.io.Serializable; public class staff implements Serializable { private String JobNumber; private String Name; private int Age; private String DepartmentNumber; private String DepartmentName; private int WageId; public staff(String jobNumber, String name, int age, String departmentNumber, String departmentName, int wageId) { super(); JobNumber = jobNumber; Name = name; Age = age; DepartmentNumber = departmentNumber; DepartmentName = departmentName; WageId = wageId; } public staff() { super(); } public String getJobNumber() { return JobNumber; } public void setJobNumber(String jobNumber) { JobNumber = jobNumber; } public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return Age; } public void setAge(int age) { Age = age; } public String getDepartmentNumber() { return DepartmentNumber; } public void setDepartmentNumber(String departmentNumber) { DepartmentNumber = departmentNumber; } public String getDepartmentName() { return DepartmentName; } public void setDepartmentName(String departmentName) { DepartmentName = departmentName; } public int getWageId() { return WageId; } public void setWageId(int wageId) { WageId = wageId; } @Override public String toString() { return "staff [JobNumber=" + JobNumber + ", Name=" + Name + ", Age=" + Age + ", DepartmentNumber=" + DepartmentNumber + ", DepartmentName=" + DepartmentName + ", WageId=" + WageId + "]"; } }
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 3.2.1.6 by WSRD Tencent. // Generated from `/data/jcetool/taf//upload/opalli/pitu_meta_protocol.jce' // ********************************************************************** package NS_PITU_META_PROTOCOL; public final class stUserWealthInfo extends com.qq.taf.jce.JceStruct { public int pitub = 0; public stUserWealthInfo() { } public stUserWealthInfo(int pitub) { this.pitub = pitub; } public void writeTo(com.qq.taf.jce.JceOutputStream _os) { _os.write(pitub, 0); } public void readFrom(com.qq.taf.jce.JceInputStream _is) { this.pitub = (int) _is.read(pitub, 0, false); } }
package com.city.beijing.service.impl; import com.city.beijing.dao.CheckExceptionDao; import com.city.beijing.model.LogLoanMatchedCheckException; import com.city.beijing.model.LogLoanMatchedCheckExceptionExample; import com.city.beijing.service.CheckExceptionService; import com.city.beijing.utils.Utility; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.List; /** * Created by liuyang on 16-11-8. */ @Service public class CheckExceptionServiceImpl implements CheckExceptionService { @Autowired private CheckExceptionDao checkExceptionDao; public void insertData(LogLoanMatchedCheckException checkException){ checkExceptionDao.insertData(checkException); } public void updateDataByExample(){ LogLoanMatchedCheckException checkException = new LogLoanMatchedCheckException(); LogLoanMatchedCheckExceptionExample exceptionExample = new LogLoanMatchedCheckExceptionExample(); checkExceptionDao.updateDataByExample(checkException, exceptionExample); } public void updateDataByDynamicExample(LogLoanMatchedCheckException checkException, Integer methodType, String recordGid){ checkExceptionDao.updateDataByDynamicExample(checkException, methodType, recordGid); } public void updateById(LogLoanMatchedCheckException checkException){ checkExceptionDao.updateById(checkException); } public void deleteById(int dataid){ checkExceptionDao.deleteById(dataid); } public LogLoanMatchedCheckException getDataById(int id){ return checkExceptionDao.getDataById(id); } public LogLoanMatchedCheckException getFirstDataByCondition(){ LogLoanMatchedCheckExceptionExample exceptionExample = new LogLoanMatchedCheckExceptionExample(); return checkExceptionDao.getFirstDataByCondition(exceptionExample); } public List<LogLoanMatchedCheckException> getAllDataByCondition(){ LogLoanMatchedCheckExceptionExample exceptionExample = new LogLoanMatchedCheckExceptionExample(); return checkExceptionDao.getAllDataByCondition(exceptionExample); } }
package org.jboss.perf.test.server.dao; import java.util.List; import org.jboss.perf.test.server.model.Local; public interface LocalDao { List<Local> getLocalsByProjectId(long projectId); }
import java.util.Arrays; public class ArraysExercises { public static void main(String[] args) { // int[] numbers = {1, 2, 3, 4, 5}; Person[] newPerson = new Person[3]; newPerson[0] = new Person("Correy"); newPerson[1] = new Person("Jon"); newPerson[2] = new Person("Doe"); for (Person individual : newPerson) { System.out.println(individual.getName()); } // public static Person[] addPerson(Person[] newPerson, Person person) { // // return; // } } }
package com.awrzosek.ski_station.cong_prize_management; import com.awrzosek.ski_station.basic.BasicConsts; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class SkipassPriceManager {//TODO zawrzeć to jakoś fajnie w ui - może być póki co brzydko private static final BigDecimal NOK_TO_ZL_IN_DECEMBER_2016 = BigDecimal.valueOf(0.49); public BigDecimal calculateSkipassPrice(BigDecimal c, BigDecimal a, BigDecimal b, BigDecimal minimalPrice, BigDecimal maximumPrice) { List<BigDecimal> priceRange = new ArrayList<>(); for (BigDecimal i = minimalPrice; i.compareTo(maximumPrice) < 0; i = i.add(BigDecimal.ONE)) priceRange.add(i); HashMap<BigDecimal, BigDecimal> priceToRevenue = new HashMap<>(); BigDecimal power, eToPower, dividend, divisor, demand, revenue; for (BigDecimal p : priceRange) { power = (b.multiply(p)).add(a); eToPower = BigDecimal.valueOf(Math.pow(Math.E, power.doubleValue())); dividend = (eToPower).multiply(c); divisor = eToPower.add(BigDecimal.ONE); demand = dividend.divide(divisor, RoundingMode.HALF_UP); if (demand.intValue() > BasicConsts.MAX_NO_OF_CLIENTS) demand = BigDecimal.valueOf(BasicConsts.MAX_NO_OF_CLIENTS); revenue = demand.multiply(p); priceToRevenue.put(p, revenue); } BigDecimal finalPrice = Collections.max(priceToRevenue.entrySet(), Map.Entry.comparingByValue()).getKey(); BigDecimal finalPriceInZl = finalPrice.multiply(NOK_TO_ZL_IN_DECEMBER_2016); return finalPriceInZl.setScale(2, RoundingMode.HALF_UP); } public BigDecimal calculateThreeDaysPrice(BigDecimal oneDayPrice) { BigDecimal threeDaysPrice = oneDayPrice.multiply(BigDecimal.valueOf(3)).multiply(BigDecimal.valueOf(0.8)); return threeDaysPrice.setScale(2, RoundingMode.HALF_UP); } public BigDecimal calculateOneWeekDaysPrice(BigDecimal oneDayPrice) { BigDecimal oneWeekPrice = oneDayPrice.multiply(BigDecimal.valueOf(7)).multiply(BigDecimal.valueOf(0.7)); return oneWeekPrice.setScale(2, RoundingMode.HALF_UP); } public BigDecimal calculateTwoWeeksDaysPrice(BigDecimal oneDayPrice) { BigDecimal twoWeeksPrice = oneDayPrice.multiply(BigDecimal.valueOf(14)).multiply(BigDecimal.valueOf(0.6)); return twoWeeksPrice.setScale(2, RoundingMode.HALF_UP); } }
package Objects.TrafficLight.TrafficLightState; import Objects.DrawObject; public abstract class State implements DrawObject { public abstract String getName(); }
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int q[] = new int[in.nextInt()]; for(int z=0;z<q.length;z++){ q[z] = in.nextInt(); } System.out.println(java.util.Arrays.stream(q).sum()); } }
package com.kangYh.fangdou2.app.mine; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.bumptech.glide.request.RequestOptions; import com.kangYh.fangdou2.R; import com.kangYh.fangdou2.app.home.BlurTransformation; import com.kangYh.fangdou2.base.BaseFragment; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; public class MineFragment extends BaseFragment { @BindView(R.id.h_back) ImageView hBack; @BindView(R.id.h_head) ImageView hHead; private Unbinder unbinder; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mine, container, false); unbinder = ButterKnife.bind(this, view); init(); return view; } public void init() { Glide.with(getContext()).load(R.drawable.head) .apply(RequestOptions.bitmapTransform(new BlurTransformation(getContext(), 25))) .into(hBack); Glide.with(getContext()).load(R.drawable.head) .apply(RequestOptions.bitmapTransform(new CircleCrop())) .into(hHead); } }
package video; import java.io.File; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.sql.SQLException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class VideoServer extends Thread { private ServerSocket serverSocket; private JFrame frame; public VideoServer(int port) throws IOException, SQLException, ClassNotFoundException, Exception { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(180000); frame = new JFrame(); } public void serve() throws IOException { while (true) { // block until a client connects Socket socket = serverSocket.accept(); try { handle(socket); } catch (IOException ioe) { ioe.printStackTrace(); // but don't terminate serve() } finally { socket.close(); } } } public void handle(Socket server) throws IOException { System.out.println("client connected"); System.out.println("trying to get the photo"); BufferedImage img = ImageIO.read(ImageIO.createImageInputStream(server.getInputStream())); System.out.println("received new imagess"); //server.getInputStream().close(); frame.getContentPane().removeAll(); frame.getContentPane().add(new JLabel(new ImageIcon(img))); frame.pack(); frame.setVisible(true); // ImageIO.write(img, "jpg" , new File("C:\\Users\\Sina // Saleh\\eclipse-workspace\\VideoServer\\photo.jpg")); // JFrame frame = new JFrame(); // frame.getContentPane().add(new JLabel(new ImageIcon(img))); // frame.pack(); // frame.setVisible(true); } public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception { System.out.println("server started bros"); VideoServer server = new VideoServer(6066); server.serve(); } }
package com.javed.jkclasses; import java.util.ArrayList; import java.util.HashMap; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBController extends SQLiteOpenHelper { private static final String LOGCAT = null; public DBController(Context applicationcontext) { super(applicationcontext, "sqlitejaved.db", null, 1); Log.d(LOGCAT,"Created"); } @Override public void onCreate(SQLiteDatabase database) { String query; query = "CREATE TABLE Studtable ( StudId INTEGER PRIMARY KEY,Name TEXT,Phone TEXT)"; database.execSQL(query); Log.d(LOGCAT,"Studtable Created"); } @Override public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) { String query; query = "DROP TABLE IF EXISTS Studtable"; database.execSQL(query); onCreate(database); } public void insertStudent(HashMap<String, String> queryValues) { SQLiteDatabase database = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("Name", queryValues.get("Name")); values.put("Phone", queryValues.get("Phone")); //values.put("QTY", queryValues.get("QTY")); database.insert("Studtable", null, values); database.close(); } public int updateStudent(HashMap<String, String> queryValues) { SQLiteDatabase database = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("Name", queryValues.get("Name")); values.put("Phone", queryValues.get("Phone")); return database.update("Studtable", values, "StudId" + " = ?", new String[] { queryValues.get("StudId") }); //String updateQuery = "Update words set txtWord='"+word+"' where txtWord='"+ oldWord +"'"; //Log.d(LOGCAT,updateQuery); //database.rawQuery(updateQuery, null); //return database.update("words", values, "txtWord = ?", new String[] { word }); } public void deleteStudent(String id) { Log.d(LOGCAT,"delete"); SQLiteDatabase database = this.getWritableDatabase(); String deleteQuery = "DELETE FROM Studtable where StudId='"+ id +"'"; Log.d("query",deleteQuery); database.execSQL(deleteQuery); } public ArrayList<HashMap<String, String>> getAllStudents() { ArrayList<HashMap<String, String>> wordList; wordList = new ArrayList<HashMap<String, String>>(); String selectQuery = "SELECT * FROM Studtable"; SQLiteDatabase database = this.getWritableDatabase(); Cursor cursor = database.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { HashMap<String, String> map = new HashMap<String, String>(); map.put("StudId", cursor.getString(0)); map.put("Name", cursor.getString(1)); map.put("Phone", cursor.getString(2)); //map.put("QTY", cursor.getString(3)); wordList.add(map); } while (cursor.moveToNext()); } // return contact list return wordList; } public HashMap<String, String> getStudentInfo(String id) { HashMap<String, String> wordList = new HashMap<String, String>(); SQLiteDatabase database = this.getReadableDatabase(); String selectQuery = "SELECT * FROM Studtable where StudId='"+id+"'"; Cursor cursor = database.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { //HashMap<String, String> map = new HashMap<String, String>(); wordList.put("Name", cursor.getString(1)); wordList.put("Phone", cursor.getString(2)); //wordList.add(map); } while (cursor.moveToNext()); } return wordList; } }
package com.plter.translate3d; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; /** * Created by plter on 7/30/15. */ public class AppMainFragment extends Fragment implements Animation.AnimationListener, View.OnClickListener, FragmentManager.OnBackStackChangedListener { private View root; private Translation3D animToHide = new Translation3D(0,90,300,true); private Translation3D animToShow = new Translation3D(90,0,300,false); public AppMainFragment(){ animToHide.setAnimationListener(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_app_main, container, false); root.findViewById(R.id.btnOpenConfigPanel).setOnClickListener(this); getFragmentManager().addOnBackStackChangedListener(this); return root; } private void startHide(){ root.startAnimation(animToHide); } private void startShow(){ root.setVisibility(View.VISIBLE); root.startAnimation(animToShow); } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { root.setVisibility(View.INVISIBLE); getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.fragment, new ConfigPanelFragment()).commit(); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnOpenConfigPanel: startHide(); break; } } @Override public void onBackStackChanged() { if (getFragmentManager().findFragmentById(R.id.fragment)==this){ startShow(); } } @Override public void onDestroy() { super.onDestroy(); getFragmentManager().removeOnBackStackChangedListener(this); } }
package la.opi.verificacionciudadana.exceptions; /** * Created by Jhordan on 11/02/15. */ public class StorageException extends Exception { public StorageException() { super(); } public StorageException(String msg) { super(msg); } }
package com.urhive.panicbutton.activities; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import com.urhive.panicbutton.R; import com.urhive.panicbutton.fragments.CarouselFragment; import com.urhive.panicbutton.helpers.UIHelper; import com.urhive.panicbutton.services.EmergencyActivityService; public class LockScreenActivity extends AppCompatBase { private static final String TAG = "LockScreenActivity"; @SuppressLint("StaticFieldLeak") public static TabLayout tabLayout; private CoordinatorLayout mainCL; private CarouselFragment carouselFragment; private Bundle bundle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bundle = getIntent().getExtras(); if (bundle == null) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); } setContentView(R.layout.activity_lockscreen); setToolbar(getString(R.string.app_name)); mainCL = (CoordinatorLayout) findViewById(R.id.mainCL); tabLayout = (TabLayout) findViewById(R.id.tablayout); // tabLayout.setupWithViewPager(); if (savedInstanceState == null) { // withholding the previously created fragment from being created again // On orientation change, it will prevent fragment recreation // its necessary to reserve the fragment stack inside each tab initScreen(); } else { // restoring the previously created fragment // and getting the reference carouselFragment = (CarouselFragment) getSupportFragmentManager().getFragments().get(0); } } private void initScreen() { // Creating the ViewPager container fragment once carouselFragment = new CarouselFragment(); final FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container, carouselFragment).commit(); } @Override protected void onPause() { super.onPause(); if (bundle == null) { EmergencyActivityService.checkLockScreenStateAndSetViews(getApplicationContext(), 1); } } @Override protected void onResume() { super.onResume(); if (bundle == null) { EmergencyActivityService.checkLockScreenStateAndSetViews(getApplicationContext(), 2); } } public void callEmergency(View view) { // Snackbar.make(mainCL, R.string.lorem_ipsum, Snackbar.LENGTH_SHORT).show(); UIHelper.makeCall(LockScreenActivity.this, "112"); } /** * Only Activity has this special callback method * Fragment doesn't have any onBackPressed callback * <p> * Logic: * Each time when the back button is pressed, this Activity will propagate the call to the * container Fragment and that Fragment will propagate the call to its each tab Fragment * those Fragments will propagate this method call to their child Fragments and * eventually all the propagated calls will get back to this initial method * <p> * If the container Fragment or any of its Tab Fragments and/or Tab child Fragments couldn't * handle the onBackPressed propagated call then this Activity will handle the callback itself */ @Override public void onBackPressed() { if (!carouselFragment.onBackPressed()) { // container Fragment or its associates couldn't handle the back pressed task // delegating the task to super class super.onBackPressed(); } /*else { // carousel handled the back pressed task // do not call super }*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: UIHelper.startActivity(LockScreenActivity.this, SettingsActivity.class); return true; default: break; } return super.onOptionsItemSelected(item); } }
package com.shop.dao; import java.util.List; import com.shop.model.User; public interface UserDao extends BaseDao<User> { // 根据用户名查询用户 public User findByUsername(String userName); // 根据用户名和密码查询用户 public User findByUsernameAndPassword(String username, String password); // 根据激活码查询用户 public User findByCode(String code); // 查询有多少个用户 public Integer countUser(); // 分页查找所有用户 public List<User> findAll(Integer page); // 查找单个用户 public User findOne(Integer uid); }
package engine.events; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import engine.events.Event.EventType; /** * * @author Anselme FRANÇOIS * */ public class EventManager { private static Queue<Event> events = new PriorityQueue<Event>(); private static List<Map<Emitter, Handler>> handler_list; public static void init(){ handler_list = new ArrayList<Map<Emitter, Handler>>(EventType.values().length); for(EventType et : EventType.values()) handler_list.add(et.ordinal(), new HashMap<Emitter, Handler>()); } public static void addHandler(Handler handler, Emitter emitter, EventType type){ handler_list.get(type.ordinal()).put(emitter, handler); } public static void removeHandler(Emitter emitter, EventType type){ handler_list.get(type.ordinal()).remove(emitter); } public static void addEvent(Event event){ events.add(event); } public static void clearEvents(){ events.clear(); } public static void handleEvents(){ Handler handler; Queue<Event> currentEvents = events; events = new PriorityQueue<Event>(); for(Event e : currentEvents){ handler = handler_list.get(e.getType().ordinal()).get(e.getEmitter()); if(handler != null) handler.handle(e); } } }