blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
cde6c7803d2426d2fb3e197003d17b40fe6fa71a
46e5405dec9e8afbf9e1ce4c9cd1f966b6932382
/app/src/test/java/com/example/nan/kontaktliste/ExampleUnitTest.java
7bfbe070dc11b8e6c830ed40e5bc8bd8bf433dcc
[]
no_license
AmuBog/Kontaktliste
022e35ff145ad57dac0e9fe45a757b4d11de64e7
a094e986726e1b91bb3fd614c28f63b55b645a45
refs/heads/master
2021-04-30T14:25:21.575498
2018-02-12T19:27:44
2018-02-12T19:27:44
121,217,504
0
0
null
null
null
null
UTF-8
Java
false
false
406
java
package com.example.nan.kontaktliste; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
bb1b2114b3a329c393313cb54307351396b5d2fc
e0d66e37f3889410e7e6854d1fd16f023a58096d
/W410.java
35f47d3b9eb598affd1ce3a239836ea61b312d4f
[]
no_license
MarcoValeri/java_sp1
78f69fce6b98c899a68ab9a3969a90ae19fe22f5
f61ede03ace073c82e6c6be575136302ea4141dc
refs/heads/master
2023-04-25T16:37:57.111556
2021-05-28T14:01:03
2021-05-28T14:01:03
362,054,049
0
0
null
null
null
null
UTF-8
Java
false
false
1,281
java
import java.util.Scanner; import java.util.Arrays; public class W410 { /* * Create a method that gets 1 parameter * @parameter int[] array * @return the sum of an array of values, except for the * smallest elements */ public static int sumWithoutSmallest(int[] array) { int smallest = array[0]; int sum = 0; for (int i = 0; i < array.length; i++) { if (smallest > array[i]) { smallest = array[i]; } sum+= array[i]; } return sum - smallest; } public static void main(String[] args) { int[] array = new int[10]; // Prompt integers to the user System.out.println("Please, insert 10 integers"); Scanner input_number = new Scanner(System.in); for (int i = 0; i < array.length; i++) { System.out.print("Enter integer number " + (i + 1) + ": "); int number = input_number.nextInt(); array[i] = number; } input_number.close(); System.out.print("Your array is: "); System.out.println(Arrays.toString(array)); System.out.print("Sum withput the smallest one: "); System.out.println(sumWithoutSmallest(array)); } }
29739e510877995920ba50f96b07799b964fd77d
afbe0cd9fa7ac9212a63b1387185e6ee65fe8c23
/test/oracle/src/test/java/org/hibernate/tool/test/db/oracle/TestSuite.java
f7b6677a17e7f408491e22f59be1ad1427ba8b7b
[]
no_license
stadler/hibernate-tools
b86b403aa2bc8d473aaae0c1ce8eb2f2ee12a44b
99854394611aa20317097d2504d400bab8b08def
refs/heads/master
2021-09-20T19:48:25.893096
2018-07-13T13:28:24
2018-07-13T13:28:24
110,125,782
1
0
null
2017-11-09T14:31:00
2017-11-09T14:30:59
null
UTF-8
Java
false
false
451
java
package org.hibernate.tool.test.db.oracle; import org.hibernate.tools.test.util.DbSuite; import org.junit.runner.RunWith; import org.junit.runners.Suite.SuiteClasses; @RunWith(DbSuite.class) @SuiteClasses({ org.hibernate.cfg.reveng.dialect.TestCase.class, org.hibernate.tool.jdbc2cfg.CompositeIdOrder.TestCase.class, org.hibernate.tool.jdbc2cfg.Views.TestCase.class, org.hibernate.tool.test.db.CommonTestSuite.class }) public class TestSuite {}
ffd1a2eeb28086195a26817ac557466c23112188
df14fefc84c6a319541cb302855021c4e57bd415
/Restaurant/SoftDrinks.java
e47af998ae0bd20322994902bf27be771c9bd8ec
[]
no_license
srivathsa-002/OOPS
531d5044227f3922f171e07e1aae883d8f3a4e82
60738eebb25baa62490dfa8e3d62eb3024a7a69c
refs/heads/master
2020-12-30T06:30:20.235683
2020-02-17T17:46:01
2020-02-17T17:46:01
238,893,275
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
class SoftDrinks implements IBottle{ private String type; private int quantity; public void setBottleType(String type) { this.type=type; } public String getBottleType() { return type; } public void setBottleQuantityInMl(int quantity) { this.quantity=quantity; } public int getBottleQuantityInMl() { return quantity; } }
9f73a5f714924a4fb678f26d92393102e16976ad
cc6b5940d80553bf8a178e8f3108167945fcfb12
/drools-metric/src/test/java/org/drools/metric/ConstraintsTest.java
f04821f1d11d9c152a6261b12c2911b0d501f860
[ "Apache-2.0" ]
permissive
yesamer/drools
f0f9889f212a1becb1144ed704e58649f2555bcd
92b5f4e57755bfd1f4e52af34dfcbf0d608f33c9
refs/heads/master
2023-07-06T14:50:31.161516
2023-06-27T01:00:28
2023-06-27T01:00:28
185,600,193
0
0
Apache-2.0
2022-02-15T11:22:48
2019-05-08T12:19:09
Java
UTF-8
Java
false
false
5,627
java
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.metric; import java.util.ArrayList; import java.util.List; import org.drools.mvel.compiler.Person; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class ConstraintsTest extends AbstractMetricTest { @Test public void testDoubleBetaConstraints() { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + "rule R when\n" + " Person( $age : age, $name : name )\n" + " Person( name == $name, age == $age + 1 )\n" + "then\n" + " list.add($age);\n" + "end\n"; KieBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = kbase.newKieSession(); List<Integer> list = new ArrayList<>(); ksession.setGlobal("list", list); Person p1 = new Person("AAA", 31); Person p2 = new Person("AAA", 34); Person p3 = new Person("AAA", 33); ksession.insert(p1); ksession.insert(p2); ksession.insert(p3); ksession.fireAllRules(); assertThat(list.size()).isEqualTo(1); assertThat((int) list.get(0)).isEqualTo(33); } @Test public void testTripleBetaConstraints() { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + "rule R when\n" + " Person( $age : age, $name : name, $happy : happy )\n" + " Person( name == $name, age == $age + 1, happy == $happy )\n" + "then\n" + " list.add($age);\n" + "end\n"; KieBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = kbase.newKieSession(); List<Integer> list = new ArrayList<>(); ksession.setGlobal("list", list); Person p1 = new Person("AAA", 31, true); Person p2 = new Person("AAA", 34, true); Person p3 = new Person("AAA", 33, true); ksession.insert(p1); ksession.insert(p2); ksession.insert(p3); ksession.fireAllRules(); assertThat(list.size()).isEqualTo(1); assertThat((int) list.get(0)).isEqualTo(33); } @Test public void testQuadroupleBetaConstraints() { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + "rule R when\n" + " Person( $age : age, $name : name, $happy : happy, $alive : alive )\n" + " Person( name == $name, age == $age + 1, happy == $happy, alive == $alive )\n" + "then\n" + " list.add($age);\n" + "end\n"; KieBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = kbase.newKieSession(); List<Integer> list = new ArrayList<>(); ksession.setGlobal("list", list); Person p1 = new Person("AAA", 31, true); p1.setAlive(true); Person p2 = new Person("AAA", 34, true); p2.setAlive(true); Person p3 = new Person("AAA", 33, true); p3.setAlive(true); ksession.insert(p1); ksession.insert(p2); ksession.insert(p3); ksession.fireAllRules(); assertThat(list.size()).isEqualTo(1); assertThat((int) list.get(0)).isEqualTo(33); } @Test public void testDefaultBetaConstraints() { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + "rule R when\n" + " Person( $age : age, $name : name, $happy : happy, $alive : alive, $status : status )\n" + " Person( name == $name, age == $age + 1, happy == $happy, alive == $alive, status == $status )\n" + "then\n" + " list.add($age);\n" + "end\n"; KieBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = kbase.newKieSession(); List<Integer> list = new ArrayList<>(); ksession.setGlobal("list", list); Person p1 = new Person("AAA", 31, true); p1.setAlive(true); p1.setStatus("OK"); Person p2 = new Person("AAA", 34, true); p2.setAlive(true); p2.setStatus("OK"); Person p3 = new Person("AAA", 33, true); p3.setAlive(true); p3.setStatus("OK"); ksession.insert(p1); ksession.insert(p2); ksession.insert(p3); ksession.fireAllRules(); assertThat(list.size()).isEqualTo(1); assertThat((int) list.get(0)).isEqualTo(33); } }
3a0bf174619e435afa52c90c4d16c1a6524a73a2
72a81e442af489d86398ac26920063b2ecd71cdd
/PracticeDraw2/app/src/main/java/com/hencoder/hencoderpracticedraw2/practice/Practice03SweepGradientView.java
9ec7926a870593d767211775425b5351a8e74974
[]
no_license
YasinHe/LearnHenCoker
f6c4d436796fad8eda9ca30ff100b19523ad81cc
1ed25d379862bf9982739b41aed6f40ea3ab9209
refs/heads/master
2020-03-11T07:57:48.775373
2018-07-18T09:47:04
2018-07-18T09:47:04
129,871,080
0
0
null
null
null
null
UTF-8
Java
false
false
1,365
java
package com.hencoder.hencoderpracticedraw2.practice; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.graphics.SweepGradient; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class Practice03SweepGradientView extends View { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); public Practice03SweepGradientView(Context context) { super(context); } public Practice03SweepGradientView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public Practice03SweepGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { // 用 Paint.setShader(shader) 设置一个 SweepGradient // SweepGradient 的参数:圆心坐标:(300, 300);颜色:#E91E63 到 #2196F3 paint.setShader(new SweepGradient(300,300,Color.parseColor("#E91E63") , Color.parseColor("#2196F3"))); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(300, 300, 200, paint); } }
0c18e257c27967ef70066ec9baf5d7b8979e8993
548a1b731709a376e079e1f0417cc401cce70aaf
/src/main/java/week10d05/Calculator.java
0cb99dd2ec2f07e3a0b246ecf52d407e5646c725
[]
no_license
egydGIT/javaBackend
0e96c6b2bab639ccdb4631b481b69a2205d3963c
be22a7148e10fb6da019a74e916dcd353fb53e70
refs/heads/master
2023-06-25T00:41:32.443210
2021-07-11T12:33:10
2021-07-11T12:33:10
309,369,092
0
0
null
null
null
null
UTF-8
Java
false
false
799
java
/* Junior Készítsünk egy Calculator nevű osztályt, melynek van egy findMinSum(int[] arr) metódusa. A metódus feladata, hogy kiírja a legkisebb összegeket 4 számból, amiket lehetséges összerakni az arr tömb elemeiből. Példa: ha az arr tartalma [1, 3, 5, 7, 9], akkor a minimum összeg 1+3+5+7=16. */ package week10d05; import java.util.Arrays; import java.util.List; public class Calculator { public int findMinSum(int[] arr) { Arrays.sort(arr); int sum = 0; for (int i = 0; i < 4; i++) { sum += arr[i]; } return sum; } public static void main(String[] args) { Calculator calculator = new Calculator(); System.out.println(calculator.findMinSum(new int[]{5, 10, 7, 2, 3, 8})); // 17 } }
cb5f4bcb004523416e0fd3db5b472bcdd472fe24
95603257557b22f5201da59589cffd14a17a2142
/src/JavaCode/Java206.java
e7d7463e2b8e03a7f49b15bf9329e5b01bc116e7
[]
no_license
ArtistSu/LeetCode
d98c3ad1a90076902d831beb7ac3d4b6daf74ee4
9852bb09ef7d4393b9564fabf0f91f5e88def076
refs/heads/master
2023-02-13T02:28:42.677558
2023-01-31T11:18:08
2023-01-31T11:18:08
185,704,856
1
0
null
null
null
null
UTF-8
Java
false
false
1,140
java
package JavaCode; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; public class Java206 { /** * Time Complexity: O(n) * Space Complexity: O(1) * @method iteration * @topic Reverse Linked List * @author ArtistS * @param head * @return */ public ListNode reverseList2(ListNode head) { ListNode preNode = null; ListNode currNode = head; while(currNode != null){ ListNode next = currNode.next; currNode.next = preNode; preNode = currNode; currNode = next; } return preNode; } /** * Time Complexity: O(n) * Space Complexity: O(1) * @method recursion * @topic Reverse Linked List * @author ArtistS * @param head * @return */ public ListNode reverseList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } }
5d8398ab02a830556f55bdb2a1c0d2d216270810
761c519ceb7e864ba1612e9b9926624c03e31178
/src/test/java/com/retailstore/BillServiceTesting.java
9f5d1efe85561fd94fca240c02929bf0437be95d
[]
no_license
naushad3210/RetailStore
acd60cc5eba0ed41cfe6cec75de51d8c809eb91c
fe4ecb3b3c0f9809ddd8ed49085844c7c0284023
refs/heads/master
2020-03-21T19:10:03.119469
2018-07-25T11:06:32
2018-07-25T11:06:32
138,930,609
0
0
null
null
null
null
UTF-8
Java
false
false
2,382
java
package com.retailstore; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.retailstore.dao.BillDAO; import com.retailstore.datastub.BillDataStub; import com.retailstore.domain.BillDetails; import com.retailstore.enums.ItemType; import com.retailstore.factory.DiscountStrategyFactory; import com.retailstore.service.impl.BillServiceImpl; /** * @author mohammadnaushad * */ @RunWith(SpringRunner.class) @SpringBootTest public class BillServiceTesting { private static final Logger LOGGER = LoggerFactory.getLogger(BillServiceTesting.class); @Mock BillDAO billDaoMock; @Mock DiscountStrategyFactory discountStrategyFactoryMock; @InjectMocks BillServiceImpl billServiceMock; @Test public void generateBillNonGroceryTest() { LOGGER.info("-- Testing [BillServiceTesting] [Method: generateBillNonGroceryTest()]"); when(discountStrategyFactoryMock.getStrategy(Mockito.any(ItemType.class))).thenReturn(BillDataStub.billingMockObj(ItemType.OTHER)); when(billDaoMock.persistBill(Mockito.any(BillDetails.class))).thenReturn(BillDataStub.billDetails()); assertEquals(BillDataStub.billDetails(),billServiceMock.generateBill(BillDataStub.billRequestDto(ItemType.OTHER))); } @Test public void generateBillGroceryTest() { LOGGER.info("-- Testing [BillServiceTesting] [Method: generateBillGroceryTest()]"); when(discountStrategyFactoryMock.getStrategy(Mockito.any(ItemType.class))).thenReturn(BillDataStub.billingMockObj(ItemType.GROCERY)); when(billDaoMock.persistBill(Mockito.any(BillDetails.class))).thenReturn(BillDataStub.billDetails()); assertEquals(BillDataStub.billDetails(),billServiceMock.generateBill(BillDataStub.billRequestDto(ItemType.GROCERY))); } @Test(expected = NullPointerException.class) public void generateBillGroceryNullTest() { LOGGER.info("-- Testing [BillServiceTesting] [Method: generateBillGroceryNullTest()]"); assertEquals(BillDataStub.billDetails(),billServiceMock.generateBill(BillDataStub.billRequestDto(null))); } }
58f2ade7c0affa2e6222445cd6fbb18c92fe8b5f
c65d255f32cb72be5691573e103ad541efc004ff
/src/org/deegree/ogcwebservices/wpvs/capabilities/Style.java
5ef861b3c0a3d82fa875e3a8bebaef5ec3b1cbbe
[]
no_license
lat-lon/deegree2-base-2.3.1
6bc250cd44ac1cc99e09eba9c92385b70a0ace94
0358aa6292c76065826e07b65e8b15338e1843f8
refs/heads/master
2021-01-10T21:13:29.975388
2013-03-05T15:14:27
2013-03-05T15:14:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,582
java
//$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/src/org/deegree/ogcwebservices/wpvs/capabilities/Style.java $ /*---------------- FILE HEADER ------------------------------------------ This file is part of deegree. Copyright (C) 2001-2008 by: EXSE, Department of Geography, University of Bonn http://www.giub.uni-bonn.de/deegree/ lat/lon GmbH http://www.lat-lon.de This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: Andreas Poth lat/lon GmbH Aennchenstraße 19 53177 Bonn Germany E-Mail: [email protected] Prof. Dr. Klaus Greve Department of Geography University of Bonn Meckenheimer Allee 166 53115 Bonn Germany E-Mail: [email protected] ---------------------------------------------------------------------------*/ package org.deegree.ogcwebservices.wpvs.capabilities; import org.deegree.model.metadata.iso19115.Keywords; /** * This class represents a style object. * * @author <a href="mailto:[email protected]">Judit Mays</a> * @author last edited by: $Author: apoth $ * * @version 2.0, $Revision: 9345 $, $Date: 2007-12-27 17:22:25 +0100 (Do, 27. Dez 2007) $ * * @since 2.0 */ public class Style { private String name; private String title; private String abstract_; private Keywords[] keywords; private Identifier identifier; private LegendURL[] legendURLs; private StyleSheetURL styleSheetURL; private StyleURL styleURL; /** * Creates a new style object from the given parameters. * * @param name * @param title * @param abstract_ * @param keywords * @param identifier * @param legendURLs * @param styleSheetURL * @param styleURL */ public Style( String name, String title, String abstract_, Keywords[] keywords, Identifier identifier, LegendURL[] legendURLs, StyleSheetURL styleSheetURL, StyleURL styleURL ) { this.name = name; this.title = title; this.abstract_ = abstract_; this.keywords = keywords; this.identifier = identifier; this.legendURLs = legendURLs; this.styleSheetURL = styleSheetURL; this.styleURL = styleURL; } /** * @return Returns the abstract_. */ public String getAbstract() { return abstract_; } /** * @return Returns the identifier. */ public Identifier getIdentifier() { return identifier; } /** * @return Returns the keywords. */ public Keywords[] getKeywords() { return keywords; } /** * @return Returns the legendURLs. */ public LegendURL[] getLegendURLs() { return legendURLs; } /** * @return Returns the name. */ public String getName() { return name; } /** * @return Returns the styleSheetURL. */ public StyleSheetURL getStyleSheetURL() { return styleSheetURL; } /** * @return Returns the styleURL. */ public StyleURL getStyleURL() { return styleURL; } /** * @return Returns the title. */ public String getTitle() { return title; } }
dabe0db637046f8b345bed499c14f57672c3393d
d0ea8a4e21adbcbbb00f46ec690d7312e266b983
/src/main/java/com/example/project/service/UserService.java
ebf4e21b221faed4ee9a6de08249ad11224386a2
[]
no_license
vanchela/ProjectAnimalShelter
599f4e84bc816c37053b310954d5df7cba5334d8
90e2279bea2109edc208ea8cc482c176809cd497
refs/heads/master
2023-04-10T11:23:31.991321
2021-04-07T13:59:38
2021-04-07T13:59:38
350,018,734
0
0
null
null
null
null
UTF-8
Java
false
false
568
java
package com.example.project.service; import com.example.project.model.entities.Role; import com.example.project.model.entities.User; import com.example.project.model.enums.RoleEnum; import com.example.project.model.service.UserRegistrationServiceModel; import java.util.List; public interface UserService { boolean usernameExists(String username); void registerAndLoginUser(UserRegistrationServiceModel userServiceModel); List<String> findAllUsernames(); void addRole(String username, RoleEnum valueOf); User getUser(String username); }
7d1e36eb8a74d364e073c327e47527896f08df4c
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-14227-14-14-NSGA_II-LineCoverage:ExceptionType:StackTraceSimilarity/com/xpn/xwiki/store/XWikiHibernateStore_ESTest.java
809488c5e13efbdd8774aa331d5c53fc927ea3d6
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
/* * This file was automatically generated by EvoSuite * Tue Jan 21 19:05:21 UTC 2020 */ package com.xpn.xwiki.store; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true) public class XWikiHibernateStore_ESTest extends XWikiHibernateStore_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
833ef65aa6d142bab26fe7b274ac57751d9dda17
d6fc5638cf2911a4af7eec5d7890988bcc42ddaa
/app/src/main/java/ru/by/rsa/DebitActivity.java
511a1226aa6077b9a446b349401232c75584a9cb
[]
no_license
artem-shevchuk84/RSA_sources
e77f2633ddf20026197e435cabd14454cff4b640
968c5fdfe2a4c3f3594b4ee98d9782e434bdbe12
refs/heads/master
2020-03-07T09:25:23.194667
2018-03-30T09:09:59
2018-03-30T09:09:59
127,407,234
0
0
null
null
null
null
UTF-8
Java
false
false
31,896
java
package ru.by.rsa; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnShowListener; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.InputFilter; import android.text.Spanned; import android.text.method.DigitsKeyListener; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import ru.by.rsa.adapter.item.ComboCustomerItem; import ru.by.rsa.adapter.item.DebitItem; /** * Activity that allows user view debit * @author Komarev Roman * Odessa, [email protected], +380503412392 */ public class DebitActivity extends ListActivity implements OnItemSelectedListener { /** Is set of data from DB to be shown in ClientName-ComboBox. To get value have to use mCurosr.getString("KEY") */ private Cursor mCursor; private Dialog dg; /** Is set of data from DB to be shown in ListView. To get value have to use mCurosr.getString("KEY") */ private Cursor mCursorList; /** Arrays of columns that will be used to obtain data from DB-tables in columns with the same name */ private String[] mContent = {"_id", RsaDbHelper.CUST_ID, RsaDbHelper.CUST_NAME}; //private String[] mContentList2 = {"_id", RsaDbHelper.DEBIT_CUST_ID, RsaDbHelper.DEBIT_DATEDOC, // RsaDbHelper.DEBIT_RN, RsaDbHelper.DEBIT_SUM, RsaDbHelper.DEBIT_DATEPP, // RsaDbHelper.DEBIT_CLOSED, RsaDbHelper.DEBIT_COMMENT, RsaDbHelper.DEBIT_SHOP_ID }; /** Special adapter that must be used between mCursor and combobox of customer selection */ private SimpleCursorAdapter mAdapter; private final static int IDD_INCOME = 1; /** Special adapter that must be used between mCursorList and ListView */ private SimpleAdapter mAdapterList; EditText edtDsc; /** Open SQLite database that stores all data */ SQLiteDatabase db; SQLiteDatabase db_orders; Spinner cmbCust; TextView txtTotal; TextView txtCashTotal; String currentCustID; int currentPosition; /** Designed class to store data of current order before save it to database */ private OrderHead mOrderH = null; ArrayList<DebitItem> list; DebitItem currentItem; /** Current theme */ private boolean lightTheme; private String currency; private static int verOS = 0; private boolean isPad; @Override public void onCreate(Bundle savedInstanceState) { verOS = 2; try { verOS = Integer.parseInt(Build.VERSION.RELEASE.substring(0,1)); } catch (Exception e) {}; isPad = false; lightTheme = getSharedPreferences(RsaDb.PREFS_NAME_MAIN, Context.MODE_PRIVATE).getBoolean(RsaDb.LIGHTTHEMEKEY, false); SharedPreferences def_prefs = PreferenceManager.getDefaultSharedPreferences(this); currency = " "+def_prefs.getString("prefCurrency", getResources().getString(R.string.preferences_currency_summary)); if (lightTheme) { setTheme(R.style.Theme_Custom); super.onCreate(savedInstanceState); setContentView(R.layout.l_debit); } else { setTheme(R.style.Theme_CustomBlack2); super.onCreate(savedInstanceState); setContentView(R.layout.debit); } if (savedInstanceState != null) { Bundle extras = savedInstanceState; currentCustID = extras.getString("CUST_ID"); currentPosition = extras.getInt("POSITION"); currentItem = extras.getParcelable("CURITEM"); String sklad_id = extras.getString("SKLADID"); if (sklad_id!=null) { mOrderH = extras.getParcelable("ORDERH"); } } else { currentCustID = ""; currentPosition = 0; } /** Data from previous activity (HeadActivity.class) to extras variable */ Bundle extras; // Get data from previous activity (HeadActivity.class) to extras variable */ extras = getIntent().getExtras(); if (extras != null) { // Init class to store data of current order before save it to database mOrderH = new OrderHead(); // Get data of current order from back activity(HeadActivity.class) to this */ mOrderH = extras.getParcelable("ORDERH"); } } @Override public void onStart() { super.onStart(); isPad = RsaDb.checkScreenSize(this, 5); txtCashTotal = (TextView)findViewById(R.id.txtCash_debit); txtCashTotal.setText("0.00"); // Button when user wants to go back to orders list, by pressing // it current activity going down, and previous activity // starts (RSAActivity) Button btnBack = (Button)findViewById(R.id.debit_pbtn_prev); // Listener for OK-button click, calls when OK-button clicked btnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); if (mOrderH != null) { Bundle b = new Bundle(); b.putInt("MODE", mOrderH.mode); b.putString("_id", mOrderH._id); b.putString("SKLADID", mOrderH.sklad_id.toString()); b.putString("REMARK", mOrderH.remark.toString()); b.putString("DELAY", mOrderH.delay.toString()); b.putString("DISCOUNT", mOrderH.id.toString()); intent.putExtra("ORDERH", mOrderH); intent.putExtras(b); } setResult(RESULT_OK, intent); finish(); } }); updateList(); } /** * Fills combobox and display with data */ private void updateList() { /** Get Shared Preferences */ SharedPreferences prefs = getSharedPreferences(RsaDb.PREFS_NAME, Context.MODE_PRIVATE); /** Init database with architecture that designed in RsaDbHelper.class */ RsaDbHelper mDb = new RsaDbHelper(this, prefs.getString(RsaDb.ACTUALDBKEY, RsaDbHelper.DB_NAME1)); RsaDbHelper mDb_orders = new RsaDbHelper(this, RsaDbHelper.DB_ORDERS); // Open SQLite database that stores all data db = mDb.getWritableDatabase(); db_orders = mDb_orders.getWritableDatabase(); /** Binding xml elements of view to variables */ cmbCust = (Spinner)findViewById(R.id.cmbDebit_debit); // Get data from database to mCursorList by call query: // SELECT TABLE_DEBIT FROM mContentList // mCursorList = db.query(RsaDbHelper.TABLE_DEBIT, mContentList, null, null, null, null, null); // if debit is empty exit from function // if (mCursorList.getCount()<1) // return; // Init mCursor to work with it // //19.12.2012 Romka // if (verOS<3) startManagingCursor(mCursorList); // Move to first record in mCursor // mCursorList.moveToFirst(); /* String MY_QUERY = "SELECT _cust._id, _cust.ID, _cust.NAME " + "FROM _cust " + "WHERE _cust.ID IN (SELECT _debit.CUST_ID FROM _debit) " + "ORDER BY _cust.NAME";*/ if (mOrderH!=null && mOrderH.cust_id!=null && mOrderH.shop_id!=null && !mOrderH.cust_id.equals("-XXX") && !mOrderH.shop_id.equals("ZZZ")) { String testQuery = "select CUST_ID from _debit where CLOSED!='2' and CUST_ID='"+mOrderH.cust_id+"' limit 1"; Cursor testCursor = db.rawQuery(testQuery, null); if (testCursor.getCount()<1) { ContentValues insertValues = new ContentValues(); SimpleDateFormat formatNew = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat formatOld = new SimpleDateFormat("dd.MM.yy"); Calendar c = Calendar.getInstance(); //insertValues.put("_id", null); insertValues.put(RsaDbHelper.DEBIT_ID, "new"); insertValues.put(RsaDbHelper.DEBIT_CUST_ID, mOrderH.cust_id.toString()); insertValues.put(RsaDbHelper.DEBIT_RN, "new"); insertValues.put(RsaDbHelper.DEBIT_DATEDOC, formatOld.format(c.getTime())); insertValues.put(RsaDbHelper.DEBIT_SUM, "0"); insertValues.put(RsaDbHelper.DEBIT_DATEPP, formatNew.format(c.getTime())); insertValues.put(RsaDbHelper.DEBIT_CLOSED, "0"); insertValues.put(RsaDbHelper.DEBIT_COMMENT, ""); insertValues.put(RsaDbHelper.DEBIT_SHOP_ID, mOrderH.shop_id.toString()); insertValues.put(RsaDbHelper.DEBIT_PAYMENT, ""); db.insert(RsaDbHelper.TABLE_DEBIT, RsaDbHelper.DEBIT_CUST_ID, insertValues); } } String MY_QUERY = "SELECT _debit._id, _debit.CUST_ID as ID, _cust.NAME " + "FROM _debit " + "INNER JOIN _cust " + "ON _debit.CUST_ID = _cust.ID " + "WHERE CLOSED!='2' " + "GROUP BY _debit.CUST_ID " + "ORDER BY _cust.NAME"; // Get data from database to mCursor by call query: // SELECT TABLE_CUST FROM mContent ORDERBY CUST_NAME //mCursor = db.query(RsaDbHelper.TABLE_CUST, mContent, null, null, null, null, RsaDbHelper.CUST_NAME); mCursor = db.rawQuery(MY_QUERY, null); // if no cutomers to show then exit from function if (mCursor.getCount()<1) return; // Init mCursor to work with it // //19.12.2012 Romka if (verOS<3) startManagingCursor(mCursor); // Move to first record in mCursor mCursor.moveToFirst(); // Init mAdapter with binding data in mCursor with values customer combobox mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mCursor, mContent, new int [] {0, 0, android.R.id.text1}); // Set standart DropDown view mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Set mAdapter to customers combobox data adapter to show data from mCursor on combobox cmbCust.setAdapter(mAdapter); // Set Listener for Customer combobox - this activity (DebitActivity.class) // so we have to Override special listening methods in this class cmbCust.setOnItemSelectedListener(this); if (mOrderH != null) { mCursor.moveToFirst(); for (int i=0;i<mCursor.getCount();i++) { if (mCursor.getString(1).equals(mOrderH.cust_id)) { cmbCust.setSelection(i); this.onItemSelected(null, null, i, 0); break; } mCursor.moveToNext(); } } else { // Select first record in combobox this.onItemSelected(null, null, 0, 0); } Log.d("RRR","R"); } private void updateRNList(int index, String cash) { SharedPreferences def_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean isAutocorrect = def_prefs.getBoolean("prefDebitAutocorrection", false); String sum = currentItem.get(DebitItem.SUM); String startsum = currentItem.get(DebitItem.STARTDEBT); String mon = cash; float ss = 0; if (isAutocorrect) { float s = Float.parseFloat(sum.equals("")?"0":sum); float m = Float.parseFloat(mon.equals("")?"0":mon); ss = Float.parseFloat(startsum.equals("")?"0":startsum); s = ss - m; sum = Float.toString(s); //Log.d("RRR","sum="+sum); //Log.d("RRR","ss="+startsum); } DebitItem newItem = new DebitItem( currentItem.get(DebitItem.DATEDOC), sum, currentItem.get(DebitItem.EXPDATE), currentItem.get(DebitItem.DOCNUMBER), currentItem.get(DebitItem.EXPIRED), cash, currency, currentItem.get(DebitItem.COMMENT), currentItem.get(DebitItem.ADDRESS), currentItem.get(DebitItem.STARTDEBT)); list.set(index, newItem); setListAdapter(mAdapterList); try { txtCashTotal.setText(calcCashSum(list)); } catch (Exception e) { txtCashTotal.setText("0"); Toast.makeText(this, "Sum calculation error", Toast.LENGTH_SHORT).show(); } Log.d("RR","D"); } /** * Metohd that starts when another activity becomes on display */ @Override public void onStop() { try { super.onStop(); // We have to release mAdapter with that Cursor // before Activity will close if (this.mAdapter !=null) { ((CursorAdapter) this.mAdapter).getCursor().close(); this.mAdapter= null; } // We have to release mCursorList // before Activity will close if (this.mCursorList != null) { this.mCursorList.close(); } // We have to release mCursor // before Activity will close if (this.mCursor != null) { this.mCursor.close(); } } catch (Exception error) { /** Error Handler Code **/ } // Close database after reading if (db != null) { db.close(); } if (db_orders != null) { db_orders.close(); } } /** * Selects item from combobox with customers list. When user do this * program make query to database to get list of debit that Customer have * and binds that list to listview * @param arg0 - In this param system puts pointer to parent * @param arg1 - In this param system puts pointer to selected View, used to apply selection * @param arg3 - In this param system puts id of selected View */ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { SharedPreferences def_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean isAutocorrect = def_prefs.getBoolean("prefDebitAutocorrection", false); txtTotal = (TextView)findViewById(R.id.debit_txtTotal); // Move cursor to selected position mCursor.moveToPosition(arg2); currentCustID = mCursor.getString(1); def_prefs.edit().putString("prevSCust", currentCustID).commit(); // Get data from database to mCursorList by call query: // SELECT TABLE_DEBIT FROM mContentList //mCursorList = db.query(RsaDbHelper.TABLE_DEBIT, mContentList2, // RsaDbHelper.DEBIT_CUST_ID + "='" // + mCursor.getString(1) + "'", // null, null, null, null); String query = "select d._id, d.CUST_ID, d.DATEDOC, d.RN, d.SUM, " + "d.DATEPP, d.CLOSED, d.COMMENT, s.NAME from _debit as d " + "left join _shop as s on s.CUST_ID=d.CUST_ID and s.ID = d.SHOP_ID " + "where CLOSED!='2' and d.CUST_ID='"+ mCursor.getString(1) + "' order by s.NAME"; mCursorList = db.rawQuery(query, null); if (mCursorList.getCount()<1) return; // Init mCursor to work with it //19.12.2012 Romka if (verOS<3) startManagingCursor(mCursorList); // Move to first record in mCursorList mCursorList.moveToFirst(); float fltTotalDebit = 0; float fltTotalExpired = 0; Calendar c = Calendar.getInstance(); Date currentDate = c.getTime(); Date expireDate = c.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); long diff = 0; float deb = 0; float cs = 0; long lngExpiredDays = 0; StringBuilder strExpiration; list = new ArrayList<DebitItem>(); for (int i=0;i<mCursorList.getCount();i++) { strExpiration = new StringBuilder(getResources().getString(R.string.debit_txtExpired)); // Expired.......-> try { expireDate = sdf.parse(mCursorList.getString(5)); // invoice expiration date diff = currentDate.getTime() - expireDate.getTime(); // difference between exp and current date deb = Float.parseFloat(mCursorList.getString(4).replace(',', '.')); // invoice debit if (isAutocorrect) { cs = getKassaDet(mCursorList.getString(1), mCursorList.getString(3)); } // Expired days, if <= 0 then NOT EXPIRED lngExpiredDays = diff / (24 * 60 * 60 * 1000); // Total Debit for current Customer fltTotalDebit += deb - cs; if (lngExpiredDays > 0) { // Total Expired debit for current Customer fltTotalExpired += deb - cs; } else { // Expired days, if <= 0 then NOT EXPIRED and make it = 0 lngExpiredDays = 0; // Expired debit for current invoice make it 0 because NOT EXPIRED deb = 0; } } catch (Exception e) {} strExpiration.append(String.format("%.2f",deb).replace(',', '.')); strExpiration.append(getResources().getString(R.string.debit_txtFor)); strExpiration.append(Long.toString(lngExpiredDays)); strExpiration.append(getResources().getString(R.string.debit_txtDays)); String cash = ""; String d = sdf.format(currentDate); // current date String id = currentCustID; String rn = mCursorList.getString(3); String comment = mCursorList.getString(7); if(comment==null||comment.length()==0) { comment = "(без комментария)"; } try { String q = "select SUM from _kassadet where (DATE='"+d+"') and (CUST_ID='"+id+"') and (RN='"+rn+"') limit 1"; Cursor cashCursor = db_orders.rawQuery(q, null); if (cashCursor.getCount()>0) { cashCursor.moveToFirst(); cash = cashCursor.getString(0); } if (cashCursor != null) { cashCursor.close(); } } catch (Exception e3) {} String adr = "Неизвестный адрес"; try { if (mCursorList.getString(8)!=null) { adr = mCursorList.getString(8); } } catch (Exception e) {} isAutocorrect = def_prefs.getBoolean("prefDebitAutocorrection", false); String ss = mCursorList.getString(4); String startsum = mCursorList.getString(4); if (isAutocorrect) { float m = 0; try { m = Float.parseFloat(cash.equals("")?"0":cash); } catch (Exception e) {} float s = Float.parseFloat(ss.equals("")?"0":ss); s = s - m; ss = Float.toString(s); } list.add(new DebitItem( mCursorList.getString(2), // datedoc ss, // sum mCursorList.getString(5), // expdate mCursorList.getString(3), // docnumber strExpiration.toString(), // expired cash, currency, comment, adr, startsum)); mCursorList.moveToNext(); } String strExpired = String.format("%.2f",fltTotalExpired).replace(',', '.'); String strDebit = String.format("%.2f",fltTotalDebit).replace(',', '.'); txtTotal.setText(strExpired + " (" + strDebit + ")"); try { txtCashTotal.setText(calcCashSum(list)); } catch (Exception e) { txtCashTotal.setText("0"); Toast.makeText(this, "Ошибка расчета суммы", Toast.LENGTH_SHORT).show(); } mAdapterList = new SimpleAdapter( this, list, lightTheme?R.layout.l_list_debit:R.layout.list_debit, new String[] {DebitItem.DATEDOC, DebitItem.SUM, DebitItem.EXPDATE, DebitItem.DOCNUMBER, DebitItem.EXPIRED, DebitItem.CASH, DebitItem.CURRENCY, DebitItem.COMMENT, DebitItem.ADDRESS}, new int[] {R.id.txtDate_debit, R.id.txtSum_debit, R.id.txtDateAp_debit, R.id.txtRN_debit, R.id.txtExpiration_debit, R.id.txtCash_debit, R.id.txtCurrency_debit, R.id.txtComment_debit, R.id.txtAD_debit}); setListAdapter(mAdapterList); Log.d("RRR","z"); } private float getKassaDet(String c, String r) { float result = 0; try { Cursor curs = db_orders.rawQuery("select SUM from _kassadet where CUST_ID='"+c+"' and RN='"+r+"' limit 1", null); if (curs.moveToFirst()) { result = Float.parseFloat(curs.getString(0).replace(",",".")); } if (curs!=null && !curs.isClosed() ) { curs.close(); } } catch (Exception e) {} return result; } private void calculateTotal(String c) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); Date currentDate = cal.getTime(); txtTotal = (TextView)findViewById(R.id.debit_txtTotal); float fltTotalExpired = 0; float fltTotalDebit = 0; try { for (DebitItem item:list) { String cash = item.get(DebitItem.CASH).equals("")?"0":item.get(DebitItem.CASH); String st_debt = item.get(DebitItem.STARTDEBT).equals("")?"0":item.get(DebitItem.STARTDEBT); fltTotalDebit += Float.parseFloat(st_debt) - Float.parseFloat(cash); Date expireDate = sdf.parse(item.get(DebitItem.EXPDATE)); if (expireDate.getTime() < currentDate.getTime()) { fltTotalExpired += Float.parseFloat(st_debt) - Float.parseFloat(cash); } Log.d("zaza", "total="+Float.toString(fltTotalDebit) + " | Expired="+Float.toString(fltTotalExpired)); } }catch(Exception e) { Log.d("zulu",e.getMessage()); } String strExpired = String.format("%.2f",fltTotalExpired).replace(',', '.'); String strDebit = String.format("%.2f",fltTotalDebit).replace(',', '.'); txtTotal.setText(strExpired + " (" + strDebit + ")"); } private String calcCashSum(ArrayList<DebitItem> l) { String result = "0.00"; float s = 0; for (DebitItem item : l ) { try { s += Float.parseFloat(item.get(DebitItem.CASH)); } catch (Exception e3) {} } result = String.format("%.2f", s).replace(',', '.'); return result; } /** * If Back-button on device pressed then do... */ @Override public void onBackPressed() { Intent intent = new Intent(); if (mOrderH != null) { Bundle b = new Bundle(); b.putInt("MODE", mOrderH.mode); b.putString("_id", mOrderH._id); b.putString("SKLADID", mOrderH.sklad_id.toString()); b.putString("REMARK", mOrderH.remark.toString()); b.putString("DELAY", mOrderH.delay.toString()); b.putString("DISCOUNT", mOrderH.id.toString()); intent.putExtra("ORDERH", mOrderH); intent.putExtras(b); } setResult(RESULT_OK, intent); finish(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } public void onListItemClick(ListView parent, View v, int position, long id) { currentItem = list.get(position); currentPosition = position; showDialog(IDD_INCOME); } private boolean alreadyTaken(String date, String cust_id, String rn) { boolean result = false; Cursor cashCursor = null; try { String q = "select SUM from _kassadet where (DATE='"+date+"') and (CUST_ID='"+cust_id+"') and (RN='"+rn+"') limit 1"; cashCursor = db_orders.rawQuery(q, null); if (cashCursor.getCount()>0) { result = true; } } catch (Exception e3) {} try { if (cashCursor != null) { cashCursor.close(); } } catch (Exception e4) {} return result; } @Override protected Dialog onCreateDialog(int id, Bundle args) { switch(id) { case IDD_INCOME: { /** Set my own view of dialog to display to layout variable. Uses dlg_head.xml */ LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.dlg_head, (ViewGroup)findViewById(R.id.linear_dlg_head)); /** Binding xml element of my own layout to final variable */ edtDsc = (EditText)layout.findViewById(R.id.edtRemark_head); edtDsc.setInputType(android.text.InputType.TYPE_CLASS_NUMBER); int maxLength = 9; InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(maxLength); edtDsc.setFilters(FilterArray); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(layout); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Calendar c = Calendar.getInstance(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat fmtTime = new SimpleDateFormat("HH:mm:ss"); String time = fmtTime.format(c.getTime()); String date = fmt.format(c.getTime()); String cust_id = currentCustID; String rn = currentItem.get(DebitItem.DOCNUMBER); String sum = edtDsc.getText().toString(); sum = sum.equals("")?"0":sum; String full = "0"; String cust_name = ((TextView)cmbCust.getSelectedView()).getText().toString(); SharedPreferences def_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean isAutocorrect = def_prefs.getBoolean("prefDebitAutocorrection", false); try { float f_sum = Float.parseFloat(sum); float prev_sum = Float.parseFloat(currentItem.get(DebitItem.STARTDEBT)); if (f_sum>prev_sum) { if (isAutocorrect==true && prev_sum>0) { sum = currentItem.get(DebitItem.STARTDEBT); Toast.makeText(getApplicationContext(),"Автокоррекция! Денег больше чем долга!!",Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(),"Денег больше чем долга!!",Toast.LENGTH_LONG).show(); } } } catch (Exception e) {} ContentValues values = new ContentValues(); values.put(RsaDbHelper.KASSADET_SUM, sum); values.put(RsaDbHelper.KASSADET_DATE, date); if (alreadyTaken(date, cust_id, rn)) { db_orders.update(RsaDbHelper.TABLE_KASSADET, values, "(DATE='"+date+"') and (CUST_ID='"+cust_id+"') and (RN='"+rn+"')", null); } else { values.put(RsaDbHelper.KASSADET_CUST_ID, cust_id); values.put(RsaDbHelper.KASSADET_RN, rn); values.put(RsaDbHelper.KASSADET_CUSTNAME, cust_name); values.put(RsaDbHelper.KASSADET_FULL, full); values.put(RsaDbHelper.KASSADET_TIME, time); db_orders.insert(RsaDbHelper.TABLE_KASSADET, RsaDbHelper.KASSADET_CUST_ID, values); } InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edtDsc.getWindowToken(), 0); updateRNList(currentPosition, sum); if (isAutocorrect) { calculateTotal(cust_id); } } }); builder.setNegativeButton(R.string.head_dlg_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edtDsc.getWindowToken(), 0); } }); Dialog md = builder.create(); md.requestWindowFeature(Window.FEATURE_NO_TITLE); dg = md; return md; } default: return null; } } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); // Determining the type of dialog to show, in this Activity only one dialog switch(id) { case IDD_INCOME: { /** Binding xml element of remark edit */ edtDsc = (EditText)dialog.findViewById(R.id.edtRemark_head); edtDsc.setInputType(android.text.InputType.TYPE_CLASS_NUMBER | android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL); edtDsc.setFilters(new InputFilter[] {}); edtDsc.setText(currentItem.get(DebitItem.STARTDEBT)); edtDsc.setFilters(new InputFilter[] { new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) { int beforeDecimal = 6, afterDecimal = 2; @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String temp = edtDsc.getText() + source.toString(); if (temp.equals(".")) { return "0."; } else if (temp.toString().indexOf(".") == -1) { // no decimal point placed yet // if (temp.length() > beforeDecimal) { // return ""; // } } else { // temp = temp.substring(temp.indexOf(".") + 1); // if (temp.length() > afterDecimal) { // return ""; // } } return super.filter(source, start, end, dest, dstart, dend); } } }); edtDsc.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View arg0) { return false; }}); edtDsc.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View arg0, MotionEvent arg1) { return false; }}); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialog) { edtDsc.setSelection(0, edtDsc.getText().toString().length()); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(edtDsc, InputMethodManager.SHOW_FORCED); } }); } break; default: // Do nothing if another kind of dialog is selected } if (isPad == false) { dialog.getWindow().setGravity(Gravity.TOP); } else { dialog.getWindow().setGravity(Gravity.CENTER); } dg = dialog; } @Override protected void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); outState.putString("CUST_ID", currentCustID); outState.putInt("POSITION", currentPosition); outState.putParcelable("CURITEM", currentItem); if (mOrderH!=null) { outState.putInt("MODE", mOrderH.mode); outState.putString("_id", mOrderH._id); outState.putString("SKLADID", mOrderH.sklad_id.toString()); outState.putString("REMARK", mOrderH.remark.toString()); outState.putString("DELAY", mOrderH.delay.toString()); outState.putString("DISCOUNT", mOrderH.id.toString()); outState.putParcelable("ORDERH", mOrderH); } try { if (dg != null) dg.dismiss(); } catch (Exception e) {} } }
[ "Ghjuhfvth16" ]
Ghjuhfvth16
b3481eb5df81e31b0ddb0a5296d655e2e858c20b
38d12b616edd275f6b7697857d25d1ecf9cd740d
/src/main/java/com/example/javaWebDemo/AntiLeechServlet.java
2190056b95720a6cee7c57eb9e78684f1528ce38
[]
no_license
zhaoshichen1/java_demo
42b74a13b36e44171f2d85e15772f2edbecaa96c
03485380f5aa560e452c06511dc0647ad04635c9
refs/heads/main
2023-03-06T07:53:10.918370
2021-02-17T17:11:20
2021-02-17T17:11:20
332,954,202
1
0
null
null
null
null
UTF-8
Java
false
false
1,590
java
package com.example.javaWebDemo; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; /** * 防盗链逻辑实现 */ @WebServlet(name = "AntiLeechServlet", value = "/AntiLeechServlet") public class AntiLeechServlet extends HttpServlet { /** * 以下的请求会命中防盗链逻辑从而进行重定向;需要从首页点击请求后访问; * curl -X GET \ * http://localhost:8080/javaWebDemo_war_exploded/AntiLeechServlet \ * -H 'Content-Type: application/x-www-form-urlencoded' \ * -H 'Postman-Token: 51b00920-e009-4a3d-b7fd-e630f692c54e' \ * -H 'cache-control: no-cache' * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String refer = request.getHeader("Referer"); System.out.println(refer); // 不是从我的首页进来的,不被允许的访问 if (refer == null || !refer.contains("http://localhost:8080/javaWebDemo_war_exploded/")){ response.sendRedirect("/javaWebDemo_war_exploded"); return ; } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("恭喜你,被允许的访问获取到数据了!"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
3c54191fdd6b5905f8b15ba6e3e8d4f486cb76f8
e059ffae6926997f34b666e7901f1be1fcb763da
/src/main/java/com/urbancode/terraform/tasks/vmware/util/Path.java
f2515e07faca501178ac082c0a67bbcf1bb978f6
[ "Apache-2.0" ]
permissive
sjroot/terraform
5cd81829590ad6a742645a8a508164dad5e738aa
d67ac40cb3609173cdb369a0bb400d18d01797f2
refs/heads/master
2021-01-17T11:59:13.116800
2013-05-07T17:23:37
2013-05-07T17:23:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,734
java
/******************************************************************************* * Copyright 2012 Urbancode, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.urbancode.terraform.tasks.vmware.util; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Path implements Serializable { //********************************************************************************************** // CLASS //********************************************************************************************** private static final long serialVersionUID = 1L; //********************************************************************************************** // INSTANCE //********************************************************************************************** final private List<String> path; //---------------------------------------------------------------------------------------------- public Path(Path parent, String name) { List<String> path = parent.toList(); String[] split = name.split("/"); for (int i=0; i<split.length; i++) { path.add(split[i]); } this.path = path; } //---------------------------------------------------------------------------------------------- public Path(String path) { // scrub path path = path.replaceAll("/+", "/"); if (path.startsWith("/")) { path = path.substring(1); } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } this.path = Arrays.asList(path.split("/")); } //---------------------------------------------------------------------------------------------- private Path(List<String> path) { this.path = path; } //---------------------------------------------------------------------------------------------- @Override public String toString() { StringBuilder sb = new StringBuilder(); for (String p : path) { sb.append("/"); sb.append(p); } return sb.toString(); } //---------------------------------------------------------------------------------------------- public Path getFolders() { Path result; if (path.size() < 1) { throw new RuntimeException("No folders specified"); } else { result = new Path(path.subList(1, path.size())); } return result; } //---------------------------------------------------------------------------------------------- public String getDatacenterName() { String result; if (path.size() < 1) { throw new RuntimeException("No datacenter specified"); } else { result = path.get(0); } return result; } //---------------------------------------------------------------------------------------------- public String getHostName() { String result; if (path.size() < 2) { throw new RuntimeException("No host specified"); } else { result = path.get(1); } return result; } //---------------------------------------------------------------------------------------------- public String getName() { String result; if (path.size() == 0) { result = ""; } else { result = path.get(path.size() - 1); } return result; } //---------------------------------------------------------------------------------------------- public Path getParent() { Path result; if (path.size() == 0) { result = new Path(Collections.<String>emptyList()); } else { result = new Path(path.subList(0, path.size() - 1)); } return result; } //---------------------------------------------------------------------------------------------- public Path getParentFolders() { Path result; if (path.size() < 2) { throw new RuntimeException("No parent folders"); } else { result = new Path(path.subList(1, path.size() - 1)); } return result; } //---------------------------------------------------------------------------------------------- public List<String> toList() { return new ArrayList<String>(path); } //---------------------------------------------------------------------------------------------- @Override public boolean equals(Object otherPath) { boolean result; if (otherPath instanceof Path) { result = this.toString().equals(otherPath.toString()); } else { result = false; } return result; } //---------------------------------------------------------------------------------------------- @Override public int hashCode() { return toString().hashCode(); } }
4a5fe73d4be9862aff6c2a69b5a4f0d21928b69b
a29f3585fb83ee521d2298a7b5a11ff5c2cb750f
/builder/src/main/java/com/galaxyt/aquarius/builder/VegBurger.java
7d62ab53c49e15432db3b521543bd9c807241c1a
[]
no_license
galaxy-t/aquarius
e59fd1f8bf3d2bb360379f8adba6fcc81501dd7d
dafbde33f21b60ec4a8b19b446405a2af33b3d8c
refs/heads/master
2020-06-13T06:57:01.430195
2019-07-01T10:41:03
2019-07-01T10:41:03
194,578,793
3
1
null
null
null
null
UTF-8
Java
false
false
708
java
package com.galaxyt.aquarius.builder; /** * 蔬菜汉堡 * 扩展了 Burger 的实体类。 * @author zhouqi * @date 2019-06-28 14:06 * @version v1.0.0 * @Description * * Modification History: * Date Author Version Description ---------------------------------------------------------------------------------* * 2019-06-28 14:06 zhouqi v1.0.0 Created * */ public class VegBurger extends Burger { /** * 蔬菜汉堡的价格 * @return */ public float price() { return 25.0f; } /** * 蔬菜汉堡的名称 * @return */ public String name() { return "蔬菜汉堡"; } }
5c2622bf32aaa0b5ed3c10edde4c3768ca7b7528
a4515123a47a3f6e5d24783ec804c47dd6110045
/src/main/java/ood/jigsaw/PuzzleBlockEdge.java
c240a1ae226eff7863dc6906d13f92ff2a6881de
[]
no_license
sjw611/code-interview
afdf3a51c11d10783f533ea00ff23452d4a1465f
e0567bc633a40cfe88af30b7d907477022ab2793
refs/heads/master
2021-01-01T18:00:05.062467
2018-09-25T20:24:03
2018-09-30T20:29:24
98,219,209
0
0
null
2017-09-05T17:41:26
2017-07-24T17:56:07
Java
UTF-8
Java
false
false
102
java
package ood.jigsaw; public interface PuzzleBlockEdge { boolean fitsWith(PuzzleBlockEdge another); }
8dd6adb891c0af99200dd7b7b5a66b81ff472e92
7732cf7715d336916216b4457f3c00c46d0bd71b
/app/src/main/java/com/wwc2/main/driver/eq/EQDriverable.java
1345cd8fdb437f7722dd5678433234de470b97f5
[]
no_license
mlopezsegura/Main
b57c9d6254d3894dc766420604be6b766c0cbb96
6b5b74b9ef4c9b180ab75a1fc300652df117ddb4
refs/heads/master
2023-03-17T18:47:57.960474
2020-11-14T02:42:55
2020-11-14T02:42:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
861
java
package com.wwc2.main.driver.eq; /** * the eq driver interface. * * @author wwc2 * @date 2017/1/20 */ public interface EQDriverable { void enter(); /**设置等响度*/ void setLoudness(boolean enable); boolean getLoudness(); /**设置风格*/ void setStyle(int style); /**设置频率值*/ void setTypeValue(int type, int value); /**声场设置*/ void setX(int x); void setY(int y); void setField(int[] data); /**DSP设置*/ void setDspSoundEffects(int index, int type, int value); void setDspParam(int type, int value); void setDspSoundField(int type, int value); void resetDsp(int value); void set3D(boolean enable); void outputDsp(); void setDspHpfLpf(int type, int value); void setQValue(int value); void setSubwoofer(boolean enable, int subwooferFreq); }
dd8df5365e3eedb817dd7fab5f20a42127eb44ac
adc9a81f6857e7e0be6faf1a54223faa05e78b47
/TemperatureConverter/src/ru/academits/java/kononov/temperatureconverter/model/scales/FahrenheitScale.java
bd8aba512e5e7acf32c0ba2017b667f4669ce48b
[]
no_license
EgorKononov/JavaOop
814d008f274c7c8b2ffd213c70d35422aa28684c
f79244b139e887b800c4c901d57e7d9dd0f510fd
refs/heads/main
2023-04-18T03:19:17.952991
2021-05-06T08:03:45
2021-05-06T08:03:45
300,429,333
0
0
null
null
null
null
UTF-8
Java
false
false
385
java
package ru.academits.java.kononov.temperatureconverter.model.scales; public class FahrenheitScale implements Scale { @Override public double convertToCelsius(double initialTemperature) { return (initialTemperature - 32) / 1.8; } @Override public double convertFromCelsius(double initialTemperature) { return initialTemperature * 1.8 + 32; } }
c07f189aaf3ed6978f9afe8e40851395c35565f0
bae51da01f34ef38ad782bbf7f09a05468c77cab
/moco-core/src/main/java/com/github/dreamhead/moco/extractor/CookiesRequestExtractor.java
e6bea7bf5a36b5f702d5c677991686c8b6e20a27
[ "MIT" ]
permissive
sassds/moco
3965e49f2e100c2b2ea765719657edde324e29a0
0b1606f5e6f63ed2ff003fb03449aece167d4e02
refs/heads/master
2021-01-16T21:49:16.087101
2014-07-06T23:33:29
2014-07-06T23:33:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,490
java
package com.github.dreamhead.moco.extractor; import com.github.dreamhead.moco.HttpRequest; import com.github.dreamhead.moco.RequestExtractor; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import io.netty.handler.codec.http.Cookie; import io.netty.handler.codec.http.CookieDecoder; import io.netty.handler.codec.http.HttpHeaders; import java.util.Map; import java.util.Set; import static com.google.common.base.Optional.absent; import static com.google.common.base.Optional.of; import static com.google.common.collect.ImmutableMap.copyOf; import static com.google.common.collect.Maps.newHashMap; public class CookiesRequestExtractor implements RequestExtractor<ImmutableMap<String, String>> { private final RequestExtractor<String> extractor = new HeaderRequestExtractor(HttpHeaders.Names.COOKIE); public Optional<ImmutableMap<String, String>> extract(final HttpRequest request) { Optional<String> cookieString = extractor.extract(request); if (!cookieString.isPresent()) { return absent() ; } return of(doExtract(cookieString.get())); } private static ImmutableMap<String, String> doExtract(String cookieString) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); Map<String, String> target = newHashMap(); for (Cookie cookie : cookies) { target.put(cookie.getName(), cookie.getValue()); } return copyOf(target); } }
8bd353133f4360f835b0e155da76614a8074902d
a7f5ffda2b920a53de7194991d0ff8344065df01
/22_04_2020_spring_boot_hibernate_employee/src/main/java/com/example/demo/Application.java
76795c2acb8ac68569efbee55cd1d7d7aabc79be
[]
no_license
shivam1207/LPU-IBM
bcfbe3d0ef3372398e0bd7ec8cc7630a00d073da
ad616cfc03c851aedd29e538d4ac6df51d452502
refs/heads/master
2022-12-25T02:27:38.217423
2020-05-31T13:00:46
2020-05-31T13:00:46
254,328,372
0
0
null
2022-12-16T05:16:43
2020-04-09T09:31:24
Java
UTF-8
Java
false
false
302
java
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
eb729cb8c153d6e500531dc8cb05e23ef5cc2d59
e657dbf6ad2986b0b03af4ad255f73cdf7786953
/src/main/java/br/com/digidev/web/rest/LogsResource.java
d6cf3f03407dd4aa453617d2572788a942ff773e
[]
no_license
BulkSecurityGeneratorProject/finapplication
8d01485d1181416b556408c7f5df3f78d244e9e6
65404ffe57f1d139c5a70de1c3dff8e02d39fc0f
refs/heads/master
2022-12-18T08:05:46.850532
2018-02-06T13:25:40
2018-02-06T13:25:40
296,545,689
0
0
null
2020-09-18T07:23:43
2020-09-18T07:23:42
null
UTF-8
Java
false
false
1,166
java
package br.com.digidev.web.rest; import br.com.digidev.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/management") public class LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
8f5276ef876546adcecdc71d91165784d66d18fd
c9b1daab264d885d8c4849e3d9fb5641a7bf04bb
/ch13WebDownload/app/src/test/java/com/example/ch13webdownload/ExampleUnitTest.java
a5bd8ed7b937f1adbf27c96e4f569cfc2d3aaa9a
[]
no_license
JaeWooPark96/androidTest
237fcd3fb5f728a7241e6bff2d2f96ed53d38adc
043c9200b4dd74e721efb9ae0caa6e3bcee0c4ca
refs/heads/master
2021-01-05T12:07:13.471343
2020-02-17T04:34:51
2020-02-17T04:34:51
241,019,099
0
0
null
null
null
null
UTF-8
Java
false
false
388
java
package com.example.ch13webdownload; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
a94c2ba53e77e66256a93ed18fba9ba3398a3983
d575d69018d8ab67fb10a90de1ff948a1d41cbe3
/src/main/model/Initialization.java
396295c134fa6b081d94c9d4ab9dfc17a3bcdb28
[]
no_license
KaiRunLeong/JavaFX_HotDesking_app
9a5777c6d41bdc1d8e462eeeb4f312fa6c198acb
440ec576e1a22471b6139563435deba68be6c443
refs/heads/master
2023-07-27T13:57:12.896762
2021-09-14T03:34:20
2021-09-14T03:34:20
400,216,184
0
0
null
null
null
null
UTF-8
Java
false
false
2,697
java
/* * Class: Initialization.java * * Description: The Initialization class will be called each time the login scene is * staged. This class will determine if a booking should be cancelled * automatically. * * Author: Kai Run Leong (s3862092) */ package main.model; import java.sql.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import main.SQLConnection; public class Initialization { Connection connection; /* * Description: This method will automatically cancel any bookings that has not been * been approved by the admin before the day of the booking. */ public void autoCancel() throws SQLException{ connection = SQLConnection.connect(); Statement stmt = connection.createStatement(); ResultSet myRS = null; try{ String sql = "SELECT booking_id, booking_date FROM bookings WHERE release_booking_status = 'accepted' and checked_in_status = 'pending'"; myRS = stmt.executeQuery(sql); while(myRS.next()){ setToCancel(myRS.getInt("booking_id"), myRS.getString("booking_date")); } }catch(Exception e){ }finally { stmt.close(); myRS.close(); connection.close(); } } public void setToCancel(int bookingID, String dateBooked) throws SQLException { Statement stmt = connection.createStatement(); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); //Parse booking date and booking time from string to type DATE; String bookingDate = dateBooked; java.util.Date booking_date = dateFormat.parse(bookingDate); //Yesterday's date calendar.setTime(booking_date); calendar.add(Calendar.DATE, -1); calendar.add(Calendar.HOUR_OF_DAY, 23); calendar.add(Calendar.MINUTE, 59); calendar.add(Calendar.SECOND, 59); java.util.Date deadline = calendar.getTime(); //Today's date java.util.Date currentDate = new Date(); if(currentDate.compareTo(deadline) > 0){ String sql = "UPDATE bookings SET release_booking_status = 'cancel' WHERE booking_id = " + bookingID; stmt.executeUpdate(sql); } }catch(Exception e){ e.printStackTrace(); }finally { stmt.close(); } } }
a185b2172aff6085010877054593257ec481e345
69a5b43d30d8c618a70f37c2f8bb4631b66544ab
/SiriusOrderClient/src/com/sirius/mailws/mail/wsdl/ObjectFactory.java
a57c0ad63aeae9249c4f35d51b4f57eff7b3b0ce
[]
no_license
corte128/Sirius_Order_Project_Workspace
af608c01bc4b09c5ed82f9ab85fe802ea03eed6e
0deb1515aface35f54e6251e9052a6b9c34a9beb
refs/heads/master
2021-01-23T21:12:17.681467
2017-10-06T13:45:32
2017-10-06T13:45:32
102,881,690
0
0
null
null
null
null
UTF-8
Java
false
false
4,285
java
// // Generated By:JAX-WS RI IBM 2.2.1-11/28/2011 08:28 AM(foreman)- (JAXB RI IBM 2.2.3-11/28/2011 06:21 AM(foreman)-) // package com.sirius.mailws.mail.wsdl; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.sirius.mailws.mail.wsdl package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _Message_QNAME = new QName("http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", "message"); private final static QName _SendMessageResponse_QNAME = new QName("http://jaxws.mail.service.order.sirius.com/jaxws/JaxwsMail/wsdl", "sendMessageResponse"); private final static QName _SendMessage_QNAME = new QName("http://jaxws.mail.service.order.sirius.com/jaxws/JaxwsMail/wsdl", "sendMessage"); private final static QName _ToAddress_QNAME = new QName("http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", "toAddress"); private final static QName _Subject_QNAME = new QName("http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", "subject"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.sirius.mailws.mail.wsdl * */ public ObjectFactory() { } /** * Create an instance of {@link SendMessageResponse } * */ public SendMessageResponse createSendMessageResponse() { return new SendMessageResponse(); } /** * Create an instance of {@link SendMessage } * */ public SendMessage createSendMessage() { return new SendMessage(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", name = "message") public JAXBElement<String> createMessage(String value) { return new JAXBElement<String>(_Message_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SendMessageResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://jaxws.mail.service.order.sirius.com/jaxws/JaxwsMail/wsdl", name = "sendMessageResponse") public JAXBElement<SendMessageResponse> createSendMessageResponse(SendMessageResponse value) { return new JAXBElement<SendMessageResponse>(_SendMessageResponse_QNAME, SendMessageResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SendMessage }{@code >}} * */ @XmlElementDecl(namespace = "http://jaxws.mail.service.order.sirius.com/jaxws/JaxwsMail/wsdl", name = "sendMessage") public JAXBElement<SendMessage> createSendMessage(SendMessage value) { return new JAXBElement<SendMessage>(_SendMessage_QNAME, SendMessage.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", name = "toAddress") public JAXBElement<String> createToAddress(String value) { return new JAXBElement<String>(_ToAddress_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://jaxws.attendance.service.order.sirius.com/jaxws/attendance/wsdl", name = "subject") public JAXBElement<String> createSubject(String value) { return new JAXBElement<String>(_Subject_QNAME, String.class, null, value); } }
61c9977a63dc615d9fa99f4a5b12a24132fe700f
fdbf30a3b113a236c5640b8c1c76b5eec9aa23c7
/src/weekly_contest/week_212/MinimumEffortPath.java
cc69d6467deeb3c2e1648b646f6fd16a4d94a018
[]
no_license
BUPTmango/leetcode
e12456f84215110c1d8e7aa036d9cfaa676090e1
82359d22c78c4b48881406e0d9270c372d96b32a
refs/heads/master
2021-12-08T22:33:48.029057
2021-09-30T03:25:17
2021-09-30T03:25:17
242,442,277
1
0
null
null
null
null
GB18030
Java
false
false
4,314
java
package weekly_contest.week_212; /** * 5548. 最小体力消耗路径 * 你准备参加一场远足活动。给你一个二维 rows x columns 的地图 heights ,其中 heights[row][col] 表示格子 (row, col) 的高度。一开始你在最左上角的格子 (0, 0) ,且你希望去最右下角的格子 (rows-1, columns-1) (注意下标从 0 开始编号)。你每次可以往 上,下,左,右 四个方向之一移动,你想要找到耗费 体力 最小的一条路径。 * * 一条路径耗费的 体力值 是路径上相邻格子之间 高度差绝对值 的 最大值 决定的。 * * 请你返回从左上角走到右下角的最小 体力消耗值 。 * * * * 示例 1: * * * * 输入:heights = [[1,2,2],[3,8,2],[5,3,5]] * 输出:2 * 解释:路径 [1,3,5,3,5] 连续格子的差值绝对值最大为 2 。 * 这条路径比路径 [1,2,2,2,5] 更优,因为另一条路劲差值最大值为 3 。 * 示例 2: * * * * 输入:heights = [[1,2,3],[3,8,4],[5,3,5]] * 输出:1 * 解释:路径 [1,2,3,4,5] 的相邻格子差值绝对值最大为 1 ,比路径 [1,3,5,3,5] 更优。 * 示例 3: * * * 输入:heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]] * 输出:0 * 解释:上图所示路径不需要消耗任何体力。 * * * 提示: * * rows == heights.length * columns == heights[i].length * 1 <= rows, columns <= 100 * 1 <= heights[i][j] <= 106 * @author Wang Guolong * @version 1.0 * @date 2020/10/25 11:21 上午 */ public class MinimumEffortPath { private int m = 0; private int n = 0; private int res = Integer.MAX_VALUE; private int[][] directions = new int[][]{{1,0},{0,1},{0,-1},{-1,0}}; // private boolean[][] visited; // public int minimumEffortPath(int[][] heights) { // m = heights.length; // n = heights[0].length; // visited = new boolean[m][n]; // backtrack(heights, 0, 0, 0); // return res; // } // // private void backtrack(int[][] heights, int i, int j, int strength) { // if (i == m - 1 && j == n - 1) { // res = Math.min(res, strength); // return; // } // visited[i][j] = true; // for (int[] direction : directions) { // int di = i + direction[0]; // int dj = j + direction[1]; // if (di >= 0 && dj >= 0 && di < m && dj < n && !visited[di][dj]) { // // 注意!! 这里要使用局部变量 // int tmpStrength = Math.max(strength, Math.abs(heights[di][dj] - heights[i][j])); // backtrack(heights, di, dj, tmpStrength); // } // } // visited[i][j] = false; // } /** * 二分法 通过遍历所有可能的体力来得到结果 * @param heights * @return */ public int minimumEffortPath_better(int[][] heights) { m = heights.length; n = heights[0].length; int l = 0, r = 1_000_000, ans = 0; while (l <= r) { int mid = l + (r - l) / 2; boolean[][] visited = new boolean[m][n]; if (dfs(heights, visited, 0, 0, mid)) { r = mid - 1; ans = mid; } else { l = mid + 1; } } return ans; } private boolean dfs(int[][] heights, boolean[][] visited, int i, int j, int limit) { if (i == m - 1 && j == n - 1) { return true; } visited[i][j] = true; for (int[] direction : directions) { int di = i + direction[0]; int dj = j + direction[1]; if (di >= 0 && dj >= 0 && di < m && dj < n && !visited[di][dj] && Math.abs(heights[di][dj] - heights[i][j]) <= limit) { if (dfs(heights, visited, di, dj, limit)) { return true; } } } // 注意!!! 这里不需要回溯 // visited[i][j] = false; return false; } public static void main(String[] args) { MinimumEffortPath minimumEffortPath = new MinimumEffortPath(); System.out.println(minimumEffortPath.minimumEffortPath_better(new int[][]{{1,2,1,1,1}, {1,2,1,2,1}, {1,2,1,2,1}, {1, 2,1,2,1}, {1,1,1,2,1}})); } }
c62ba55157e13948c2d3dcf40f724ebec39abf0c
a493f43c255039d977dfc3357fcf177eeee7d77b
/src/main/java/com/gemini/business/goods/po/GoodsCategoryBrandPo.java
4d9186895d2dba2021fe442a3f79cf6c7001d8bc
[]
no_license
xiaominglol/product-boot
5c04c29bbdb646fc69f3b606f7331d4eb5028c5a
ee5880de36c29de9f399a724424035afe1d6c395
refs/heads/master
2020-08-25T02:08:17.091525
2020-03-25T02:15:22
2020-03-25T02:15:22
216,946,314
0
0
null
null
null
null
UTF-8
Java
false
false
792
java
package com.gemini.business.goods.po; import com.baomidou.mybatisplus.annotation.TableName; import com.gemini.boot.framework.mybatis.po.BasePo; import lombok.Data; import lombok.EqualsAndHashCode; /** * 商品品牌表 * * @author 小明不读书 * @date Tue Nov 26 21:22:00 CST 2019 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("goods_category_brand") public class GoodsCategoryBrandPo extends BasePo { /** * 商品id */ private Long brandId; /** * 品牌名称 */ private String brandName; /** * 分类id */ private Long categoryId; /** * 分类名称 */ private String categoryName; /** * logo */ private String logo; /** * 排序 */ private Byte sort; }
c6942b15262368a8a443ce701e3febd1acc5a0d6
3fc7b81793f71e679631ec850b09e39d1fbf54df
/datalayer/manage/src/main/java/com/waben/stock/datalayer/manage/controller/AnalogDataController.java
c1299622ded45ef739db39fc1074c8b25a60475b
[]
no_license
soldiers1989/finance-1
5eabd98ef0a40b47124a1126b163bbb3e8974d8f
3fae0a3c1fba6f7d435c3242b5c8f39005b196bf
refs/heads/master
2020-04-02T05:36:57.472318
2018-05-24T01:51:31
2018-05-24T01:51:31
154,092,493
0
1
null
2018-10-22T05:41:37
2018-10-22T05:41:29
null
UTF-8
Java
false
false
1,320
java
package com.waben.stock.datalayer.manage.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.waben.stock.datalayer.manage.entity.AnalogData; import com.waben.stock.datalayer.manage.service.AnalogDataService; import com.waben.stock.interfaces.dto.manage.AnalogDataDto; import com.waben.stock.interfaces.enums.AnalogDataType; import com.waben.stock.interfaces.pojo.Response; import com.waben.stock.interfaces.pojo.query.PageInfo; import com.waben.stock.interfaces.service.manage.AnalogDataInterface; import com.waben.stock.interfaces.util.PageToPageInfo; /** * 模拟数据 Controller * * @author luomengan * */ @RestController @RequestMapping("/analogdata") public class AnalogDataController implements AnalogDataInterface { @Autowired private AnalogDataService service; public Response<PageInfo<AnalogDataDto>> pagesByType(String typeIndex, int page, int limit) { Page<AnalogData> pageData = service.pageByType(AnalogDataType.getByIndex(typeIndex), page, limit); PageInfo<AnalogDataDto> result = PageToPageInfo.pageToPageInfo(pageData, AnalogDataDto.class); return new Response<>(result); } }
09aad598e5bf69056689a01e739e43a06dd9486e
36c3e1c15afec9264b1284a417c069009c0f2744
/paas-common/src/main/java/com/yjfei/paas/common/MachineState.java
2ece954f9eab2da942ea2ab27648288645a3e68c
[]
no_license
jinfei21/paas
aaa4dc2692dcb075a504af8969d7449a4f30160e
12a3ce443e52719188e6d5b39b6c78a41dffd1b7
refs/heads/master
2021-01-02T22:34:05.142578
2018-07-04T08:04:41
2018-07-04T08:04:41
99,341,667
1
0
null
null
null
null
UTF-8
Java
false
false
1,059
java
package com.yjfei.paas.common; public enum MachineState { UP(1,"machine up",true), SLAVE_DECOMISSION(2,"slave decomission",false), RACK_DECOMISSION(3,"rack decomission",false), RACK_NOT_MATCH(2,"rack not match",false),; private int code; private boolean isAppropriate; private String text; MachineState(int code,String text,boolean isAppropriate){ this.code = code; this.text = text; this.isAppropriate = isAppropriate; } public int getCode(){ return this.code; } public boolean isAppropriate(){ return this.isAppropriate; } public static String getNameByCode(int code){ for(MachineState type:values()){ if(type.code == code){ return type.text; } } return "unknow"; } public static int getCodeByName(String name){ for(MachineState type:values()){ if(type.text.equalsIgnoreCase(name)){ return type.code; } } return 0; } public static MachineState getStateByCode(int code){ for(MachineState type:values()){ if(type.code == code){ return type; } } return UP; } }
b359f342d93ea2d7c08f30676555122bc3da3cfd
feec83628648cc40df2161c42f8b517252ab5159
/ChartCoreSlim/app/src/main/java/com/example/anan/chartcore_slim/AAChartCoreLib/AAChartEnum/AAChartLegendAlignType.java
d96101227f7f74d2571671b0adca97345fca6f19
[ "MIT", "Apache-2.0" ]
permissive
Biangkerok32/AAChartCore
2252b895659a858eb3d5cb55a94158fa93e404d3
6e11cf7239ba817c251fbaf78dfa7b6e1a53eb34
refs/heads/master
2020-07-05T05:40:23.114728
2019-08-09T16:06:22
2019-08-09T16:06:22
202,540,869
0
0
Apache-2.0
2019-08-15T12:56:28
2019-08-15T12:53:31
Java
UTF-8
Java
false
false
206
java
package com.example.anan.chartcore_slim.AAChartCoreLib.AAChartEnum; public interface AAChartLegendAlignType { String Left = "left"; String Center = "center"; String Right = "right"; }
9ed470eced6e33c2bd70ac32ac8d951d63c10178
d5f2757003543ae6771fc77225d0b6076cd1bea5
/src/LargestNumber.java
75cfe40e02dbaf96157cb9ee5a35c4026f7dd9b7
[]
no_license
quzhou/leet
f9fe44345910ec3eebfecee375b6017fa3fd0f4e
47391f6c822efc8552353b860750b9c519ffb477
refs/heads/master
2020-04-01T19:29:57.925208
2017-11-22T04:55:56
2017-11-22T04:55:56
68,641,566
0
0
null
null
null
null
UTF-8
Java
false
false
4,445
java
/** * Created by qzhou on 1/31/17. * http://www.lintcode.com/en/problem/largest-number/ */ import java.util.Comparator; import java.util.Arrays; public class LargestNumber { public String largestNumber(int[] num) { // 放在前面的是小的, return -1 Comparator<String> myComp = new Comparator<String>() { public int compare(String s1, String s2) { //return -str1.compareTo(str2); // This way does not work, 98 > 9, 3 & 39 return (s2 + s1).compareTo(s1 + s2); } }; String[] sorted = new String[num.length]; for (int i = 0; i < num.length; i++) { sorted[i] = String.valueOf(num[i]); } Arrays.sort(sorted, myComp); if (sorted[0].equals("0")) { return "0"; } String ans = ""; for (int i = 0; i < sorted.length; i++) { ans += sorted[i]; } return ans; } // http://www.lintcode.com/en/problem/string-to-integer-ii/ public int atoi(String str) { if (str.isEmpty()) { return 0; } boolean neg = false; char[] s = str.toCharArray(); int i = 0; while (s[i] == ' ') { i++; } if (s[i] == '-') { i++; neg = true; } else if (s[i] == '+') { i++; } // use double to store result double ans = 0; while (i < s.length && s[i] != '.' && s[i] != ' ' && Character.isDigit(s[i])) { ans = ans * 10 + (s[i] - '0'); i++; } if (neg) { ans = -ans; } if (ans > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (ans < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } else { return (int)ans; } } // http://www.lintcode.com/en/problem/binary-representation/ public String binaryRepresentation(String n) { if (n.indexOf('.') == -1) { return parseInteger(n); } String[] arr = n.split("\\."); if (arr.length > 2) { return "ERROR"; } String flt = parseFloat(arr[1]); if (flt == "ERROR") { return flt; } if (flt.equals("0") || flt.equals("")) { return parseInteger(arr[0]); } return parseInteger(arr[0]) + "." + flt; } private String parseInteger(String str) { if (str.isEmpty() || str.equals("0")) { return "0"; } int num = Integer.parseInt(str); String ret = ""; while (num > 0) { ret = (num & 1) + ret; num >>= 1; } return ret; } private String parseFloat(String str) { if (str.isEmpty()) { return ""; } double[] arr = new double[32]; double num = 0.5; for (int i = 0; i < 32; i++) { arr[i] = num; num /= 2; } String ret = ""; double d = Double.parseDouble("0." + str); for (int idx = 0; idx < 32; idx++) { if (d == 0) { break; } if (d >= arr[idx]) { d -= arr[idx]; ret += "1"; } else { ret += "0"; } } if (d != 0) { return "ERROR"; } return ret; } // http://www.lintcode.com/en/problem/delete-digits/ // Number can not start with 0 public String DeleteDigits(String A, int k) { int n = A.length(); if (k == n) { return "0"; } if (k == 0) { return A; } char[] buf = A.toCharArray(); int idx = -1; int len = n - k; String ans = ""; for (int i = 0; i < n - k; i++) { idx = helper(buf, idx + 1, len); len--; if (!ans.isEmpty() || buf[idx] != '0') { ans += buf[idx]; } } return ans; } // return first index of the smallest digit private int helper(char[] buf, int start, int strLen) { int idx = start; for (int i = start + 1; i <= buf.length - strLen; i++) { if (buf[i] < buf[idx]) { idx = i; } } return idx; } }
66ab6ca32b63924890473c222ebc5e5aacffa1d7
e6a7504d8016a40af49972fddecde20a6c78d213
/java-basic/Core Java v1/ch11/action/ActionFrame.java
11346ca8d11db322d6624db0899fe586c31629a6
[]
no_license
Qin-K/my-learning
311c130d3b2cbf68c53807bb275efbf4126ffa4f
176d1084210adc2903851e5f5cebd917e4e8f2fd
refs/heads/master
2023-08-31T01:06:19.947070
2023-08-28T07:46:14
2023-08-28T07:46:14
185,811,294
4
0
null
2023-07-05T20:38:15
2019-05-09T14:06:34
Java
UTF-8
Java
false
false
1,898
java
package action; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.peer.ButtonPeer; import javax.swing.event.*; public class ActionFrame extends JFrame { private JPanel buttonPanel; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; public ActionFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); // 定义事件 Action yellowAction = new ColorAction("Yellow", new ImageIcon("icon.png"), Color.YELLOW); Action blueAction = new ColorAction("Blue", new ImageIcon("icon.png"), Color.BLUE); Action redAction = new ColorAction("Red", new ImageIcon("icon.png"), Color.RED); // 为这些事件添加按钮并添加到面板 buttonPanel.add(new JButton(yellowAction)); buttonPanel.add(new JButton(blueAction)); buttonPanel.add(new JButton(redAction)); // 将面板添加到框架 add(buttonPanel); // 将动作键和名字相联系 InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow"); imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); // 将名字和事件相联系 ActionMap amap = buttonPanel.getActionMap(); amap.put("panel.yellow", yellowAction); amap.put("panel.blue", blueAction); amap.put("panel.red", redAction); } public class ColorAction extends AbstractAction{ /** * */ public ColorAction(String name, Icon icon, Color c) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, icon); putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase()); putValue("color", c); } public void actionPerformed(ActionEvent event) { Color c = (Color)getValue("color"); buttonPanel.setBackground(c); } } }
61b0660a7820aaaeb0ec871e66ebdb2c3c7989e5
c8d2266872675aa5e2bfce39deaf052d15160278
/build/decompiled/com/amap/api/mapcore/util/u.java
47fd19ac39e40726e7ef1c662a7c1d26796562c7
[]
no_license
baoxin/fluttify-core-example
3d586d4aa3ff1b5798c330fb69a34d326823c9cf
2ef109064c816d72182fdc294e3cb504896f2577
refs/heads/master
2022-04-25T05:16:46.237390
2019-08-28T07:46:52
2019-08-28T07:48:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,392
java
package com.amap.api.mapcore.util; import android.content.Context; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.location.Location; import android.os.RemoteException; import android.view.MotionEvent; import android.view.View; import com.amap.api.maps.model.BitmapDescriptor; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.LatLngBounds; import com.autonavi.ae.gmap.GLMapEngine; import com.autonavi.ae.gmap.GLMapState; import com.autonavi.ae.gmap.gesture.EAMapPlatformGestureInfo; import com.autonavi.ae.gmap.listener.AMapWidgetListener; import com.autonavi.amap.mapcore.AbstractCameraUpdateMessage; import com.autonavi.amap.mapcore.DPoint; import com.autonavi.amap.mapcore.FPoint; import com.autonavi.amap.mapcore.IPoint; import com.autonavi.amap.mapcore.interfaces.IAMap; import com.autonavi.amap.mapcore.interfaces.IMarkerAction; import com.autonavi.amap.mapcore.message.AbstractGestureMapMessage; public interface u extends IAMap { void b(); GLMapState c(); int d(); int f(int var1); int e(); void a(Location var1) throws RemoteException; boolean a(String var1) throws RemoteException; void f(); void a(double var1, double var3, IPoint var5); void a(int var1, int var2, FPoint var3); void a(int var1, int var2, DPoint var3); float g(); x h(); void a(int var1, MotionEvent var2); boolean c(int var1, MotionEvent var2); boolean b(int var1, MotionEvent var2); void a(m var1) throws RemoteException; void i(); void a(double var1, double var3, FPoint var5); void b(int var1, int var2, DPoint var3); void b(double var1, double var3, IPoint var5); void a(int var1, int var2, IPoint var3); void j(); void a(boolean var1); void b(boolean var1); void c(boolean var1); void d(boolean var1); void e(boolean var1); void g(int var1); LatLngBounds a(LatLng var1, float var2, float var3, float var4); void a(int var1, int var2, PointF var3); void a(float var1, float var2, IPoint var3); float h(int var1); boolean k(); Point l(); float t(); View m(); boolean n(); void a(ad var1); void c(String var1); ad a(BitmapDescriptor var1); ad a(BitmapDescriptor var1, boolean var2); int a(IMarkerAction var1, Rect var2); void i(int var1); void j(int var1); void k(int var1); float l(int var1); void a(int var1, float var2); int o(); void a(AbstractCameraUpdateMessage var1) throws RemoteException; void b(AbstractCameraUpdateMessage var1) throws RemoteException; Context v(); int a(EAMapPlatformGestureInfo var1); GLMapEngine a(); void a(int var1, AbstractGestureMapMessage var2); void a(int var1, int var2); boolean e(int var1); float n(int var1); void a(int var1, IPoint var2); float a(int var1); boolean d(int var1); float o(int var1); void c(int var1); void a(AMapWidgetListener var1); float[] x(); String d(String var1); void h(boolean var1); dv u(int var1); dw y(); void b(int var1, int var2); void i(boolean var1); void a(String var1, boolean var2, int var3); void z(); void q(); void a(boolean var1, byte[] var2); void a(boolean var1, boolean var2); void w(); boolean b(String var1); float v(int var1); }
35dc4c24250ba8ff0322b790351f53217b11af42
0ef3ae4029b688cce24c5cb39aa6a9b205b738dd
/src/main/java/com/kys/algorithm/sort/QuickSort2.java
18ae5d81f415cfb4fb14c2cc34e91e5c052b47cd
[]
no_license
KimYongSung/algorithm
50ee411ee15904fae1eb9cd0fded8b0e4fae2642
1ad3c826c7fda3d42f90c220362a5e36dbeca5f5
refs/heads/master
2020-07-31T13:44:13.383791
2020-02-12T14:51:13
2020-02-12T14:51:13
210,622,340
2
0
null
null
null
null
UTF-8
Java
false
false
1,025
java
package com.kys.algorithm.sort; public class QuickSort2 { public static void sort(int[] nums){ quickSort(nums, 0, nums.length-1); } private static void quickSort(int[] nums, int left, int right){ int pi = partition(nums, left, right); if(left < pi-1){ quickSort(nums, left, pi -1); } if(right > pi){ quickSort(nums, pi, right); } } private static int partition(int[] nums, int left, int right){ int mid = (left + right) /2; int pivot = nums[mid]; while(left <= right){ while(pivot > nums[left]) left++; while(pivot < nums[right]) right--; if(left <= right){ swap(nums, left, right); left++; right--; } } return left; } private static void swap(int[] nums, int pos1, int pos2){ int temp = nums[pos1]; nums[pos1] = nums[pos2]; nums[pos2] = temp; } }
2b135ae859cd7fd17c2eff7f6d86e2266ea4eb56
6a1c374d9baddd147920b5b8337ef23f22c58f93
/src/ru/luxoft/labs/lab4/hierarchy/operation/OperType.java
e2590e1c598a78749bb3baa0aed9d88bfe79ade8
[]
no_license
ssslighty/JavaTraining
e9e5c47bed400e54ecda3f5c062bff138ea1a802
8a9cdc0a6df4326f5c470475e1da15662ceeed2a
refs/heads/master
2023-04-18T08:01:42.789080
2021-04-29T15:23:40
2021-04-29T15:23:40
359,554,226
0
0
null
null
null
null
UTF-8
Java
false
false
89
java
package ru.luxoft.labs.lab4.hierarchy.operation; public enum OperType { SALE, BUY }
dde8cc866b7c10f4e0ba7f7870a6d43a2df48fbb
f4b7d25f1f928e315ab1be5b5c47ff7d6236fa82
/.svn/pristine/7e/7e065360e1a8d18af5b85dc41d5765ecfb5ff871.svn-base
402b1ad6038ea01988f986ba9b8e086d0f735d36
[]
no_license
celestinbasura/celestin.basura
c49d019024ee5faee0f395feb603a40bde067212
6048c0286ee3b7b02a40f93df1b2a75b874d5bde
refs/heads/master
2021-01-19T06:40:43.351107
2014-02-10T12:28:30
2014-02-10T12:28:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,188
/* * This is free software; you can redistribute it and/or modify it under * the terms of version 3 of the GNU General Public License as published * by the Free Software Foundation. * * Copyright 2011 Milan Draganic - NetAkademija */ package Poglavlje07.Primjeri; /** * p0622 * Rad sa dvodimenzionalnim poljima */ class P0722 { public static void main(String[] args) { int[][] polje2D = { {2, 3, 7, 5, 4, 6}, {3, 5, 6, 8}, {2}, {7, 2, 8, 7, 6, 3, 9, 5} }; int elementPodpolja = polje2D[1][2] = 7; int duljinaPodpolja = polje2D[0].length; int duljinaPolja2D = polje2D.length; System.out.println("Polje polje2D: " + dvaDPoljeToString(polje2D)); } public static String dvaDPoljeToString(int[][] p) { String s = "["; for(int i = 0; i < p.length; i++) { String t = "["; for(int j = 0; j < p[i].length; j++) { t += p[i][j] + ","; } t = t.substring(0, t.length() - 1) + "]"; s += t + ","; } s = s.substring(0, s.length() - 1) + "]"; return s; } }
db25ec8ad954d252c158bd54776f2970547d4ed4
3c334f52843aae72e66b7c106c0d53600cb3d89d
/LAB6.3/src/com/cg/eis/exception/EmployeeException.java
017391c8458403ebe61bbb0d270931a429743196
[]
no_license
RajatNagil/abc117
830fc8f63ea2997f554cab09287d4726ab08498d
7cffc9e19b214c3e37aff5504c4b9dc1efa5b160
refs/heads/master
2020-04-22T21:05:36.498618
2019-02-14T09:16:28
2019-02-14T09:16:28
170,662,194
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package com.cg.eis.exception; public class EmployeeException extends Exception{ public EmployeeException(){ System.out.println("Salary must be more than 3000 INR"); System.exit(0); } }
8d1fc7bb9c0ab859153d6a2da7b5682a30d32c6e
db4ea26fc513990a15ecb9ed67f770ec2a5e2044
/src/CapaPresentacion/PantallaRegisConsulta.java
c1094709deff9d527772b316cf4af391f7aa00eb
[]
no_license
josuePerez/EjemploClinica
a2eb6152735188cf2dc652325f825ebcb13da67d
393a8d3f806a709bfcdfaab31963728b0562e03f
refs/heads/master
2021-01-01T16:14:02.118262
2014-08-27T04:32:13
2014-08-27T04:32:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,287
java
package CapaPresentacion; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextArea; import java.awt.Color; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import CapaLogica.Gestor; import java.awt.SystemColor; public class PantallaRegisConsulta extends JFrame { private JPanel contentPane; private JTextField txtIdVeterinario; private JTextField txtIdExpediente; private JTextField txtFechaConsul; Gestor gestor; private JTextArea txtDescrip; private JTextField txtIdConsulta; private JTextField txtPeso; private JTextField txtAltura; private JTextField txtLongEspal; private JTextField txtLongPecho; private JTextField txtDiaCuello; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PantallaRegisConsulta frame = new PantallaRegisConsulta(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public PantallaRegisConsulta() { setTitle("Registrar Consulta"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 670); contentPane = new JPanel(); contentPane.setBackground(Color.GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTextArea txtrIdVeterinario = new JTextArea(); txtrIdVeterinario.setBackground(Color.GRAY); txtrIdVeterinario.setEditable(false); txtrIdVeterinario.setText("ID Veterinario"); txtrIdVeterinario.setBounds(10, 11, 123, 20); contentPane.add(txtrIdVeterinario); txtIdVeterinario = new JTextField(); txtIdVeterinario.setBounds(218, 12, 172, 20); contentPane.add(txtIdVeterinario); txtIdVeterinario.setColumns(10); JTextArea txtrIdExpediente = new JTextArea(); txtrIdExpediente.setBackground(Color.GRAY); txtrIdExpediente.setEditable(false); txtrIdExpediente.setText("ID Expediente"); txtrIdExpediente.setBounds(10, 55, 123, 20); contentPane.add(txtrIdExpediente); txtIdExpediente = new JTextField(); txtIdExpediente.setBounds(218, 56, 172, 20); contentPane.add(txtIdExpediente); txtIdExpediente.setColumns(10); JTextArea txtrFechaConsulta = new JTextArea(); txtrFechaConsulta.setBackground(Color.GRAY); txtrFechaConsulta.setEditable(false); txtrFechaConsulta.setText("Fecha Consulta"); txtrFechaConsulta.setBounds(10, 125, 123, 20); contentPane.add(txtrFechaConsulta); txtFechaConsul = new JTextField(); txtFechaConsul.setBounds(218, 126, 172, 20); contentPane.add(txtFechaConsul); txtFechaConsul.setColumns(10); JTextArea txtrDescripcion = new JTextArea(); txtrDescripcion.setBackground(Color.GRAY); txtrDescripcion.setEditable(false); txtrDescripcion.setText("Descripcion"); txtrDescripcion.setBounds(10, 338, 123, 20); contentPane.add(txtrDescripcion); JButton btnRegistrar = new JButton("Registrar"); btnRegistrar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnRegistrar_mouseClicked(e); } }); btnRegistrar.setFont(new Font("Tahoma", Font.PLAIN, 21)); btnRegistrar.setBounds(10, 570, 172, 62); contentPane.add(btnRegistrar); txtDescrip = new JTextArea(); txtDescrip.setBounds(10, 392, 422, 123); contentPane.add(txtDescrip); JButton btnVolver = new JButton("Volver"); btnVolver.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { btnVolver_mouseClicked(e); } }); btnVolver.setFont(new Font("Tahoma", Font.PLAIN, 21)); btnVolver.setBounds(268, 570, 111, 62); contentPane.add(btnVolver); JTextArea txtrIdConsulta = new JTextArea(); txtrIdConsulta.setEditable(false); txtrIdConsulta.setBackground(Color.GRAY); txtrIdConsulta.setText("ID Consulta"); txtrIdConsulta.setBounds(10, 96, 111, 20); contentPane.add(txtrIdConsulta); txtIdConsulta = new JTextField(); txtIdConsulta.setBounds(218, 95, 172, 20); contentPane.add(txtIdConsulta); txtIdConsulta.setColumns(10); JTextArea txtrPeso = new JTextArea(); txtrPeso.setBackground(Color.GRAY); txtrPeso.setText("Peso"); txtrPeso.setBounds(10, 156, 59, 20); contentPane.add(txtrPeso); txtPeso = new JTextField(); txtPeso.setBounds(218, 157, 86, 20); contentPane.add(txtPeso); txtPeso.setColumns(10); JTextArea txtrAltura = new JTextArea(); txtrAltura.setBackground(Color.GRAY); txtrAltura.setText("Altura"); txtrAltura.setBounds(10, 187, 59, 20); contentPane.add(txtrAltura); txtAltura = new JTextField(); txtAltura.setBounds(218, 188, 86, 20); contentPane.add(txtAltura); txtAltura.setColumns(10); JTextArea txtrLongitudDelPecho = new JTextArea(); txtrLongitudDelPecho.setBackground(Color.GRAY); txtrLongitudDelPecho.setText("Longitud de la espalda"); txtrLongitudDelPecho.setBounds(10, 218, 178, 20); contentPane.add(txtrLongitudDelPecho); txtLongEspal = new JTextField(); txtLongEspal.setBounds(218, 219, 123, 20); contentPane.add(txtLongEspal); txtLongEspal.setColumns(10); JTextArea txtrLongitudDelPecho_1 = new JTextArea(); txtrLongitudDelPecho_1.setBackground(Color.GRAY); txtrLongitudDelPecho_1.setText("Longitud del pecho"); txtrLongitudDelPecho_1.setBounds(10, 249, 146, 20); contentPane.add(txtrLongitudDelPecho_1); txtLongPecho = new JTextField(); txtLongPecho.setBounds(218, 250, 86, 20); contentPane.add(txtLongPecho); txtLongPecho.setColumns(10); JTextArea txtrDiametroDelCuello = new JTextArea(); txtrDiametroDelCuello.setBackground(Color.GRAY); txtrDiametroDelCuello.setText("Diametro del cuello"); txtrDiametroDelCuello.setBounds(10, 280, 154, 20); contentPane.add(txtrDiametroDelCuello); txtDiaCuello = new JTextField(); txtDiaCuello.setBounds(218, 281, 86, 20); contentPane.add(txtDiaCuello); txtDiaCuello.setColumns(10); gestor = new Gestor(); } /** * * */ public void btnRegistrar_mouseClicked(ActionEvent e){ String idConsulta, idVeterinario, idExpediente, fechaConsul, descrip, peso, longEspal, longPecho, diaCuello, altura; try { idConsulta = txtIdConsulta.getText(); idVeterinario = txtIdVeterinario.getText(); idExpediente = txtIdExpediente.getText(); fechaConsul = txtFechaConsul.getText(); descrip = txtDescrip.getText(); peso = txtPeso.getText(); altura = txtAltura.getText(); longEspal = txtLongEspal.getText(); longPecho = txtLongPecho.getText(); diaCuello = txtDiaCuello.getText(); gestor.registrarConsulta(idConsulta, idVeterinario, fechaConsul, descrip, idExpediente, peso,altura, longEspal, longPecho,diaCuello ); JOptionPane.showMessageDialog(this,"La consulta ha sido agregada","Informacion",JOptionPane.INFORMATION_MESSAGE); } catch (Exception ex) { JOptionPane.showMessageDialog(this,(String) ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } } /** * * */ public void btnVolver_mouseClicked(ActionEvent e){ this.setVisible(false); } }
cbccd614d3884b5ac8469534c43d27754c4a5240
67f30e30ad398c018d3f7c5da22288f1a53e8712
/src/chapter11/ConOverloading.java
288ee4d9e4738eed6ce9264a6645650fff96f7e5
[]
no_license
n3316202/java_hello
822a798f1ab59dd0406bf225bd0bed8de20706ce
aba935a33a887d4ba4bf6b528e63450eda4eb657
refs/heads/master
2022-11-02T17:04:36.978673
2022-11-02T07:12:12
2022-11-02T07:12:12
264,208,960
0
0
null
null
null
null
UHC
Java
false
false
992
java
package chapter11; class Person { private int regiNum; // 주민등록 번호 private int passNum; // 여권 번호 Person(int rnum, int pnum) { regiNum = rnum; passNum = pnum; } Person(int rnum) { regiNum = rnum; passNum = 0; } void showPersonalInfo() { System.out.println("주민등록 번호: " + regiNum); if(passNum != 0) System.out.println("여권 번호: " + passNum + '\n'); else System.out.println("여권을 가지고 있지 않습니다. \n"); } } class ConOverloading { public static void main(String[] args) { // 여권 있는 사람의 정보를 담은 인스턴스 생성 Person jung = new Person(335577, 112233); // 여권 없는 사람의 정보를 담은 인스턴스 생성 Person hong = new Person(775544); jung.showPersonalInfo(); hong.showPersonalInfo(); } }
56b5a42ae9e2c583f9b444888b46826a68c2f8f1
a911f926261b82ec8a2ade2d0af1a973280ceab6
/qipai_guandan/src/main/java/com/anbang/qipai/guandan/cqrs/c/domain/PukeGameValueObject.java
a2ac1d4cf4f050d2e03a04fb4f15c346c40e803e
[]
no_license
791837060/qipai_huainanmajiang
31325550c9db1fcb139c6f5a89d84f7deac0e3a2
b4f17b26484bbe2840a0852156117faee9996bbb
refs/heads/master
2023-06-26T22:31:40.822705
2021-07-30T07:20:49
2021-07-30T07:20:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,141
java
package com.anbang.qipai.guandan.cqrs.c.domain; import com.anbang.qipai.guandan.cqrs.c.domain.state.PukeGamePlayerChaodiState; import com.dml.mpgame.game.extend.fpmpv.FixedPlayersMultipanAndVotetofinishGameValueObject; import com.dml.shuangkou.ju.JuResult; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PukeGameValueObject extends FixedPlayersMultipanAndVotetofinishGameValueObject { private int panshu; private int renshu; private OptionalPlay optionalPlay; private int powerLimit; private double difen; private Map<String, Double> playeTotalScoreMap = new HashMap<>(); private Map<String, Integer> playeGongxianfenMap = new HashMap<>(); private Map<String, Integer> playerGongxianfenDetalMap = new HashMap<>(); private Map<String, GuandanGongxianFen> playeTotalGongxianfenMap = new HashMap<>(); private Map<String, Integer> playerMaxXianshuMap = new HashMap<>(); private Map<String, Integer> playerOtherMaxXianshuMap = new HashMap<>(); private Map<String, PukeGamePlayerChaodiState> playerChaodiStateMap = new HashMap<>(); private Map<String, Integer> playerMingciMap = new HashMap<>(); private List<String> chaodiPlayerIdList = new ArrayList<>(); private JuResult juResult; public PukeGameValueObject(PukeGame pukeGame) { super(pukeGame); panshu = pukeGame.getPanshu(); renshu = pukeGame.getRenshu(); optionalPlay=pukeGame.getOptionalPlay(); difen=pukeGame.getDifen(); playeTotalScoreMap.putAll(pukeGame.getPlayerTotalScoreMap()); playeGongxianfenMap.putAll(pukeGame.getPlayerGongxianfenMap()); playerGongxianfenDetalMap.putAll(pukeGame.getPlayerGongxianfenDetalMap()); playerChaodiStateMap.putAll(pukeGame.getPlayerChaodiStateMap()); playeTotalGongxianfenMap.putAll(pukeGame.getPlayerTotalGongxianfenMap()); playerMaxXianshuMap.putAll(pukeGame.getPlayerMaxXianshuMap()); playerOtherMaxXianshuMap.putAll(pukeGame.getPlayerOtherMaxXianshuMap()); chaodiPlayerIdList = new ArrayList<>(pukeGame.getChaodiPlayerIdList()); playerMingciMap.putAll(pukeGame.getPlayerMingciMap()); if (pukeGame.getJu() != null) { juResult = pukeGame.getJu().getJuResult(); } powerLimit = pukeGame.getPowerLimit(); } public int getPanshu() { return panshu; } public void setPanshu(int panshu) { this.panshu = panshu; } public int getRenshu() { return renshu; } public void setRenshu(int renshu) { this.renshu = renshu; } public OptionalPlay getOptionalPlay() { return optionalPlay; } public void setOptionalPlay(OptionalPlay optionalPlay) { this.optionalPlay = optionalPlay; } public double getDifen() { return difen; } public void setDifen(double difen) { this.difen = difen; } public Map<String, Double> getPlayeTotalScoreMap() { return playeTotalScoreMap; } public void setPlayeTotalScoreMap(Map<String, Double> playeTotalScoreMap) { this.playeTotalScoreMap = playeTotalScoreMap; } public Map<String, Integer> getPlayeGongxianfenMap() { return playeGongxianfenMap; } public void setPlayeGongxianfenMap(Map<String, Integer> playeGongxianfenMap) { this.playeGongxianfenMap = playeGongxianfenMap; } public Map<String, Integer> getPlayerGongxianfenDetalMap() { return playerGongxianfenDetalMap; } public void setPlayerGongxianfenDetalMap(Map<String, Integer> playerGongxianfenDetalMap) { this.playerGongxianfenDetalMap = playerGongxianfenDetalMap; } public Map<String, GuandanGongxianFen> getPlayeTotalGongxianfenMap() { return playeTotalGongxianfenMap; } public void setPlayeTotalGongxianfenMap(Map<String, GuandanGongxianFen> playeTotalGongxianfenMap) { this.playeTotalGongxianfenMap = playeTotalGongxianfenMap; } public Map<String, Integer> getPlayerMaxXianshuMap() { return playerMaxXianshuMap; } public void setPlayerMaxXianshuMap(Map<String, Integer> playerMaxXianshuMap) { this.playerMaxXianshuMap = playerMaxXianshuMap; } public Map<String, Integer> getPlayerOtherMaxXianshuMap() { return playerOtherMaxXianshuMap; } public void setPlayerOtherMaxXianshuMap(Map<String, Integer> playerOtherMaxXianshuMap) { this.playerOtherMaxXianshuMap = playerOtherMaxXianshuMap; } public Map<String, PukeGamePlayerChaodiState> getPlayerChaodiStateMap() { return playerChaodiStateMap; } public void setPlayerChaodiStateMap(Map<String, PukeGamePlayerChaodiState> playerChaodiStateMap) { this.playerChaodiStateMap = playerChaodiStateMap; } public Map<String, Integer> getPlayerMingciMap() { return playerMingciMap; } public void setPlayerMingciMap(Map<String, Integer> playerMingciMap) { this.playerMingciMap = playerMingciMap; } public List<String> getChaodiPlayerIdList() { return chaodiPlayerIdList; } public void setChaodiPlayerIdList(List<String> chaodiPlayerIdList) { this.chaodiPlayerIdList = chaodiPlayerIdList; } public JuResult getJuResult() { return juResult; } public void setJuResult(JuResult juResult) { this.juResult = juResult; } public int getPowerLimit() { return powerLimit; } public void setPowerLimit(int powerLimit) { this.powerLimit = powerLimit; } }
eb88b02fbcc83e3854fea8ab342b0723f0ca2685
183931eedd8ed7ff685e22cb055f86f12a54d707
/test/miscCode/src/main/java/tree/graph/Node.java
bdafe228aee3b19139140624c41a2e41f0db5b40
[]
no_license
cynepCTAPuk/headFirstJava
94a87be8f6958ab373cd1640a5bdb9c3cc3bf166
7cb45f6e2336bbc78852d297ad3474fd491e5870
refs/heads/master
2023-08-16T06:51:14.206516
2023-08-08T16:44:11
2023-08-08T16:44:11
154,661,091
0
1
null
2023-01-06T21:32:31
2018-10-25T11:40:54
Java
UTF-8
Java
false
false
549
java
package tree.graph; import java.util.List; public class Node { private int number; private List<Node> edges; public Node(int node) { this.number = node; } public void setEdges(List<Node> edges) { this.edges = edges; } @Override public String toString() { String ed = ""; // for (Node n : edges) ed += n.number; int size = 0; if (edges != null) size = edges.size(); return "\n\tNode{" + "node=" + number + ", qtyEdge=" + size + '}'; } }
ca9dfdd439d1f0ae48d20f698d16d486eaa8ec65
c49681fff1944fc397f2b90da608b9a13488c486
/app/src/androidTest/java/pl/bialorucki/popularmovies/ExampleInstrumentedTest.java
5787cc237eefec2191bf55a5d77d53be0b12f231
[]
no_license
mbialorucki/PopularMovies
b338f1f1446a5d00c21defc896bb2961db23dfc3
f69f64a14e1c0e87756843a6d4eb34deb4097b5c
refs/heads/master
2021-01-25T00:17:43.892219
2018-04-26T11:25:03
2018-04-26T11:25:03
123,291,869
0
0
null
null
null
null
UTF-8
Java
false
false
755
java
package pl.bialorucki.popularmovies; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("pl.bialorucki.popularmovies", appContext.getPackageName()); } }
0e1e7bcbb40fb97bd5141530b2cc4c115c412173
3d6f2614e6d792eb50203a039f0cede7389b59b4
/app/src/androidTest/java/rod/bailey/trafficatnsw/instrument/dagger/TestComponent.java
d4deb1fc50513ab67ee2761b86088b787bdaecf5
[]
no_license
replicant1/TrafficAtNSW
e1495a3cbaf98329686d7a07459e96c60b44eda0
9b6e49d1ad40c805d1a5b2af8adb537842ddb723
refs/heads/master
2021-01-11T06:22:04.582267
2017-08-24T11:24:45
2017-08-24T11:24:45
69,955,089
0
0
null
2017-08-22T04:39:03
2016-10-04T10:33:14
Kotlin
UTF-8
Java
false
false
610
java
package rod.bailey.trafficatnsw.instrument.dagger; import javax.inject.Singleton; import dagger.Component; import rod.bailey.trafficatnsw.instrument.service.TestDataService; import rod.bailey.trafficatnsw.instrument.service.TestDataServiceHolder; import rod.bailey.trafficatnsw.dagger.AppComponent; import rod.bailey.trafficatnsw.dagger.AppModule; /** * Created by rodbailey on 8/8/17. */ @Singleton @Component(modules = {AppModule.class, TestDataServiceModule.class}) public interface TestComponent extends AppComponent { void inject(TestDataService service); void inject(TestDataServiceHolder obj); }
3d6e2a48b68af6381c61a0345244d7239d87837b
cf86ed3b5d5b0baa559a54c5e4f7d815b516ec63
/src/com/srts/controlPanel/dao/impl/PersonPasswordChangeDaoImpl.java
5d7bae91c88e03e93b18eecf6670ae6564b2ea17
[]
no_license
zhousning/srts
cc4380a9b55e1a9e2d96e92fa49834bdefb4bf2c
8902cfc05e2256694eb566e6698e1fdad119e6e9
refs/heads/master
2021-01-12T01:37:20.635038
2017-01-09T08:51:05
2017-01-09T08:51:05
78,410,722
0
0
null
null
null
null
UTF-8
Java
false
false
949
java
package com.srts.controlPanel.dao.impl; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.srts.controlPanel.dao.PersonPasswordChangeDao; import com.srts.system.domain.Sys_User; @Repository @Transactional public class PersonPasswordChangeDaoImpl implements PersonPasswordChangeDao { @Resource private SessionFactory sessionFactory; public String updateUserPassword(Sys_User usr, String password) { long UsrId=usr.getId(); String resString="fail"; int res=sessionFactory.getCurrentSession().createSQLQuery( "update srts_sys_user set srts_sys_user.password=:password " + "where srts_sys_user.id=:UsrId") .setString("password", password).setLong("UsrId", UsrId).executeUpdate(); if(res==1) { resString="success"; } return resString; } }
ded4a4ba08bb5bfa227d68eae12a1da7aee669b1
82e110149c60b5d7214ed70263519140539ee604
/Unit_5/Assignment_5/Q04_EmailSMTP/src/EmailSMTP/SendEmail.java
23e1fa2e3a000e67cb2c3d6c2bc0d94b2ad5307a
[]
no_license
DipendraDLS/Java_Assignment
79f027652682f6ae1868b3996d60ca1964bc6317
11f9668209a46a198bfb699e380004d94d75a9e4
refs/heads/master
2022-11-13T00:55:30.959711
2020-07-05T12:57:45
2020-07-05T12:57:45
266,341,359
2
2
null
null
null
null
UTF-8
Java
false
false
2,018
java
package EmailSMTP; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.*; public class SendEmail { public static void main(String[] args) throws IOException { Email email = new Email( "[email protected]", "[email protected]", "Test email." ); email.send(); } } class Email { private Scanner in = null; private PrintWriter out = null; private final String SMTP_SERVER = "smtp.wlink.com.np"; private final int SMTP_PORT = 25; private String from = null; private String to = null; private String message = null; public Email(String from, String to, String message) { this.from = from; this.to = to; this.message = message; } private void send(String s) throws IOException { System.out.println(">> " + s); out.print(s.replaceAll("\n", "\r\n")); out.print("\r\n"); out.flush(); } private void receive() throws IOException { String line = in.nextLine(); System.out.println(" " + line); } public void send() throws IOException { Socket socket = new Socket(SMTP_SERVER, SMTP_PORT); in = new Scanner(socket.getInputStream()); out = new PrintWriter(socket.getOutputStream(), true); String hostName = InetAddress.getLocalHost().getHostName(); receive(); send("HELO " + hostName); receive(); send("MAIL FROM: <" + from + ">"); receive(); send("RCPT TO: <" + to + ">"); receive(); send("DATA"); receive(); send(message); send("."); receive(); socket.close(); } }
976f476d5a15557d22e6f649bc2b8b912406641f
831a3bc998be17f447c90a1593fd1b537b74d9a7
/e3-search-web/target/tomcat/work/Tomcat/localhost/_/org/apache/jsp/WEB_002dINF/jsp/commons/header_jsp.java
12000164d63ee67145c97b80149021ca88b68d97
[]
no_license
zcn0203/pigpigMall
f4961022f165b2b972309d6788fa2d8387c484ba
e2a9c429feae70dcf581d302fba58df34ce0e0c1
refs/heads/master
2020-04-20T19:03:48.601962
2019-02-05T15:14:17
2019-02-05T15:14:18
169,039,024
0
0
null
null
null
null
UTF-8
Java
false
false
6,932
java
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.47 * Generated at: 2018-10-19 08:53:11 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.jsp.commons; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class header_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!--shortcut start-->\r\n"); org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "shortcut.jsp", out, false); out.write("\r\n"); out.write("<!--shortcut end-->\r\n"); out.write("<div id=\"header\">\r\n"); out.write(" <div class=\"header_inner\">\r\n"); out.write(" <div class=\"logo\">\r\n"); out.write("\t\t\t<a name=\"sfbest_hp_hp_head_logo\" href=\"http://www.e3mall.cn\" class=\"trackref logoleft\">\r\n"); out.write("\t\t</a>\r\n"); out.write("\t\t\t<div class=\"logo-text\">\r\n"); out.write("\t\t\t\t<img src=\"/images/html/logo_word.jpg\">\r\n"); out.write("\t\t\t</div>\r\n"); out.write("\t\t</div>\r\n"); out.write(" <div class=\"index_promo\"></div>\r\n"); out.write(" <div class=\"search\">\r\n"); out.write(" <form action=\"http://localhost:8085/search.html\" id=\"searchForm\" name=\"query\" method=\"GET\">\r\n"); out.write(" <input type=\"text\" class=\"text keyword ac_input\" name=\"keyword\" id=\"keyword\" value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${query }", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); out.write("\" style=\"color: rgb(153, 153, 153);\" onkeydown=\"javascript:if(event.keyCode==13) search_keys('searchForm');\" autocomplete=\"off\">\r\n"); out.write(" <input type=\"button\" value=\"\" class=\"submit\" onclick=\"search_keys('searchForm')\">\r\n"); out.write(" </form>\r\n"); out.write(" <div class=\"search_hot\"><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E5%A4%A7%E9%97%B8%E8%9F%B9#trackref=sfbest_hp_hp_head_Keywords1\">大闸蟹</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E7%9F%B3%E6%A6%B4#trackref=sfbest_hp_hp_head_Keywords2\">石榴</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E6%9D%BE%E8%8C%B8#trackref=sfbest_hp_hp_head_Keywords3\">松茸</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E7%89%9B%E6%8E%92#trackref=sfbest_hp_hp_head_Keywords4\">牛排</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E7%99%BD%E8%99%BE#trackref=sfbest_hp_hp_head_Keywords5\">白虾</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E5%85%A8%E8%84%82%E7%89%9B%E5%A5%B6#trackref=sfbest_hp_hp_head_Keywords6\">全脂牛奶</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E6%B4%8B%E6%B2%B3#trackref=sfbest_hp_hp_head_Keywords7\">洋河</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E7%BB%BF%E8%B1%86#trackref=sfbest_hp_hp_head_Keywords8\">绿豆</a><a target=\"_blank\" href=\"http://www.e3mall.cn/productlist/search?inputBox=1&amp;keyword=%E4%B8%80%E5%93%81%E7%8E%89#trackref=sfbest_hp_hp_head_Keywords9\">一品玉</a></div>\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"shopingcar\" id=\"topCart\">\r\n"); out.write(" <s class=\"setCart\"></s><a href=\"http://cart.e3mall.cn\" class=\"t\" rel=\"nofollow\">我的购物车</a><b id=\"cartNum\">0</b>\r\n"); out.write(" <span class=\"outline\"></span>\r\n"); out.write(" <span class=\"blank\"></span>\r\n"); out.write(" <div id=\"cart_lists\">\r\n"); out.write(" <!--cartContent--> \r\n"); out.write(" <div class=\"clear\"></div>\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write(" <script type=\"text/javascript\">\r\n"); out.write(" \tfunction search_keys(formName){\r\n"); out.write("\t $('#'+formName).submit();\r\n"); out.write("\t}\r\n"); out.write(" </script>\r\n"); out.write("</div>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
98b2dabc8f377a2e499fb39f549a6376a2e83ad3
58803f70557a11c0aed300806497a916b96ea18a
/module/urn.org.netkernelroc.nk4um.db/src/org/netkernelroc/nk4um/db/forumGroup/ListAccessor.java
5032988f6a943284095a6741e96ead17aa7c6438
[]
no_license
pjr1060/nk4um
085393fc77e7ddc28d9a767ccccc7176c72c41e5
60d2456d8c088527cff873619cccd84f55212d86
refs/heads/master
2021-01-17T21:33:53.878600
2011-06-01T19:11:07
2011-06-01T19:11:07
1,751,357
0
0
null
null
null
null
UTF-8
Java
false
false
2,152
java
/* * Copyright (C) 2010-2011 by Chris Cormack * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.netkernelroc.nk4um.db.forumGroup; import org.netkernel.layer0.nkf.INKFRequestContext; import org.netkernel.layer0.nkf.INKFResponse; import org.netkernel.layer0.representation.IHDSNode; import org.netkernelroc.mod.layer2.ArgByValue; import org.netkernelroc.mod.layer2.DatabaseAccessorImpl; import org.netkernelroc.mod.layer2.DatabaseUtil; public class ListAccessor extends DatabaseAccessorImpl { @Override public void onSource(INKFRequestContext aContext, DatabaseUtil util) throws Exception { String sql= "SELECT id\n" + "FROM nk4um_forum_group\n" + "ORDER BY display_order,\n" + " id;"; INKFResponse resp= util.issueSourceRequestAsResponse("active:sqlPSQuery", IHDSNode.class, new ArgByValue("operand", sql)); resp.setHeader("no-cache", null); util.attachGoldenThread("nk4um:all", "nk4um:forumGroup"); } }
98e8419abcf872d29342afe0545cdc2913e5164f
f7dbe2b1d49ae90c1079a681b883bd1b73f53c84
/pljava-examples/src/main/java/org/postgresql/pljava/example/RandomInts.java
08ae02fe913e6480982560b25b9d3b967882f209
[]
no_license
sourcewave/pljava
fbb0b0b2def1c6b80838c93670f0373523250430
fc4b78eb2465ff11470676f12c93b046660e393b
refs/heads/master
2021-01-15T18:50:27.553480
2013-01-18T11:45:05
2013-01-18T11:45:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,084
java
/* * Copyright (c) 2004 TADA AB - Taby Sweden * Distributed under the terms shown in the file COPYRIGHT * found in the root directory of this distribution or at * http://eng.tada.se/osprojects/COPYRIGHT.html */ package org.postgresql.pljava.example; import java.sql.SQLException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Random; public class RandomInts implements Iterator { private final int m_rowCount; private final Random m_random; private int m_currentRow; public static Iterator createIterator(int rowCount) throws SQLException { return new RandomInts(rowCount); } public RandomInts(int rowCount) throws SQLException { m_rowCount = rowCount; m_random = new Random(System.currentTimeMillis()); } public boolean hasNext() { return m_currentRow < m_rowCount; } public Object next() { if(m_currentRow < m_rowCount) { ++m_currentRow; return new Integer(m_random.nextInt()); } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } }
6a81982a4d8acc0afc956b0c37ec0019136a1334
fee60a54bb88f3c22698eb6684295e43a198b02f
/Small-Financial/src/Auditoria/MainThread.java
c209c145e1d7e83c1d1cd85b3c3111536d4f094f
[]
no_license
Joao7747/Small-Financial
fdb055e1ae057c28a03cd47a97d355cfe0a5d492
26ebdd37cad0ad9bdcd59cdeab8fe5bad826088a
refs/heads/main
2023-05-07T21:05:02.427931
2021-05-28T22:49:47
2021-05-28T22:49:47
349,577,084
0
0
null
2021-05-28T22:38:06
2021-03-19T23:08:48
Java
UTF-8
Java
false
false
2,469
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Auditoria; import DAO.DAOUsuario; import java.time.Instant; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Caio */ public class MainThread { private static MainThread instancia; public String user; public static MainThread getInstance() { if (instancia == null) { instancia = new MainThread(); } return instancia; } public void StartThread(String acao) throws InterruptedException{ GerenciadorAuditoria.getInstancia().ativar(); try{ String mensagem = String.format("%s - Usuario " +user+ " clicou em %s\n\n", Instant.now().toString(),acao); System.out.printf(mensagem); GerenciadorAuditoria.getInstancia().adicionaMsgAuditoria(mensagem); } catch (Exception ex) { Logger.getLogger(MainThread.class.getName()).log(Level.SEVERE, null, ex); } finally { GerenciadorAuditoria.getInstancia().desativar(); } } // public String tela = "vazio"; // public String usuario; // @Override // public void run(){ // // System.out.printf("%s - Início da auditoria\n", Instant.now().toString()); // GerenciadorAuditoria.getInstancia().ativar(); // try { // for (int i=0;i<10;i++){ // Random rand = new Random(); //instance of random class // int upperbound = 10; // int proximoSleep = rand.nextInt(upperbound); // String msgRandomica = String.format("%s - Entreu na tela de " + tela + "- Com o usuario " + usuario + "\n", Instant.now().toString(),i+1); // System.out.printf(msgRandomica); // GerenciadorAuditoria.getInstancia().adicionaMsgAuditoria("Auditoria - "+msgRandomica); // Thread.sleep(proximoSleep); // } // Thread.sleep(15000); // } catch (InterruptedException ex) { // Logger.getLogger(MainThread.class.getName()).log(Level.SEVERE, null, ex); // } finally { // GerenciadorAuditoria.getInstancia().desativar(); // } // // System.out.printf("%s - Final da brincadeira\n", Instant.now().toString()); // } }
5ed469bfa535f2d38495a98d977687dfacdfc6b6
5cdd5aefbb7300a53e1139fa05f6d22a2b7591bf
/QuizZz/src/main/java/venkat/example/quizzz/controller/web/WebUserController.java
ca299f4d2e956afd743af241f1f52679ce17d0d2
[]
no_license
aranva2006/targetquizz
b8d78bfff0bdf04c515590db92ef04c56d4f9ba8
e3274da5d4b80cb4fadcf183d2159423b3196e08
refs/heads/master
2020-04-25T14:51:41.330158
2019-02-27T18:21:23
2019-02-27T18:21:23
172,856,723
0
0
null
null
null
null
UTF-8
Java
false
false
994
java
package venkat.example.quizzz.controller.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import venkat.example.quizzz.service.UserService; @Controller @RequestMapping("/user") public class WebUserController { @Autowired UserService userService; @RequestMapping(value = "/{user_id}/quizzes", method = RequestMethod.GET) @PreAuthorize("permitAll") public String getQuizzesForUser(@PathVariable Long user_id) { userService.find(user_id); // TODO: Unimplemented return "error"; } @RequestMapping(value = "/quizzes", method = RequestMethod.GET) @PreAuthorize("isAuthenticated()") public String getQuizzesForAuthenticatedUser() { return "myQuizzes"; } }
3ac22d9bb56e00fcbe82d213372310d85b9a7443
131ad8c57870b58a1aea368c8b2a437ae20e9263
/app/src/androidTest/java/com/example/cubelearner/ExampleInstrumentedTest.java
7dcee4af678cdc412231950f33e9880c5371fe8b
[]
no_license
LCoquet/Cube_Learner
56a1a196273102e3ccd64cd24c7cf30e28ad7263
d1f52ec5a7a14669505beeecb17414d9469a4f74
refs/heads/master
2023-02-08T09:40:06.335632
2021-01-02T15:25:39
2021-01-02T15:25:39
323,934,651
0
0
null
null
null
null
UTF-8
Java
false
false
760
java
package com.example.cubelearner; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.cubelearner", appContext.getPackageName()); } }
72a94467724ba39971c6564caee789f2732bb1e9
88bdf958fa8e456e7e4080637c1f12c1ef19e484
/W4D1/src/main/java/edu/miu/CustomTime.java
99d0d1227cb48aab3ba9ccc38ee1e546ad3b003a
[]
no_license
Ataklete/WAP
6542f2443303cb46dc17966aec81c1a6b7763d9d
4a84fdac835b249607313a8530a74f9cd740b77b
refs/heads/master
2022-12-29T14:00:41.165581
2020-10-14T01:11:34
2020-10-14T01:11:34
274,259,685
0
0
null
2020-10-13T23:32:57
2020-06-22T23:00:22
JavaScript
UTF-8
Java
false
false
967
java
package edu.miu; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; public class CustomTime extends SimpleTagSupport{ String foreColor; String size; public void doTag() throws JspException, IOException //render custom tag { JspWriter out = getJspContext().getOut(); Date dNow = new Date(); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); if (foreColor != null) out.write(String.format("<span style='color:%s; font-size: %s'>%s</span>", foreColor,size, ft.format(dNow))); else out.write(String.format("<span>%s</span>", size)); } //Need a setter for each attribute of custom tag public void setForeColor(String foreColor) { this.foreColor = foreColor; } public void setSize(String size) { this.size = size; } }
42fabac528e4f3d5cc8bc5fbd92f4be1e0d22b76
7ec84ee8fecbb481ca843567cb222ca0585b4883
/RevisaoAritimetica/Cilindro.java
5ede93053378eccf32f239e4f81b7f3175fa37ad
[]
no_license
CriptX-42/EstruturaDados
9f664511770b271dec5177c92ea4280966dbdde0
01ddbcb4de8477d5db93681942411cc52e397056
refs/heads/master
2021-01-24T08:12:16.224705
2018-02-26T13:33:33
2018-02-26T13:33:33
122,973,694
0
0
null
null
null
null
ISO-8859-1
Java
false
false
495
java
package RevisaoAritimetica; import javax.swing.JOptionPane; public class Cilindro { public static void main(String[] args) { int Raio = 0, Volume= 0, Altura = 0; double PI = 3.14; Raio = Integer.parseInt(JOptionPane.showInputDialog("Coloque o raio da circunferência: ")); Altura = Integer.parseInt(JOptionPane.showInputDialog("Coloque a altura do cilindro: ")); Volume = (int) (Altura * PI * Raio); JOptionPane.showMessageDialog(null, "O volume é : " + Volume); } }
6ba063a912b995f223158f39f27f0ff27d4b5c85
0a9038622022305d475e5913b19c7eeb08ea9883
/app/src/main/java/cn/edu/gdmec/android/boxuegu/splite/SQLiteHelper.java
284ff6a8bd14cdb2acfddf8662017b9f9c9ebee4
[]
no_license
cjybb5413/Boxuegu
85a42650f6c1f44ce29abc21e22c986ef2140b2a
6e6e427c2c6262aabb70594a910c2d567d4b1287
refs/heads/master
2020-03-09T16:07:42.151288
2018-05-08T07:37:55
2018-05-08T07:37:55
125,962,829
0
0
null
null
null
null
UTF-8
Java
false
false
1,598
java
package cn.edu.gdmec.android.boxuegu.splite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Asus on 2018/4/1. */ public class SQLiteHelper extends SQLiteOpenHelper{ private static final int DB_VERSION=2; public static String DB_NAME="bxg.db"; public static final String U_USERINFO="userinfo"; public static final String U_VIDEO_PLAY_LIST="videoplaylist"; public SQLiteHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + U_USERINFO + "(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "userName VARCHAR, " + "nickName VARCHAR, " + "sex VARCHAR, " + "signature VARCHAR, " + "qq VARCHAR" +")"); db.execSQL("CREATE TABLE IF NOT EXISTS " + U_VIDEO_PLAY_LIST + "(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "userName VARCHAR, " + "chapterId INT, " + "videoId INT, " + "videoPath VARCHAR," + "title VARCHAR," + "secondTitle VARCHAR" +")"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + U_USERINFO); db.execSQL("DROP TABLE IF EXISTS " + U_VIDEO_PLAY_LIST); onCreate(db); } }
a73b40c86fb7da5c0aedb7de2c765285b03cc0a9
f19eed20552464e067d79466f996323148045961
/src/LeeCode.java
b93534be6f2a6dea18f49d2d3bc9a9be136a69b0
[]
no_license
h424568209/12_17
c9a25227c7151ed62146bfbef8ec34880414e7d6
ba7cc7b1b2b300f1eeb10871d8272714293bfea2
refs/heads/master
2020-11-25T10:08:21.823525
2019-12-17T12:29:27
2019-12-17T12:29:27
228,612,029
0
0
null
null
null
null
UTF-8
Java
false
false
2,377
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class LeeCode { /** * * 给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置 * 注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。 * * * 直接的思路,判断每个子串是否符合,符合就把下标保存起来,最后返回即可 * @param s 字符串 * @param words 长度相同的单词的集合 * @return 所有能串联的起始位置 */ public List<Integer> findSubstring(String s, String[] words) { List<Integer> res = new ArrayList<>(); int wordNum = words.length; if(wordNum == 0){ return res; } int worldlen = words[0].length(); //保存所有的单词在map1 //单词--出现的次数对 HashMap<String ,Integer> allWords = new HashMap<>(); for(String w:words){ int val = allWords.getOrDefault(w,0); allWords.put(w,val+1); } //遍历所有子串 for(int i = 0 ; i < s.length() -wordNum*worldlen+1; i++){ HashMap<String ,Integer> haswords = new HashMap<>(); int num = 0; //判断该子串是否符合 while(num < wordNum){ String word = s.substring(i+num*worldlen,i+(num+1)*worldlen); //判断该单词在map1中 if(allWords.containsKey(word)){ int val = haswords.getOrDefault(word,0); haswords.put(word,val+1); //判断当前的单词的val和map1中的val if(haswords.get(word) > allWords.get(word)){ break; } }else{ break; } num++; } //判断是不是所有的单词都符合 if(num == wordNum) res.add(i); } return res; } public static void main(String[] args) { String s = "fooabbsfooabb"; String []words = {"foo","abb"}; LeeCode l = new LeeCode(); System.out.println(l.findSubstring(s,words)); } }
65e9d49c6934c3389317465546a36cbe3e307671
237e75786b89cc121f2c7ab16cd5cc42eed98a8a
/src/main/java/optional/OnlineClass.java
9e81d0fa470946621241af05103c66f636ece161
[]
no_license
dlehdrjs36/java-practice
00dd3b8aab9fdf3bc9d23b9522140dc657aca431
38edcd9361c2f43483fb022d4041b0de5577ada2
refs/heads/main
2023-07-02T16:12:18.826602
2021-08-02T14:16:22
2021-08-02T14:16:22
377,508,536
0
0
null
null
null
null
UTF-8
Java
false
false
2,466
java
package optional; import java.util.Optional; public class OnlineClass { private Integer id; private String title; private boolean closed; public Progress progress; /* 아래와 같이 인스턴스 필드 타입으로 Optional을 사용하는 것은 좋지 않다. 아래와 같은 형태는 설계의 문제이다. 상위 클래스, 하위 클래스로 쪼개거나 위임 방식을 사용하는 것이 좋다. */ // public Optional<Progress> progress; public OnlineClass(Integer id, String title, boolean closed) { this.id = id; this.title = title; this.closed = closed; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isClosed() { return closed; } public void setClosed(boolean closed) { this.closed = closed; } // public Progress getProgress() { // 에러는 필요한 상황에서만 던져야 하고 로직에서 사용하는 것은 좋지 않다. // if (this.getProgress() == null) { // throw new IllegalStateException(); // } // return progress; // } public Optional<Progress> getProgress() { return Optional.ofNullable(progress); /* 아래와 같이 Optional을 리턴하는 메소드에서 null을 리턴하면 안된다. null을 리턴하면 Optional을 받는 변수에서 관련 메소드 호출 시, 에러가 발생한다. */ // return null; } public void setProgress(Optional<Progress> progress) { /* Optional은 리턴 값으로만 사용하는 것이 권장된다. 위와 같이 매개변수에 Optional을 사용한 경우, 위험하다.(NullPointerException) 매개변수가 null로 전달된 경우, 오히려 매개변수에 Optional을 사용함으로서 처리가 더 복잡해질 수 있다.(추가적인 null 비교 조건 필요) 비교 조건을 추가하지 않는다면, 메소드 호출 시, 매개변수가 null일 경우에도 progress가 null로 설정되고 결과적으로 에러가 발생한다. */ if (progress != null) { progress.ifPresent((p) -> this.progress = p); } } }
3fa291c2adb3d8886c8afb6bf9eeceae7a5c0742
6e63a018c1e02b61a2b58ae56e93ae4805547122
/src/test/java/seedu/address/logic/commands/staff/DeleteStaffCommandTest.java
0399f99e94e603617492dc541ff5cb35e72d1159
[ "MIT" ]
permissive
zj-cs2103/main
d710c53867b76f1e935da100645fbefca0522a37
eb2b2b2af8f6f913b75b6a747b30d05799571a9b
refs/heads/master
2020-04-23T06:11:52.293342
2019-04-15T14:19:11
2019-04-15T14:19:11
170,965,690
0
0
NOASSERTION
2019-02-16T05:16:14
2019-02-16T05:16:13
null
UTF-8
Java
false
false
8,359
java
package seedu.address.logic.commands.staff; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.logic.commands.CommandTestUtil.showStaffAtIndex; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST; import static seedu.address.testutil.TypicalIndexes.INDEX_SECOND; import static seedu.address.testutil.TypicalStaff.getTypicalAddressBook; import org.junit.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.RedoCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.person.staff.Staff; /** * Contains integration tests (interaction with the Model, UndoCommand and RedoCommand) and unit tests for * {@code DeleteStaffCommand}. */ public class DeleteStaffCommandTest { private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); private CommandHistory commandHistory = new CommandHistory(); @Test public void execute_validIndexUnfilteredList_success() { Staff staffToDelete = model.getFilteredStaffList().get(INDEX_FIRST.getZeroBased()); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(INDEX_FIRST); String expectedMessage = String.format(DeleteStaffCommand.MESSAGE_DELETE_STAFF_SUCCESS, staffToDelete); ModelManager expectedModel = new ModelManager(model.getRestaurantBook(), new UserPrefs()); expectedModel.deleteStaff(staffToDelete); expectedModel.commitRestaurantBook(); assertCommandSuccess(deleteStaffCommand, model, commandHistory, expectedMessage, expectedModel); } @Test public void execute_invalidIndexUnfilteredList_throwsCommandException() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredStaffList().size() + 1); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(outOfBoundIndex); assertCommandFailure(deleteStaffCommand, model, commandHistory, Messages.MESSAGE_INVALID_STAFF_DISPLAYED_INDEX); } @Test public void execute_validIndexFilteredList_success() { showStaffAtIndex(model, INDEX_FIRST); Staff staffToDelete = model.getFilteredStaffList().get(INDEX_FIRST.getZeroBased()); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(INDEX_FIRST); String expectedMessage = String.format(DeleteStaffCommand.MESSAGE_DELETE_STAFF_SUCCESS, staffToDelete); Model expectedModel = new ModelManager(model.getRestaurantBook(), new UserPrefs()); expectedModel.deleteStaff(staffToDelete); expectedModel.commitRestaurantBook(); showNoStaff(expectedModel); assertCommandSuccess(deleteStaffCommand, model, commandHistory, expectedMessage, expectedModel); } @Test public void execute_invalidIndexFilteredList_throwsCommandException() { showStaffAtIndex(model, INDEX_FIRST); Index outOfBoundIndex = INDEX_SECOND; // ensures that outOfBoundIndex is still in bounds of address book list assertTrue(outOfBoundIndex.getZeroBased() < model.getRestaurantBook().getStaffList().size()); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(outOfBoundIndex); assertCommandFailure(deleteStaffCommand, model, commandHistory, Messages.MESSAGE_INVALID_STAFF_DISPLAYED_INDEX); } @Test public void executeUndoRedo_validIndexUnfilteredList_success() throws Exception { Staff staffToDelete = model.getFilteredStaffList().get(INDEX_FIRST.getZeroBased()); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(INDEX_FIRST); Model expectedModel = new ModelManager(model.getRestaurantBook(), new UserPrefs()); expectedModel.deleteStaff(staffToDelete); expectedModel.commitRestaurantBook(); // delete -> first staff deleted deleteStaffCommand.execute(model, commandHistory); // undo -> reverts addressbook back to previous state and filtered staff list to show all staffs expectedModel.undoRestaurantBook(); assertCommandSuccess(new UndoCommand(), model, commandHistory, UndoCommand.MESSAGE_SUCCESS, expectedModel); // redo -> same first staff deleted again expectedModel.redoRestaurantBook(); assertCommandSuccess(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_SUCCESS, expectedModel); } @Test public void executeUndoRedo_invalidIndexUnfilteredList_failure() { Index outOfBoundIndex = Index.fromOneBased(model.getFilteredStaffList().size() + 1); DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(outOfBoundIndex); // execution failed -> address book state not added into model assertCommandFailure(deleteStaffCommand, model, commandHistory, Messages.MESSAGE_INVALID_STAFF_DISPLAYED_INDEX); // single address book state in model -> undoCommand and redoCommand fail assertCommandFailure(new UndoCommand(), model, commandHistory, UndoCommand.MESSAGE_FAILURE); assertCommandFailure(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_FAILURE); } /** * 1. Deletes a {@code Staff} from a filtered list. * 2. Undo the deletion. * 3. The unfiltered list should be shown now. Verify that the index of the previously deleted staff in the * unfiltered list is different from the index at the filtered list. * 4. Redo the deletion. This ensures {@code RedoCommand} deletes the staff object regardless of indexing. */ @Test public void executeUndoRedo_validIndexFilteredList_sameStaffDeleted() throws Exception { DeleteStaffCommand deleteStaffCommand = new DeleteStaffCommand(INDEX_FIRST); Model expectedModel = new ModelManager(model.getRestaurantBook(), new UserPrefs()); showStaffAtIndex(model, INDEX_SECOND); Staff staffToDelete = model.getFilteredStaffList().get(INDEX_FIRST.getZeroBased()); expectedModel.deleteStaff(staffToDelete); expectedModel.commitRestaurantBook(); // delete -> deletes second staff in unfiltered staff list / first staff in filtered staff list deleteStaffCommand.execute(model, commandHistory); // undo -> reverts addressbook back to previous state and filtered staff list to show all staffs expectedModel.undoRestaurantBook(); assertCommandSuccess(new UndoCommand(), model, commandHistory, UndoCommand.MESSAGE_SUCCESS, expectedModel); assertNotEquals(staffToDelete, model.getFilteredStaffList().get(INDEX_FIRST.getZeroBased())); // redo -> deletes same second staff in unfiltered staff list expectedModel.redoRestaurantBook(); assertCommandSuccess(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_SUCCESS, expectedModel); } @Test public void equals() { DeleteStaffCommand deleteFirstCommand = new DeleteStaffCommand(INDEX_FIRST); DeleteStaffCommand deleteSecondCommand = new DeleteStaffCommand(INDEX_SECOND); // same object -> returns true assertTrue(deleteFirstCommand.equals(deleteFirstCommand)); // same values -> returns true DeleteStaffCommand deleteFirstCommandCopy = new DeleteStaffCommand(INDEX_FIRST); assertTrue(deleteFirstCommand.equals(deleteFirstCommandCopy)); // different types -> returns false assertFalse(deleteFirstCommand.equals(1)); // null -> returns false assertFalse(deleteFirstCommand.equals(null)); // different staff -> returns false assertFalse(deleteFirstCommand.equals(deleteSecondCommand)); } /** * Updates {@code model}'s filtered list to show no one. */ private void showNoStaff(Model model) { model.updateFilteredStaffList(p -> false); assertTrue(model.getFilteredStaffList().isEmpty()); } }
f23e99a061628ba28e169d13d7c983510f92a208
15f087e7f3b690723d360ee0453a6e6491de4d7c
/finalProject/src/main/java/kos/triple/project/service/soon/stayReservationServiceImpl.java
62e33fb3107de156c0dd42189c7987e45bd4ea09
[]
no_license
wnsfuf73/finalProject
bef519854f8f8ebe7836588873cf9a0adc5e3859
8aa727a775d66e65ce61edbd1444e64db6a54441
refs/heads/master
2021-09-06T21:57:58.291375
2018-02-12T08:01:20
2018-02-12T08:01:20
119,360,768
0
0
null
null
null
null
UHC
Java
false
false
35,482
java
package kos.triple.project.service.soon; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import kos.triple.project.etc.PageCalculator; import kos.triple.project.etc.ServerSetting; import kos.triple.project.persistence.soon.stayReservationDAO; import kos.triple.project.vo.Reservation_CarVO; import kos.triple.project.vo.Reservation_StayVO; import kos.triple.project.vo.StayRoomVO; import kos.triple.project.vo.StayVO; import kos.triple.project.vo.StayVO; import kos.triple.project.vo.WhereVO; @Service public class stayReservationServiceImpl implements stayReservationService { @Autowired stayReservationDAO dao; // 숙박지 검색 @Override public void stay_search(HttpServletRequest req, Model model) { String search = req.getParameter("search"); String stay_kind = req.getParameter("stay_kind"); String stay_class = req.getParameter("stay_class"); int standard = Integer.parseInt(req.getParameter("stay_people")); System.out.println("stay_kind"+stay_kind); System.out.println("stay_class"+stay_class); System.out.println("standard"+standard); Map<String, Object> map = new HashMap<String, Object>(); map.put("search", search); map.put("stay_kind", stay_kind); map.put("stay_class", stay_class); map.put("standard", standard); ArrayList<StayVO> vos = dao.stay_search(map); model.addAttribute("vos", vos); } @Override public void stay_view(HttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); StayVO vo = dao.stay_view(stay_no); model.addAttribute("vo", vo); } @Override public void stay_room_search(HttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); String start_date = req.getParameter("start_date"); String end_date = req.getParameter("end_date"); Map<String, Object> checkMap = new HashMap<String, Object>(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date start_Day = (Date) formatter.parse(start_date); //일 계산 - 출발날짜 Date end_Day = (Date) formatter.parse(end_date); //일 계산 - 반납날짜 long diff = end_Day.getTime() - start_Day.getTime(); long diffDats = diff / (24 * 60 * 60 * 1000); model.addAttribute("diffDats", diffDats); List<Reservation_StayVO> vo = dao.date(); if(vo != null) { for (Reservation_StayVO i : vo) { Date DBCheck_in = (Date) formatter.parse(i.getCheck_in()); //DB에 저장된 빌린날짜 Date DBCheck_out = (Date) formatter.parse(i.getCheck_out()); //DB에 저장된 반납날짜 System.out.println("DB 체크인 "+DBCheck_in); System.out.println("DB 체크아웃 "+DBCheck_out); Date Search_Check_in = (Date) formatter.parse(start_date); // ~~일부터 검색한 날짜 Date Search_Check_out = (Date) formatter.parse(end_date); // ~~일까지 검색한 날짜 System.out.println("검색 체크인 "+Search_Check_in); System.out.println("검색 체크아웃 "+Search_Check_out); String room_no= i.getRoom_no(); //DB에 저장된 차량고유번호 int rentalDate = DBCheck_in.compareTo(Search_Check_in); // A.compareTo(B) => A가 B보다 크냐를 물어본다. A가 B보다 크면 1, A와 B가 같으면 0, A가 B보다 작으면 -1 int returnDate = DBCheck_out.compareTo(Search_Check_out); int rentalDate_f = DBCheck_in.compareTo(Search_Check_out); int returnDate_f = DBCheck_out.compareTo(Search_Check_in); System.out.println("room_no : " + room_no); int check = 0; if(returnDate_f == -1) { if(rentalDate_f == -1 ) { if(rentalDate == -1 && returnDate == 1) { System.out.println("1.예약 불가능"); check = 0; }else { System.out.println("1.예약 가능"); check = 1; } }else { System.out.println("2.예약 불가능"); check = 2; } }else { if(rentalDate_f == 1){ System.out.println("2.예약 가능"); check = 3; }else { System.out.println("3.예약 불가능"); check = 4; } } checkMap.put(room_no, check); } model.addAttribute("checkMap",checkMap); } }catch(java.text.ParseException e){ e.printStackTrace(); } ArrayList<StayVO> vos = dao.stay_room_list(stay_no); model.addAttribute("check_in", start_date); model.addAttribute("check_out", end_date); model.addAttribute("vos", vos); } @Override public void stay_room_view(HttpServletRequest req, Model model) { String room_no = req.getParameter("room_no"); int total_price = Integer.parseInt(req.getParameter("total_price")); String check_in = req.getParameter("check_in"); String check_out = req.getParameter("check_out"); /*Map<String, Object> map = new HashMap<String, Object>(); map.put("stay_no", stay_no); map.put("room_no", room_no);*/ StayRoomVO vo = dao.stay_room_view(room_no); model.addAttribute("vo", vo); model.addAttribute("total_price", total_price); model.addAttribute("check_in", check_in); model.addAttribute("check_out", check_out); } @Override public void stay_room_reservation(HttpServletRequest req, Model model) { String mem_id = req.getParameter("mem_id"); String stay_no = req.getParameter("stay_no"); String room_no = req.getParameter("room_no"); String check_in = req.getParameter("check_in"); String check_out = req.getParameter("check_out"); int total_price = Integer.parseInt(req.getParameter("total_price")); String stay_people = req.getParameter("stay_people"); String pay_method = req.getParameter("pay_method"); Map<String, Object> map = new HashMap<String, Object>(); map.put("mem_id", mem_id); map.put("stay_no", stay_no); map.put("room_no", room_no); map.put("check_in", check_in); map.put("check_out", check_out); map.put("total_price", total_price); map.put("stay_people", stay_people); map.put("pay_method", pay_method); int cnt = dao.stay_room_reservation(map); model.addAttribute("cnt", cnt); } @Override public void stayResCancel(HttpServletRequest req, Model model) { String reservation_no = req.getParameter("reservation_no"); dao.stayResCancel(reservation_no); } // 마이 페이지 @Override public void getMyPageReserStay(HttpServletRequest req, Model model) { int pageSize = 5; //한 페이지당 출력할 글 개수 int pageBlock = 3; //한블럭당 페이지 개수 int number = 0; int cnt = 0; String pageNum = null; String mem_id = (String)req.getSession().getAttribute("mem_id"); //예약 리스트 갯수 구하기 cnt = dao.rentReservationCnt(); pageNum = req.getParameter("requestPage"); if(pageNum == null) { pageNum = "1"; //첫페이지를 1페이지로 설정 } PageCalculator p = new PageCalculator(Integer.parseInt(pageNum), cnt, pageBlock, pageSize); //조회하기 Map<String,Object> map = new HashMap<String, Object>(); map.put("start", p.getStart()); map.put("end", p.getEnd()); map.put("mem_id", mem_id); Map<String, Object> checkMap = new HashMap<String, Object>(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); // 현재 날짜 List<Reservation_StayVO> vo = dao.date(); if(vo != null) { for (Reservation_StayVO i : vo) { Date DBCheck_in = (Date) formatter.parse(i.getCheck_in()); //DB에 저장된 빌린날짜 Date DBCheck_out = (Date) formatter.parse(i.getCheck_out()); //DB에 저장된 반납날짜 String reservation_no= i.getReservation_no(); //DB에 저장된 차량고유번호 // A.compareTo(B) => A가 B보다 크냐를 물어본다. A가 B보다 크면 1, A와 B가 같으면 0, A가 B보다 작으면 -1 int res_ready = DBCheck_in.compareTo(date); // DB체크인이 현재 날짜보다 클때 int res_success = DBCheck_out.compareTo(date);// DB체크아웃이 현재 날짜보다 클때 System.out.println("reservation_no : " + reservation_no); int check = 0; if(res_ready == 1) { System.out.println("예약중"); check = 0; } else if(res_ready == 0) { System.out.println("숙박중"); check = 1; } else { if(res_success == 1) { System.out.println("숙박중"); check = 1; } else { System.out.println("숙박 완료"); check = 2; } } checkMap.put(reservation_no, check); } model.addAttribute("checkMap",checkMap); } }catch(java.text.ParseException e){ e.printStackTrace(); } ArrayList<Reservation_StayVO> dtos = dao.reservation_staylist(map); req.setAttribute("dtos_stay", dtos); req.setAttribute("number_stay", number); //글번호 req.setAttribute("cnt_stay", cnt); //예약 갯수 if(cnt > 0) { req.setAttribute("startPage_stay", p.getStartPage()); //시작페이지 req.setAttribute("endPage_stay", p.getEndPage());//마지막페이지 req.setAttribute("pageBlock_stay", p.getBlockSize());//출력할 페이지 개수 req.setAttribute("pageCount_stay", p.getContentCount());//페이지 개수 req.setAttribute("pageNum_stay", p.getRequestPage());//현재 페이지 req.setAttribute("blockStartNumber_stay", p.getBlockStartNumber()); req.setAttribute("blockEndNumber_stay", p.getBlockEndNumber()); } } // 관리자 @Override public void stay_add(MultipartHttpServletRequest req, Model model) { MultipartFile file1 = req.getFile("stay_Images1"); MultipartFile file2 = req.getFile("stay_Images2"); MultipartFile file3 = req.getFile("stay_Images3"); MultipartFile file4 = req.getFile("stay_Images4"); MultipartFile file5 = req.getFile("stay_Images5"); MultipartFile file6 = req.getFile("stay_Images6"); System.out.println("이미지 확인"); String saveDir = req.getSession().getServletContext().getRealPath("/resources/images/stay/stay_location"); // 저장 String realDir = ServerSetting.imgPath+"\\src\\main\\webapp\\resources\\images\\stay\\stay_location\\"; // 저장 // 경로 FileInputStream fis = null; FileOutputStream fos = null; String fileName1 = null; String fileName2 = null; String fileName3 = null; String fileName4 = null; String fileName5 = null; String fileName6 = null; try { file1.transferTo(new File(saveDir + file1.getOriginalFilename())); fis = new FileInputStream(saveDir + file1.getOriginalFilename()); fos = new FileOutputStream(realDir + file1.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName1 = file1.getOriginalFilename(); } catch (IOException e) { fileName1 = "default.jpg"; } try { file2.transferTo(new File(saveDir + file2.getOriginalFilename())); fis = new FileInputStream(saveDir + file2.getOriginalFilename()); fos = new FileOutputStream(realDir + file2.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName2 = file2.getOriginalFilename(); } catch (Exception e) { fileName2 = "default.jpg"; } try { file3.transferTo(new File(saveDir + file3.getOriginalFilename())); fis = new FileInputStream(saveDir + file3.getOriginalFilename()); fos = new FileOutputStream(realDir + file3.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName3 = file3.getOriginalFilename(); } catch (Exception e) { fileName3 = "default.jpg"; } try { file4.transferTo(new File(saveDir + file4.getOriginalFilename())); fis = new FileInputStream(saveDir + file4.getOriginalFilename()); fos = new FileOutputStream(realDir + file4.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName4 = file4.getOriginalFilename(); } catch (Exception e) { fileName4 = "default.jpg"; } try { file5.transferTo(new File(saveDir + file5.getOriginalFilename())); fis = new FileInputStream(saveDir + file5.getOriginalFilename()); fos = new FileOutputStream(realDir + file5.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName5 = file5.getOriginalFilename(); } catch (Exception e) { fileName5 = "default.jpg"; } try { file6.transferTo(new File(saveDir + file6.getOriginalFilename())); fis = new FileInputStream(saveDir + file6.getOriginalFilename()); fos = new FileOutputStream(realDir + file6.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName6 = file6.getOriginalFilename(); } catch (Exception e) { fileName6 = "default.jpg"; } String stay_name = req.getParameter("stay_Name"); String stay_address = req.getParameter("stay_Address"); String stay_cellphone = req.getParameter("stay_tell"); String stay_introduce = req.getParameter("stay_Info"); String stay_kind = req.getParameter("stay_kind"); String stay_class = req.getParameter("stay_class"); String stay_general_details = req.getParameter("stay_general_details"); String stay_amenities = req.getParameter("stay_amenities"); String stay_service = req.getParameter("stay_service"); String stay_internet = req.getParameter("stay_internet"); String stay_parking = req.getParameter("stay_parking"); String stay_check_in = req.getParameter("stay_check_in"); String stay_check_out = req.getParameter("stay_check_out"); String stay_x = req.getParameter("stay_X"); String stay_y = req.getParameter("stay_Y"); StayVO vo = new StayVO(); vo.setStay_img1(fileName1); vo.setStay_img2(fileName2); vo.setStay_img3(fileName3); vo.setStay_img4(fileName4); vo.setStay_img5(fileName5); vo.setStay_img6(fileName6); vo.setStay_name(stay_name); vo.setStay_address(stay_address); vo.setStay_cellphone(stay_cellphone); vo.setStay_introduce(stay_introduce); vo.setStay_kind(stay_kind); vo.setStay_class(stay_class); vo.setStay_general_details(stay_general_details); vo.setStay_amenities(stay_amenities); vo.setStay_service(stay_service); vo.setStay_internet(stay_internet); vo.setStay_parking(stay_parking); vo.setStay_check_in(stay_check_in); vo.setStay_check_out(stay_check_out); vo.setStay_x(stay_x); vo.setStay_y(stay_y); int cnt = dao.stay_add(vo); model.addAttribute("cnt", cnt); } @Override public void stay_list(HttpServletRequest req, Model model) { int pageSize = 10; // 한 페이지 당 출력할 글 갯수 int pageBlock = 5; // 한 블럭 당 페이지 갯수 int cnt = 0; // 장소 갯수 int start = 0; // 현재 페이지 글 시작 번호 int end = 0; // 현재 페이지 글 마지막 번호 int number = 0; // 출력할 글 번호 String pageNum = null; // 페이지 번호 int currentPage = 0; // 현재 페이지 int pageCount = 0; // 페이지 갯수 int startPage = 0; // 시작 페이지 int endPage = 0; // 마지막 페이지 // 장소 개수 구하기 cnt = dao.getCountCnt(); System.out.println("cnt : " + cnt); pageNum = req.getParameter("pageNum"); if (pageNum == null) { pageNum = "1"; // 첫 페이지를 1페이지로 설정 } currentPage = (Integer.parseInt(pageNum)); // 현재 페이지 // pageCnt = 12 / 5 + 1; --> 나머지 2건이 1페이지로 할당되므로 3페이지 pageCount = (cnt / pageSize) + (cnt % pageSize > 0 ? 1 : 0); // 페이지 갯수 // 1 = (1 - 1) * 5 + 1 // 6 = (2 - 1) * 5 + 1 // 12 = (3 - 1) * 5 + 1 start = (currentPage - 1) * pageSize + 1; // 현재 페이지 시작 번호 // 5 = 1 + 5 - 1; end = start + pageSize - 1; // 현재 페이지 끝번호 System.out.println("start : " + start); System.out.println("end : " + end); if (end > cnt) end = cnt; // 20 = 21 - (5 - 1) * 5; number = cnt - (currentPage - 1) * pageSize; // 출력할 장소 번호 --> 최신 글(큰페이지)가 1p System.out.println("number : " + number); System.out.println("cnt : " + cnt); System.out.println("currentPage : " + currentPage); System.out.println("pageSize : " + pageSize); if (cnt > 0) { // 장소 목록 Map<String, Integer> map = new HashMap<String, Integer>(); map.put("start", start); map.put("end", end); ArrayList<StayVO> vos = dao.stay_list(map); model.addAttribute("vos", vos); } startPage = (currentPage / pageBlock) * pageBlock + 1; // (5/3) * 3 + 1 = 4; if (currentPage % pageBlock == 0) startPage -= pageBlock; // (5%3) == 0 endPage = startPage + pageBlock - 1; // 4 + 3 - 1 = 6 if (endPage > pageCount) endPage = pageCount; model.addAttribute("cnt", cnt); // 장소 갯수 model.addAttribute("number", number); // 글 번호 model.addAttribute("pageNum", pageNum); // 페이지 번호 if (cnt > 0) { model.addAttribute("startPage", startPage); // 시작 페이지 model.addAttribute("endPage", endPage); // 마지막 페이지 model.addAttribute("pageBlock", pageBlock); // 출력할 페이지 갯수 model.addAttribute("pageCount", pageCount); // 페이지 갯수 model.addAttribute("currentPage", currentPage); // 현재 페이지 } } @Override public void stay_list_view(HttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); StayVO vo = dao.stay_list_view(stay_no); model.addAttribute("vo", vo); } @Override public void modify(MultipartHttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); String stay_name = req.getParameter("stay_Name"); String stay_address = req.getParameter("stay_Address"); String stay_cellphone = req.getParameter("stay_tell"); String stay_introduce = req.getParameter("stay_Info"); String stay_kind = req.getParameter("stay_kind"); String stay_class = req.getParameter("stay_class"); String stay_general_details = req.getParameter("stay_general_details"); String stay_amenities = req.getParameter("stay_amenities"); String stay_service = req.getParameter("stay_service"); String stay_internet = req.getParameter("stay_internet"); String stay_parking = req.getParameter("stay_parking"); String stay_check_in = req.getParameter("stay_check_in"); String stay_check_out = req.getParameter("stay_check_out"); String stay_x = req.getParameter("stay_X"); String stay_y = req.getParameter("stay_Y"); Map<String,Object> imgMap = new HashMap<String,Object>(); imgMap.put("stay_no", stay_no); MultipartFile file1 = req.getFile("stay_Images1"); MultipartFile file2 = req.getFile("stay_Images2"); MultipartFile file3 = req.getFile("stay_Images3"); MultipartFile file4 = req.getFile("stay_Images4"); MultipartFile file5 = req.getFile("stay_Images5"); MultipartFile file6 = req.getFile("stay_Images6"); String saveDir = req.getSession().getServletContext().getRealPath("/resources/images/stay/stay_location"); // 저장 String realDir = ServerSetting.imgPath+"\\src\\main\\webapp\\resources\\images\\stay\\stay_location\\"; // 저장 // 경로 FileInputStream fis = null; FileOutputStream fos = null; String fileName1 = null; String fileName2 = null; String fileName3 = null; String fileName4 = null; String fileName5 = null; String fileName6 = null; try { file1.transferTo(new File(saveDir + file1.getOriginalFilename())); fis = new FileInputStream(saveDir + file1.getOriginalFilename()); fos = new FileOutputStream(realDir + file1.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName1 = file1.getOriginalFilename(); imgMap.put("imgName",fileName1); imgMap.put("location","img1"); dao.updateImg(imgMap); } catch (IOException e) { e.printStackTrace(); } try { file2.transferTo(new File(saveDir + file2.getOriginalFilename())); fis = new FileInputStream(saveDir + file2.getOriginalFilename()); fos = new FileOutputStream(realDir + file2.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName2 = file2.getOriginalFilename(); imgMap.put("imgName",fileName2); imgMap.put("location","img2"); dao.updateImg(imgMap); } catch (Exception e) { } try { file3.transferTo(new File(saveDir + file3.getOriginalFilename())); fis = new FileInputStream(saveDir + file3.getOriginalFilename()); fos = new FileOutputStream(realDir + file3.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName3 = file3.getOriginalFilename(); imgMap.put("imgName",fileName3); imgMap.put("location","img3"); dao.updateImg(imgMap); } catch (Exception e) { e.printStackTrace(); } try { file4.transferTo(new File(saveDir + file4.getOriginalFilename())); fis = new FileInputStream(saveDir + file4.getOriginalFilename()); fos = new FileOutputStream(realDir + file4.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName4 = file4.getOriginalFilename(); imgMap.put("imgName",fileName4); imgMap.put("location","img4"); dao.updateImg(imgMap); } catch (Exception e) { e.printStackTrace(); } try { file5.transferTo(new File(saveDir + file5.getOriginalFilename())); fis = new FileInputStream(saveDir + file5.getOriginalFilename()); fos = new FileOutputStream(realDir + file5.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName5 = file5.getOriginalFilename(); imgMap.put("imgName",fileName5); imgMap.put("location","img5"); dao.updateImg(imgMap); } catch (Exception e) { e.printStackTrace(); } try { file6.transferTo(new File(saveDir + file6.getOriginalFilename())); fis = new FileInputStream(saveDir + file6.getOriginalFilename()); fos = new FileOutputStream(realDir + file6.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName6 = file6.getOriginalFilename(); imgMap.put("imgName",fileName6); imgMap.put("location","img6"); dao.updateImg(imgMap); } catch (Exception e) { e.printStackTrace(); } StayVO vo = new StayVO(); vo.setStay_img1(fileName1); vo.setStay_img2(fileName2); vo.setStay_img3(fileName3); vo.setStay_img4(fileName4); vo.setStay_img5(fileName5); vo.setStay_img6(fileName6); vo.setStay_name(stay_name); vo.setStay_address(stay_address); vo.setStay_cellphone(stay_cellphone); vo.setStay_introduce(stay_introduce); vo.setStay_kind(stay_kind); vo.setStay_class(stay_class); vo.setStay_general_details(stay_general_details); vo.setStay_amenities(stay_amenities); vo.setStay_service(stay_service); vo.setStay_internet(stay_internet); vo.setStay_parking(stay_parking); vo.setStay_check_in(stay_check_in); vo.setStay_check_out(stay_check_out); vo.setStay_x(stay_x); vo.setStay_y(stay_y); vo.setStay_no(stay_no); int cnt = dao.modify(vo); model.addAttribute("cnt", cnt); } @Override public void delete(HttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); int cnt = dao.delete(stay_no); model.addAttribute("cnt", cnt); } @Override public void stay_room_add(MultipartHttpServletRequest req, Model model) { MultipartFile file1 = req.getFile("room_img"); System.out.println("이미지 확인"); String saveDir = req.getSession().getServletContext().getRealPath("/resources/images/stay/stay_location_room"); // 저장 String realDir = ServerSetting.imgPath+"\\src\\main\\webapp\\resources\\images\\stay\\stay_location_room\\"; // 저장 // 경로 FileInputStream fis = null; FileOutputStream fos = null; String fileName1 = null; try { file1.transferTo(new File(saveDir + file1.getOriginalFilename())); fis = new FileInputStream(saveDir + file1.getOriginalFilename()); fos = new FileOutputStream(realDir + file1.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName1 = file1.getOriginalFilename(); } catch (IOException e) { fileName1 = "default.jpg"; } String stay_no = req.getParameter("stay_no"); String room_name = req.getParameter("room_name"); int standard = Integer.parseInt(req.getParameter("standard")); int sale_price = Integer.parseInt(req.getParameter("sale_price")); String room_info = req.getParameter("room_info"); StayVO vo = new StayVO(); vo.setRoom_img(fileName1); vo.setStay_no(stay_no); vo.setRoom_name(room_name); vo.setStandard(standard); vo.setSale_price(sale_price); vo.setRoom_info(room_info); int cnt = dao.stay_room_add(vo); model.addAttribute("cnt", cnt); } @Override public void stay_room_list(HttpServletRequest req, Model model) { String stay_no = req.getParameter("stay_no"); ArrayList<StayVO> vos = dao.stay_room_list(stay_no); model.addAttribute("vos", vos); } @Override public void stay_room_list_view(HttpServletRequest req, Model model) { String room_no = req.getParameter("room_no"); StayVO vo = dao.stay_room_list_view(room_no); model.addAttribute("vo", vo); } @Override public void stay_room_modify(MultipartHttpServletRequest req, Model model) { String room_no = req.getParameter("room_no"); String room_name = req.getParameter("room_name"); int standard = Integer.parseInt(req.getParameter("standard")); int sale_price = Integer.parseInt(req.getParameter("sale_price")); String room_info = req.getParameter("room_info"); Map<String,Object> imgMap = new HashMap<String,Object>(); imgMap.put("room_no", room_no); MultipartFile file1 = req.getFile("room_img"); String saveDir = req.getSession().getServletContext().getRealPath("/resources/images/stay/stay_location_room"); // 저장 String realDir = ServerSetting.imgPath+"\\src\\main\\webapp\\resources\\images\\stay\\stay_location_room\\"; // 저장 // 경로 FileInputStream fis = null; FileOutputStream fos = null; String fileName1 = null; try { file1.transferTo(new File(saveDir + file1.getOriginalFilename())); fis = new FileInputStream(saveDir + file1.getOriginalFilename()); fos = new FileOutputStream(realDir + file1.getOriginalFilename()); int data = 0; while ((data = fis.read()) != -1) { fos.write(data); } fis.close(); fos.close(); fileName1 = file1.getOriginalFilename(); imgMap.put("imgName",fileName1); imgMap.put("location","img1"); dao.room_updateImg(imgMap); } catch (IOException e) { e.printStackTrace(); } StayVO vo = new StayVO(); vo.setRoom_img(fileName1); vo.setRoom_name(room_name); vo.setStandard(standard); vo.setSale_price(sale_price); vo.setRoom_info(room_info); vo.setRoom_no(room_no); int cnt = dao.stay_room_modify(vo); model.addAttribute("cnt", cnt); } @Override public void stay_room_delete(HttpServletRequest req, Model model) { String room_no = req.getParameter("room_no"); int cnt = dao.stay_room_delete(room_no); model.addAttribute("cnt", cnt); } @Override public void stay_reservation_list(HttpServletRequest req, Model model) { int pageSize = 5; // 한 페이지당 출력할 글 개수 int pageBlock = 3; // 한블럭당 페이지 개수 int number = 0; int cnt = 0; String pageNum = null; // 예약 리스트 갯수 구하기 cnt = dao.rentReservationCnt(); pageNum = req.getParameter("requestPage"); if(pageNum == null) { pageNum = "1"; // 첫페이지를 1페이지로 설정 } PageCalculator p = new PageCalculator(Integer.parseInt(pageNum), cnt, pageBlock, pageSize); // 조회하기 Map<String,Object> map = new HashMap<String, Object>(); map.put("start", p.getStart()); map.put("end", p.getEnd()); Map<String, Object> checkMap = new HashMap<String, Object>(); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); // 현재 날짜 List<Reservation_StayVO> vo = dao.date(); if(vo != null) { for (Reservation_StayVO i : vo) { Date DBCheck_in = (Date) formatter.parse(i.getCheck_in()); //DB에 저장된 빌린날짜 Date DBCheck_out = (Date) formatter.parse(i.getCheck_out()); //DB에 저장된 반납날짜 String reservation_no= i.getReservation_no(); //DB에 저장된 차량고유번호 // A.compareTo(B) => A가 B보다 크냐를 물어본다. A가 B보다 크면 1, A와 B가 같으면 0, A가 B보다 작으면 -1 int res_ready = DBCheck_in.compareTo(date); // DB체크인이 현재 날짜보다 클때 int res_success = DBCheck_out.compareTo(date);// DB체크아웃이 현재 날짜보다 클때 System.out.println("reservation_no : " + reservation_no); int check = 0; if(res_ready == 1) { System.out.println("예약중"); check = 0; } else if(res_ready == 0) { System.out.println("숙박중"); check = 1; } else { if(res_success == 1) { System.out.println("숙박중"); check = 1; } else { System.out.println("숙박 완료"); check = 2; } } checkMap.put(reservation_no, check); } model.addAttribute("checkMap",checkMap); } }catch(java.text.ParseException e){ e.printStackTrace(); } ArrayList<Reservation_StayVO> dtos = dao.stay_reservation_list(map); req.setAttribute("dtos_stay", dtos); req.setAttribute("number_stay", number); //글번호 req.setAttribute("cnt_stay", cnt); //예약 갯수 req.setAttribute("startPage_stay", p.getStartPage()); //시작페이지 req.setAttribute("endPage_stay", p.getEndPage());//마지막페이지 req.setAttribute("pageBlock_stay", p.getBlockSize());//출력할 페이지 개수 req.setAttribute("pageCount_stay", p.getContentCount());//페이지 개수 req.setAttribute("pageNum_stay", p.getRequestPage());//현재 페이지 req.setAttribute("blockStartNumber_stay", p.getBlockStartNumber()); req.setAttribute("blockEndNumber_stay", p.getBlockEndNumber()); } @Override @SuppressWarnings("unchecked") public void stay_reservation_total(HttpServletRequest req, Model model) { String year = req.getParameter("year"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy"); Date date = new Date(); // 현재 날짜 String now_date = formatter.format(date); if(year == null) { year = now_date; } int totalSale = dao.getTotalSale(); model.addAttribute("totalSale", totalSale); Map<String, Object> map = (Map<String, Object>) dao.getFirstChart(); model.addAttribute("firstChat", map); Map<String, Object> map2 = (Map<String, Object>) dao.getSecondChart(); model.addAttribute("secondChart", map2); Map<String, Object> map3 = (Map<String, Object>) dao.getFinalChart(year); model.addAttribute("fianlChart", map3); model.addAttribute("today", year); } @Override public void getCharData_Stay(HttpServletRequest req, Model model) { Map<String,Object> stay_fristChat = new HashMap<String, Object>(); Map<String,Object> stay_secondChat = new HashMap<String, Object>(); Map<String,Object> stay_finalChat = new HashMap<String, Object>(); String year = req.getParameter("year") == null ? Integer.toString(Calendar.getInstance().get(Calendar.YEAR)) : req.getParameter("year"); int firstChatValue = dao.getFirstChartAll(); stay_fristChat.put("firstChatValue", 0); stay_fristChat.put("firstChatValue", firstChatValue); int secondChatValue = dao.getSecondChartAll(); stay_secondChat.put("secondChatValue", 0); stay_secondChat.put("secondChatValue", secondChatValue); stay_finalChat = dao.getFinalChartAll(year); model.addAttribute("stay_fristChat", stay_fristChat); model.addAttribute("stay_secondChat", stay_secondChat); model.addAttribute("stay_finalChat", stay_finalChat); } }
[ "KO_11@KO_11-PC" ]
KO_11@KO_11-PC
cfde8f8e465e6cfb4f7c60282a564aae8ac0bde7
1e91783ba465ba95a525e3f05c31d4b718225d78
/src/main/java/Constants.java
ffe2452e6a2659d0fcd1efbc7fa6097774b5315b
[]
no_license
aaaltive/ser316--summer2021-A-aaaltive
6a46b04aaab93859a55f9e8960e1d30734f66df9
3a9a391ed80c07177c384bf894d2f221fa071096
refs/heads/master
2023-06-05T09:18:05.328768
2021-06-11T23:55:20
2021-06-11T23:55:20
371,462,647
0
0
null
null
null
null
UTF-8
Java
false
false
219
java
public class Constants { public static final double BONUS = 1.25; public static final double DEBUFF = 0.75; public static final double ATTACK_BONUS = 1.2; public static final double NONE_ATTACK = 0; }
a61657c0cfcf161ac674bf0f6522a0716e1367ae
81a8ef917dc0ccfb50c404199d0cd05fd1df2510
/app/src/main/java/com/storagemanagement/app/scanshelf/camera/CameraSource.java
7f9c6fd0a604c6b4981ab5cbea3bb585601ddfeb
[]
no_license
rainking185/ScanShelf
39d65f1e935c48c00225cb79a9f871dbcf843319
a45d0d38120c8e4ea2d7d2151d5c015ed78c6d24
refs/heads/master
2020-03-11T01:41:34.295831
2018-06-11T08:54:09
2018-06-11T08:54:09
129,698,771
0
0
null
null
null
null
UTF-8
Java
false
false
49,112
java
/* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.storagemanagement.app.scanshelf.camera; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Build; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.annotation.StringDef; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import com.google.android.gms.common.images.Size; import com.google.android.gms.vision.Detector; import com.google.android.gms.vision.Frame; import com.storagemanagement.app.scanshelf.Main; import java.io.IOException; import java.lang.Thread.State; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; // Note: This requires Google Play Services 8.1 or higher, due to using indirect byte buffers for // storing images. /** * Manages the camera in conjunction with an underlying * {@link com.google.android.gms.vision.Detector}. This receives preview frames from the camera at * a specified rate, sending those frames to the detector as fast as it is able to process those * frames. * <p/> * This camera source makes a best effort to manage processing on preview frames as fast as * possible, while at the same time minimizing lag. As such, frames may be dropped if the detector * is unable to keep up with the rate of frames generated by the camera. You should use * {@link CameraSource.Builder#setRequestedFps(float)} to specify a frame rate that works well with * the capabilities of the camera hardware and the detector options that you have selected. If CPU * utilization is higher than you'd like, then you may want to consider reducing FPS. If the camera * preview or detector results are too "jerky", then you may want to consider increasing FPS. * <p/> * The following Android permission is required to use the camera: * <ul> * <li>android.permissions.CAMERA</li> * </ul> */ @SuppressWarnings("deprecation") public class CameraSource { @SuppressLint("InlinedApi") public static final int CAMERA_FACING_BACK = CameraInfo.CAMERA_FACING_BACK; @SuppressLint("InlinedApi") public static final int CAMERA_FACING_FRONT = CameraInfo.CAMERA_FACING_FRONT; private static final String TAG = "OpenCameraSource"; /** * The dummy surface texture must be assigned a chosen name. Since we never use an OpenGL * context, we can choose any ID we want here. */ private static final int DUMMY_TEXTURE_NAME = 100; /** * If the absolute difference between a preview size aspect ratio and a picture size aspect * ratio is less than this tolerance, they are considered to be the same aspect ratio. */ private static final float ASPECT_RATIO_TOLERANCE = 0.01f; @StringDef({ Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, Camera.Parameters.FOCUS_MODE_AUTO, Camera.Parameters.FOCUS_MODE_EDOF, Camera.Parameters.FOCUS_MODE_FIXED, Camera.Parameters.FOCUS_MODE_INFINITY, Camera.Parameters.FOCUS_MODE_MACRO }) @Retention(RetentionPolicy.SOURCE) private @interface FocusMode { } @StringDef({ Camera.Parameters.FLASH_MODE_ON, Camera.Parameters.FLASH_MODE_OFF, Camera.Parameters.FLASH_MODE_AUTO, Camera.Parameters.FLASH_MODE_RED_EYE, Camera.Parameters.FLASH_MODE_TORCH }) @Retention(RetentionPolicy.SOURCE) private @interface FlashMode { } private Context mContext; private final Object mCameraLock = new Object(); // Guarded by mCameraLock private Camera mCamera; private int mFacing = CAMERA_FACING_BACK; /** * Rotation of the device, and thus the associated preview images captured from the device. * See {@link Frame.Metadata#getRotation()}. */ private int mRotation; private Size mPreviewSize; // These values may be requested by the caller. Due to hardware limitations, we may need to // select close, but not exactly the same values for these. private float mRequestedFps = 30.0f; private int mRequestedPreviewWidth = 1024; private int mRequestedPreviewHeight = 768; private String mFocusMode = null; private String mFlashMode = null; // These instances need to be held onto to avoid GC of their underlying resources. Even though // these aren't used outside of the method that creates them, they still must have hard // references maintained to them. private SurfaceView mDummySurfaceView; private SurfaceTexture mDummySurfaceTexture; /** * Dedicated thread and associated runnable for calling into the detector with frames, as the * frames become available from the camera. */ private Thread mProcessingThread; private FrameProcessingRunnable mFrameProcessor; /** * Map to convert between a byte array, received from the camera, and its associated byte * buffer. We use byte buffers internally because this is a more efficient way to call into * native code later (avoids a potential copy). */ private Map<byte[], ByteBuffer> mBytesToByteBuffer = new HashMap<>(); //============================================================================================== // Builder //============================================================================================== /** * Builder for configuring and creating an associated camera source. */ public static class Builder { private final Detector<?> mDetector; private CameraSource mCameraSource = new CameraSource(); /** * Creates a camera source builder with the supplied context and detector. Camera preview * images will be streamed to the associated detector upon starting the camera source. */ public Builder(Context context, Detector<?> detector) { if (context == null) { throw new IllegalArgumentException("No context supplied."); } if (detector == null) { throw new IllegalArgumentException("No detector supplied."); } mDetector = detector; mCameraSource.mContext = context; } /** * Sets the requested frame rate in frames per second. If the exact requested value is not * not available, the best matching available value is selected. Default: 30. */ public Builder setRequestedFps(float fps) { if (fps <= 0) { throw new IllegalArgumentException("Invalid fps: " + fps); } mCameraSource.mRequestedFps = fps; return this; } public Builder setFocusMode(@FocusMode String mode) { mCameraSource.mFocusMode = mode; return this; } public Builder setFlashMode(@FlashMode String mode) { mCameraSource.mFlashMode = mode; return this; } /** * Sets the desired width and height of the camera frames in pixels. If the exact desired * values are not available options, the best matching available options are selected. * Also, we try to select a preview size which corresponds to the aspect ratio of an * associated full picture size, if applicable. Default: 1024x768. */ public Builder setRequestedPreviewSize(int width, int height) { // Restrict the requested range to something within the realm of possibility. The // choice of 1000000 is a bit arbitrary -- intended to be well beyond resolutions that // devices can support. We bound this to avoid int overflow in the code later. final int MAX = 1000000; if ((width <= 0) || (width > MAX) || (height <= 0) || (height > MAX)) { throw new IllegalArgumentException("Invalid preview size: " + width + "x" + height); } mCameraSource.mRequestedPreviewWidth = width; mCameraSource.mRequestedPreviewHeight = height; return this; } /** * Sets the camera to use (either {@link #CAMERA_FACING_BACK} or * {@link #CAMERA_FACING_FRONT}). Default: back facing. */ public Builder setFacing(int facing) { if ((facing != CAMERA_FACING_BACK) && (facing != CAMERA_FACING_FRONT)) { throw new IllegalArgumentException("Invalid camera: " + facing); } mCameraSource.mFacing = facing; return this; } /** * Creates an instance of the camera source. */ public CameraSource build() { mCameraSource.mFrameProcessor = mCameraSource.new FrameProcessingRunnable(mDetector); return mCameraSource; } } //============================================================================================== // Bridge Functionality for the Camera1 API //============================================================================================== /** * Callback interface used to signal the moment of actual image capture. */ public interface ShutterCallback { /** * Called as near as possible to the moment when a photo is captured from the sensor. This * is a good opportunity to play a shutter sound or give other feedback of camera operation. * This may be some time after the photo was triggered, but some time before the actual data * is available. */ void onShutter(); } /** * Callback interface used to supply image data from a photo capture. */ public interface PictureCallback { /** * Called when image data is available after a picture is taken. The format of the data * is a jpeg binary. */ void onPictureTaken(byte[] data); } /** * Callback interface used to notify on completion of camera auto focus. */ public interface AutoFocusCallback { /** * Called when the camera auto focus completes. If the camera * does not support auto-focus and autoFocus is called, * onAutoFocus will be called immediately with a fake value of * <code>success</code> set to <code>true</code>. * <p/> * The auto-focus routine does not lock auto-exposure and auto-white * balance after it completes. * * @param success true if focus was successful, false if otherwise */ void onAutoFocus(boolean success); } /** * Callback interface used to notify on auto focus start and stop. * <p/> * <p>This is only supported in continuous autofocus modes -- {@link * Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO} and {@link * Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}. Applications can show * autofocus animation based on this.</p> */ public interface AutoFocusMoveCallback { /** * Called when the camera auto focus starts or stops. * * @param start true if focus starts to move, false if focus stops to move */ void onAutoFocusMoving(boolean start); } //============================================================================================== // Public //============================================================================================== /** * Stops the camera and releases the resources of the camera and underlying detector. */ public void release() { synchronized (mCameraLock) { stop(); mFrameProcessor.release(); } } /** * Opens the camera and starts sending preview frames to the underlying detector. The preview * frames are not displayed. * * @throws IOException if the camera's preview texture or display could not be initialized */ @SuppressLint("MissingPermission") @RequiresPermission(Manifest.permission.CAMERA) public CameraSource start() throws IOException { synchronized (mCameraLock) { if (mCamera != null) { return this; } mCamera = createCamera(); // SurfaceTexture was introduced in Honeycomb (11), so if we are running and // old version of Android. fall back to use SurfaceView. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mDummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME); mCamera.setPreviewTexture(mDummySurfaceTexture); } else { mDummySurfaceView = new SurfaceView(mContext); mCamera.setPreviewDisplay(mDummySurfaceView.getHolder()); } mCamera.startPreview(); mProcessingThread = new Thread(mFrameProcessor); mFrameProcessor.setActive(true); mProcessingThread.start(); } return this; } /** * Opens the camera and starts sending preview frames to the underlying detector. The supplied * surface holder is used for the preview so frames can be displayed to the user. * * @param surfaceHolder the surface holder to use for the preview frames * @throws IOException if the supplied surface holder could not be used as the preview display */ @SuppressLint("MissingPermission") @RequiresPermission(Manifest.permission.CAMERA) public CameraSource start(SurfaceHolder surfaceHolder) throws IOException { synchronized (mCameraLock) { if (mCamera != null) { return this; } mCamera = createCamera(); mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); mProcessingThread = new Thread(mFrameProcessor); mFrameProcessor.setActive(true); mProcessingThread.start(); } return this; } /** * Closes the camera and stops sending frames to the underlying frame detector. * <p/> * This camera source may be restarted again by calling {@link #start()} or * {@link #start(SurfaceHolder)}. * <p/> * Call {@link #release()} instead to completely shut down this camera source and release the * resources of the underlying detector. */ public void stop() { synchronized (mCameraLock) { mFrameProcessor.setActive(false); if (mProcessingThread != null) { try { // Wait for the thread to complete to ensure that we can't have multiple threads // executing at the same time (i.e., which would happen if we called start too // quickly after stop). mProcessingThread.join(); } catch (InterruptedException e) { Log.d(TAG, "Frame processing thread interrupted on release."); } mProcessingThread = null; } // clear the buffer to prevent oom exceptions mBytesToByteBuffer.clear(); if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallbackWithBuffer(null); try { // We want to be compatible back to Gingerbread, but SurfaceTexture // wasn't introduced until Honeycomb. Since the interface cannot use a SurfaceTexture, if the // developer wants to display a preview we must use a SurfaceHolder. If the developer doesn't // want to display a preview we use a SurfaceTexture if we are running at least Honeycomb. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mCamera.setPreviewTexture(null); } else { mCamera.setPreviewDisplay(null); } } catch (Exception e) { Log.e(TAG, "Failed to clear camera preview: " + e); } mCamera.release(); mCamera = null; } } } /** * Returns the preview size that is currently in use by the underlying camera. */ public Size getPreviewSize() { return mPreviewSize; } /** * Returns the selected camera; one of {@link #CAMERA_FACING_BACK} or * {@link #CAMERA_FACING_FRONT}. */ public int getCameraFacing() { return mFacing; } public int doZoom(float scale) { synchronized (mCameraLock) { if (mCamera == null) { return 0; } int currentZoom = 0; int maxZoom; Camera.Parameters parameters = mCamera.getParameters(); if (!parameters.isZoomSupported()) { Log.w(TAG, "Zoom is not supported on this device"); return currentZoom; } maxZoom = parameters.getMaxZoom(); currentZoom = parameters.getZoom() + 1; float newZoom; if (scale > 1) { newZoom = currentZoom + scale * (maxZoom / 10); } else { newZoom = currentZoom * scale; } currentZoom = Math.round(newZoom) - 1; if (currentZoom < 0) { currentZoom = 0; } else if (currentZoom > maxZoom) { currentZoom = maxZoom; } parameters.setZoom(currentZoom); mCamera.setParameters(parameters); return currentZoom; } } /** * Initiates taking a picture, which happens asynchronously. The camera source should have been * activated previously with {@link #start()} or {@link #start(SurfaceHolder)}. The camera * preview is suspended while the picture is being taken, but will resume once picture taking is * done. * * @param shutter the callback for image capture moment, or null * @param jpeg the callback for JPEG image data, or null */ public void takePicture(ShutterCallback shutter, PictureCallback jpeg) { synchronized (mCameraLock) { if (mCamera != null) { PictureStartCallback startCallback = new PictureStartCallback(); startCallback.mDelegate = shutter; PictureDoneCallback doneCallback = new PictureDoneCallback(); doneCallback.mDelegate = jpeg; mCamera.takePicture(startCallback, null, null, doneCallback); } } } /** * Gets the current focus mode setting. * * @return current focus mode. This value is null if the camera is not yet created. Applications should call {@link * #autoFocus(AutoFocusCallback)} to start the focus if focus * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. * @see Camera.Parameters#FOCUS_MODE_AUTO * @see Camera.Parameters#FOCUS_MODE_INFINITY * @see Camera.Parameters#FOCUS_MODE_MACRO * @see Camera.Parameters#FOCUS_MODE_FIXED * @see Camera.Parameters#FOCUS_MODE_EDOF * @see Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO * @see Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE */ @Nullable @FocusMode public String getFocusMode() { return mFocusMode; } /** * Sets the focus mode. * * @param mode the focus mode * @return {@code true} if the focus mode is set, {@code false} otherwise * @see #getFocusMode() */ public boolean setFocusMode(@FocusMode String mode) { synchronized (mCameraLock) { if (mCamera != null && mode != null) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getSupportedFocusModes().contains(mode)) { parameters.setFocusMode(mode); mCamera.setParameters(parameters); mFocusMode = mode; return true; } } return false; } } /** * Gets the current flash mode setting. * * @return current flash mode. null if flash mode setting is not * supported or the camera is not yet created. * @see Camera.Parameters#FLASH_MODE_OFF * @see Camera.Parameters#FLASH_MODE_AUTO * @see Camera.Parameters#FLASH_MODE_ON * @see Camera.Parameters#FLASH_MODE_RED_EYE * @see Camera.Parameters#FLASH_MODE_TORCH */ @Nullable @FlashMode public String getFlashMode() { return mFlashMode; } /** * Sets the flash mode. * * @param mode flash mode. * @return {@code true} if the flash mode is set, {@code false} otherwise * @see #getFlashMode() */ public boolean setFlashMode(@FlashMode String mode) { synchronized (mCameraLock) { if (mCamera != null && mode != null) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getSupportedFlashModes().contains(mode)) { parameters.setFlashMode(mode); mCamera.setParameters(parameters); mFlashMode = mode; return true; } } return false; } } /** * Starts camera auto-focus and registers a callback function to run when * the camera is focused. This method is only valid when preview is active * (between {@link #start()} or {@link #start(SurfaceHolder)} and before {@link #stop()} or {@link #release()}). * <p/> * <p>Callers should check * {@link #getFocusMode()} to determine if * this method should be called. If the camera does not support auto-focus, * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean)} * callback will be called immediately. * <p/> * <p>If the current flash mode is not * {@link Camera.Parameters#FLASH_MODE_OFF}, flash may be * fired during auto-focus, depending on the driver and camera hardware.<p> * * @param cb the callback to run * @see #cancelAutoFocus() */ public void autoFocus(@Nullable AutoFocusCallback cb) { synchronized (mCameraLock) { if (mCamera != null) { CameraAutoFocusCallback autoFocusCallback = null; if (cb != null) { autoFocusCallback = new CameraAutoFocusCallback(); autoFocusCallback.mDelegate = cb; } mCamera.autoFocus(autoFocusCallback); } } } /** * Cancels any auto-focus function in progress. * Whether or not auto-focus is currently in progress, * this function will return the focus position to the default. * If the camera does not support auto-focus, this is a no-op. * * @see #autoFocus(AutoFocusCallback) */ public void cancelAutoFocus() { synchronized (mCameraLock) { if (mCamera != null) { mCamera.cancelAutoFocus(); } } } /** * Sets camera auto-focus move callback. * * @param cb the callback to run * @return {@code true} if the operation is supported (i.e. from Jelly Bean), {@code false} otherwise */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean setAutoFocusMoveCallback(@Nullable AutoFocusMoveCallback cb) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return false; } synchronized (mCameraLock) { if (mCamera != null) { CameraAutoFocusMoveCallback autoFocusMoveCallback = null; if (cb != null) { autoFocusMoveCallback = new CameraAutoFocusMoveCallback(); autoFocusMoveCallback.mDelegate = cb; } mCamera.setAutoFocusMoveCallback(autoFocusMoveCallback); } } return true; } //============================================================================================== // Private //============================================================================================== /** * Only allow creation via the builder class. */ private CameraSource() { } /** * Wraps the camera1 shutter callback so that the deprecated API isn't exposed. */ private class PictureStartCallback implements Camera.ShutterCallback { private ShutterCallback mDelegate; @Override public void onShutter() { if (mDelegate != null) { mDelegate.onShutter(); } } } /** * Wraps the final callback in the camera sequence, so that we can automatically turn the camera * preview back on after the picture has been taken. */ private class PictureDoneCallback implements Camera.PictureCallback { private PictureCallback mDelegate; @Override public void onPictureTaken(byte[] data, Camera camera) { if (mDelegate != null) { mDelegate.onPictureTaken(data); } synchronized (mCameraLock) { if (mCamera != null) { mCamera.startPreview(); } } } } /** * Wraps the camera1 auto focus callback so that the deprecated API isn't exposed. */ private class CameraAutoFocusCallback implements Camera.AutoFocusCallback { private AutoFocusCallback mDelegate; @Override public void onAutoFocus(boolean success, Camera camera) { if (mDelegate != null) { mDelegate.onAutoFocus(success); } } } /** * Wraps the camera1 auto focus move callback so that the deprecated API isn't exposed. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private class CameraAutoFocusMoveCallback implements Camera.AutoFocusMoveCallback { private AutoFocusMoveCallback mDelegate; @Override public void onAutoFocusMoving(boolean start, Camera camera) { if (mDelegate != null) { mDelegate.onAutoFocusMoving(start); } } } /** * Opens the camera and applies the user settings. * * @throws RuntimeException if the method fails */ @SuppressLint("InlinedApi") private Camera createCamera() { int requestedCameraId = getIdForRequestedCamera(mFacing); if (requestedCameraId == -1) { throw new RuntimeException("Could not find requested camera."); } Camera camera = Camera.open(requestedCameraId); SizePair sizePair = selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight); if (sizePair == null) { throw new RuntimeException("Could not find suitable preview size."); } Size pictureSize = sizePair.pictureSize(); mPreviewSize = sizePair.previewSize(); int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps); if (previewFpsRange == null) { throw new RuntimeException("Could not find suitable preview frames per second range."); } Camera.Parameters parameters = camera.getParameters(); if (pictureSize != null) { parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight()); } parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); parameters.setPreviewFpsRange( previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX], previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]); parameters.setPreviewFormat(ImageFormat.NV21); setRotation(camera, parameters, requestedCameraId); if (mFocusMode != null) { if (parameters.getSupportedFocusModes().contains( mFocusMode)) { parameters.setFocusMode(mFocusMode); } else { Log.i(TAG, "Camera focus mode: " + mFocusMode + " is not supported on this device."); } } // setting mFocusMode to the one set in the params mFocusMode = parameters.getFocusMode(); if (mFlashMode != null) { if (parameters.getSupportedFlashModes() != null) { if (parameters.getSupportedFlashModes().contains( mFlashMode)) { parameters.setFlashMode(mFlashMode); } else { Log.i(TAG, "Camera flash mode: " + mFlashMode + " is not supported on this device."); } } } // setting mFlashMode to the one set in the params mFlashMode = parameters.getFlashMode(); camera.setParameters(parameters); // Four frame buffers are needed for working with the camera: // // one for the frame that is currently being executed upon in doing detection // one for the next pending frame to process immediately upon completing detection // two for the frames that the camera uses to populate future preview images camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback()); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); return camera; } /** * Gets the id for the camera specified by the direction it is facing. Returns -1 if no such * camera was found. * * @param facing the desired camera (front-facing or rear-facing) */ private static int getIdForRequestedCamera(int facing) { CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); ++i) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == facing) { return i; } } return -1; } /** * Selects the most suitable preview and picture size, given the desired width and height. * <p/> * Even though we may only need the preview size, it's necessary to find both the preview * size and the picture size of the camera together, because these need to have the same aspect * ratio. On some hardware, if you would only set the preview size, you will get a distorted * image. * * @param camera the camera to select a preview size from * @param desiredWidth the desired width of the camera preview frames * @param desiredHeight the desired height of the camera preview frames * @return the selected preview and picture size pair */ private static SizePair selectSizePair(Camera camera, int desiredWidth, int desiredHeight) { List<SizePair> validPreviewSizes = generateValidPreviewSizeList(camera); // The method for selecting the best size is to minimize the sum of the differences between // the desired values and the actual values for width and height. This is certainly not the // only way to select the best size, but it provides a decent tradeoff between using the // closest aspect ratio vs. using the closest pixel area. SizePair selectedPair = null; int minDiff = Integer.MAX_VALUE; for (SizePair sizePair : validPreviewSizes) { Size size = sizePair.previewSize(); int diff = Math.abs(size.getWidth() - desiredWidth) + Math.abs(size.getHeight() - desiredHeight); if (diff < minDiff) { selectedPair = sizePair; minDiff = diff; } } return selectedPair; } /** * Stores a preview size and a corresponding same-aspect-ratio picture size. To avoid distorted * preview images on some devices, the picture size must be set to a size that is the same * aspect ratio as the preview size or the preview may end up being distorted. If the picture * size is null, then there is no picture size with the same aspect ratio as the preview size. */ private static class SizePair { private Size mPreview; private Size mPicture; public SizePair(android.hardware.Camera.Size previewSize, android.hardware.Camera.Size pictureSize) { mPreview = new Size(previewSize.width, previewSize.height); if (pictureSize != null) { mPicture = new Size(pictureSize.width, pictureSize.height); } } public Size previewSize() { return mPreview; } @SuppressWarnings("unused") public Size pictureSize() { return mPicture; } } /** * Generates a list of acceptable preview sizes. Preview sizes are not acceptable if there is * not a corresponding picture size of the same aspect ratio. If there is a corresponding * picture size of the same aspect ratio, the picture size is paired up with the preview size. * <p/> * This is necessary because even if we don't use still pictures, the still picture size must be * set to a size that is the same aspect ratio as the preview size we choose. Otherwise, the * preview images may be distorted on some devices. */ private static List<SizePair> generateValidPreviewSizeList(Camera camera) { Camera.Parameters parameters = camera.getParameters(); List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes(); List<Camera.Size> supportedPictureSizes = parameters.getSupportedPictureSizes(); List<SizePair> validPreviewSizes = new ArrayList<>(); for (android.hardware.Camera.Size previewSize : supportedPreviewSizes) { float previewAspectRatio = (float) previewSize.width / (float) previewSize.height; // By looping through the picture sizes in order, we favor the higher resolutions. // We choose the highest resolution in order to support taking the full resolution // picture later. for (android.hardware.Camera.Size pictureSize : supportedPictureSizes) { float pictureAspectRatio = (float) pictureSize.width / (float) pictureSize.height; if (Math.abs(previewAspectRatio - pictureAspectRatio) < ASPECT_RATIO_TOLERANCE) { validPreviewSizes.add(new SizePair(previewSize, pictureSize)); break; } } } // If there are no picture sizes with the same aspect ratio as any preview sizes, allow all // of the preview sizes and hope that the camera can handle it. Probably unlikely, but we // still account for it. if (validPreviewSizes.size() == 0) { Log.w(TAG, "No preview sizes have a corresponding same-aspect-ratio picture size"); for (android.hardware.Camera.Size previewSize : supportedPreviewSizes) { // The null picture size will let us know that we shouldn't set a picture size. validPreviewSizes.add(new SizePair(previewSize, null)); } } return validPreviewSizes; } /** * Selects the most suitable preview frames per second range, given the desired frames per * second. * * @param camera the camera to select a frames per second range from * @param desiredPreviewFps the desired frames per second for the camera preview frames * @return the selected preview frames per second range */ private int[] selectPreviewFpsRange(Camera camera, float desiredPreviewFps) { // The camera API uses integers scaled by a factor of 1000 instead of floating-point frame // rates. int desiredPreviewFpsScaled = (int) (desiredPreviewFps * 1000.0f); // The method for selecting the best range is to minimize the sum of the differences between // the desired value and the upper and lower bounds of the range. This may select a range // that the desired value is outside of, but this is often preferred. For example, if the // desired frame rate is 29.97, the range (30, 30) is probably more desirable than the // range (15, 30). int[] selectedFpsRange = null; int minDiff = Integer.MAX_VALUE; List<int[]> previewFpsRangeList = camera.getParameters().getSupportedPreviewFpsRange(); for (int[] range : previewFpsRangeList) { int deltaMin = desiredPreviewFpsScaled - range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX]; int deltaMax = desiredPreviewFpsScaled - range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]; int diff = Math.abs(deltaMin) + Math.abs(deltaMax); if (diff < minDiff) { selectedFpsRange = range; minDiff = diff; } } return selectedFpsRange; } /** * Calculates the correct rotation for the given camera id and sets the rotation in the * parameters. It also sets the camera's display orientation and rotation. * * @param parameters the camera parameters for which to set the rotation * @param cameraId the camera id to set rotation based on */ private void setRotation(Camera camera, Camera.Parameters parameters, int cameraId) { WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); int degrees = 0; int rotation = windowManager.getDefaultDisplay().getRotation(); switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; default: Log.e(TAG, "Bad rotation value: " + rotation); } CameraInfo cameraInfo = new CameraInfo(); Camera.getCameraInfo(cameraId, cameraInfo); int angle; int displayAngle; if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { angle = (cameraInfo.orientation + degrees) % 360; displayAngle = (360 - angle) % 360; // compensate for it being mirrored } else { // back-facing angle = (cameraInfo.orientation - degrees + 360) % 360; displayAngle = angle; } // This corresponds to the rotation constants in {@link Frame}. mRotation = angle / 90; camera.setDisplayOrientation(displayAngle); parameters.setRotation(angle); } /** * Creates one buffer for the camera preview callback. The size of the buffer is based off of * the camera preview size and the format of the camera image. * * @return a new preview buffer of the appropriate size for the current camera settings */ private byte[] createPreviewBuffer(Size previewSize) { int bitsPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.NV21); long sizeInBits = previewSize.getHeight() * previewSize.getWidth() * bitsPerPixel; int bufferSize = (int) Math.ceil(sizeInBits / 8.0d) + 1; // // NOTICE: This code only works when using play services v. 8.1 or higher. // // Creating the byte array this way and wrapping it, as opposed to using .allocate(), // should guarantee that there will be an array to work with. byte[] byteArray = new byte[bufferSize]; ByteBuffer buffer = ByteBuffer.wrap(byteArray); if (!buffer.hasArray() || (buffer.array() != byteArray)) { // I don't think that this will ever happen. But if it does, then we wouldn't be // passing the preview content to the underlying detector later. throw new IllegalStateException("Failed to create valid buffer for camera source."); } mBytesToByteBuffer.put(byteArray, buffer); return byteArray; } //============================================================================================== // Frame processing //============================================================================================== /** * Called when the camera has a new preview frame. */ private class CameraPreviewCallback implements Camera.PreviewCallback { @Override public void onPreviewFrame(byte[] data, Camera camera) { mFrameProcessor.setNextFrame(data, camera); } } /** * This runnable controls access to the underlying receiver, calling it to process frames when * available from the camera. This is designed to run detection on frames as fast as possible * (i.e., without unnecessary context switching or waiting on the next frame). * <p/> * While detection is running on a frame, new frames may be received from the camera. As these * frames come in, the most recent frame is held onto as pending. As soon as detection and its * associated processing are done for the previous frame, detection on the mostly recently * received frame will immediately start on the same thread. */ private class FrameProcessingRunnable implements Runnable { private Detector<?> mDetector; private long mStartTimeMillis = SystemClock.elapsedRealtime(); // This lock guards all of the member variables below. private final Object mLock = new Object(); private boolean mActive = true; // These pending variables hold the state associated with the new frame awaiting processing. private long mPendingTimeMillis; private int mPendingFrameId = 0; private ByteBuffer mPendingFrameData; FrameProcessingRunnable(Detector<?> detector) { mDetector = detector; } /** * Releases the underlying receiver. This is only safe to do after the associated thread * has completed, which is managed in camera source's release method above. */ @SuppressLint("Assert") void release() { assert (mProcessingThread.getState() == State.TERMINATED); mDetector.release(); mDetector = null; } /** * Marks the runnable as active/not active. Signals any blocked threads to continue. */ void setActive(boolean active) { synchronized (mLock) { mActive = active; mLock.notifyAll(); } } /** * Sets the frame data received from the camera. This adds the previous unused frame buffer * (if present) back to the camera, and keeps a pending reference to the frame data for * future use. */ void setNextFrame(byte[] data, Camera camera) { synchronized (mLock) { if (mPendingFrameData != null) { camera.addCallbackBuffer(mPendingFrameData.array()); mPendingFrameData = null; } if (!mBytesToByteBuffer.containsKey(data)) { Log.d(TAG, "Skipping frame. Could not find ByteBuffer associated with the image " + "data from the camera."); return; } // Timestamp and frame ID are maintained here, which will give downstream code some // idea of the timing of frames received and when frames were dropped along the way. mPendingTimeMillis = SystemClock.elapsedRealtime() - mStartTimeMillis; mPendingFrameId++; mPendingFrameData = mBytesToByteBuffer.get(data); // Notify the processor thread if it is waiting on the next frame (see below). mLock.notifyAll(); } } /** * As long as the processing thread is active, this executes detection on frames * continuously. The next pending frame is either immediately available or hasn't been * received yet. Once it is available, we transfer the frame info to local variables and * run detection on that frame. It immediately loops back for the next frame without * pausing. * <p/> * If detection takes longer than the time in between new frames from the camera, this will * mean that this loop will run without ever waiting on a frame, avoiding any context * switching or frame acquisition time latency. * <p/> * If you find that this is using more CPU than you'd like, you should probably decrease the * FPS setting above to allow for some idle time in between frames. */ @Override public void run() { Frame outputFrame; ByteBuffer data; while (true) { synchronized (mLock) { while (mActive && (mPendingFrameData == null)) { try { // Wait for the next frame to be received from the camera, since we // don't have it yet. mLock.wait(); } catch (InterruptedException e) { Log.d(TAG, "Frame processing loop terminated.", e); return; } } if (!mActive) { // Exit the loop once this camera source is stopped or released. We check // this here, immediately after the wait() above, to handle the case where // setActive(false) had been called, triggering the termination of this // loop. return; } outputFrame = new Frame.Builder() .setImageData(mPendingFrameData, mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.NV21) .setId(mPendingFrameId) .setTimestampMillis(mPendingTimeMillis) .setRotation(mRotation) .build(); // Hold onto the frame data locally, so that we can use this for detection // below. We need to clear mPendingFrameData to ensure that this buffer isn't // recycled back to the camera before we are done using that data. data = mPendingFrameData; mPendingFrameData = null; } // The code below needs to run outside of synchronization, because this will allow // the camera to add pending frame(s) while we are running detection on the current // frame. try { mDetector.receiveFrame(outputFrame); } catch (Throwable t) { Log.e(TAG, "Exception thrown from receiver.", t); } finally { mCamera.addCallbackBuffer(data.array()); } } } } }
aa110abb22ea1b79aa52cd6f22fb3380f904a76c
c8417895a7b071e7b2cc07a6791357c5bffc7889
/com/google/android/gms/drive/internal/OnResourceIdSetResponse.java
854bd6fb801a407b1efadc369d5bc1543aeca090
[]
no_license
HansaTharuka/Explore
70a610cac38469cddf2dc87c9f67dcd9a94f8d1a
b71eb84c57fb28b687ce6df4a69e14a3dcaf8458
refs/heads/master
2021-01-24T11:27:25.524180
2018-02-27T06:33:37
2018-02-27T06:33:37
123,083,071
0
0
null
null
null
null
UTF-8
Java
false
false
1,037
java
package com.google.android.gms.drive.internal; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.SafeParcelable; import java.util.List; public class OnResourceIdSetResponse implements SafeParcelable { public static final Parcelable.Creator<OnResourceIdSetResponse> CREATOR = new av(); private final int CK; private final List<String> Po; OnResourceIdSetResponse(int paramInt, List<String> paramList) { this.CK = paramInt; this.Po = paramList; } public int describeContents() { return 0; } public int getVersionCode() { return this.CK; } public List<String> iF() { return this.Po; } public void writeToParcel(Parcel paramParcel, int paramInt) { av.a(this, paramParcel, paramInt); } } /* Location: D:\Testing\hacking\dex2jar-0.0.9.15\dex2jar-0.0.9.15\classes_dex2jar.jar * Qualified Name: com.google.android.gms.drive.internal.OnResourceIdSetResponse * JD-Core Version: 0.6.0 */
ae2c5e766c67056812af98b70d95e831545bba4f
958b13739d7da564749737cb848200da5bd476eb
/src/main/java/com/alipay/api/response/KoubeiMarketingCampaignCrowdModifyResponse.java
5d2b7be9b4794318069dee240e7771dbea5daed3
[ "Apache-2.0" ]
permissive
anywhere/alipay-sdk-java-all
0a181c934ca84654d6d2f25f199bf4215c167bd2
649e6ff0633ebfca93a071ff575bacad4311cdd4
refs/heads/master
2023-02-13T02:09:28.859092
2021-01-14T03:17:27
2021-01-14T03:17:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
387
java
package com.alipay.api.response; import com.alipay.api.AlipayResponse; /** * ALIPAY API: koubei.marketing.campaign.crowd.modify response. * * @author auto create * @since 1.0, 2019-01-07 20:51:15 */ public class KoubeiMarketingCampaignCrowdModifyResponse extends AlipayResponse { private static final long serialVersionUID = 3412397314475755375L; }
fc00d53cda8f17af0960a18bd96d73c82591e78b
e546d47b6689b9a4a09b5244b06ae598f1ff3dc9
/src/main/java/com/example/array/KadaneAlgorithmMaxSubArray.java
2b71bd82ab86e44169ac0a55ba488c9e76dc6bb0
[]
no_license
narayantalk2u/Interview
8e606dbeb3c3124205901706ae6c1981fb0bb913
4574efea0a2be7e5aa612214da0d119a9101594d
refs/heads/master
2022-08-06T15:01:26.564581
2020-05-14T02:18:43
2020-05-14T02:18:43
263,791,202
0
0
null
null
null
null
UTF-8
Java
false
false
1,233
java
package com.example.array; import static java.lang.Integer.max; public class KadaneAlgorithmMaxSubArray { /** * Kadane algoritm to findout max sum of subarray * @param a * @return */ public static int kadaneAlgorithmMaxSubArray(int a[]) { int currMax = a[0]; int globalMax = a[0]; int sum = 0; int start = 0; int end = 0; for (int i = 1; i < a.length; ++i) { sum = currMax + a[i]; currMax = max(a[i], sum); globalMax = max(globalMax, currMax); // updating start index if (sum < currMax) { start = i; } // updating end index if (globalMax < currMax) { end = i; } } System.out.println("Maximum contiguous sum is " + globalMax); System.out.println("Starting index " + start + "Ending index " +end); return globalMax; } /*Driver program to test maxSubArraySum*/ public static void main(String []args) { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int max_sum = kadaneAlgorithmMaxSubArray(a); System.out.println("Maximum sum: "+max_sum); } }
f5827163d332c8489a1f17c8158ed1d566fe1c62
ffd1cfbaa438019f1c596792714a478871903e8d
/Lesson17Concurrency/src/io/zhaoyang/java24hr/lesson17/TextThread.java
f7d48703f264dc95931a8bb016df6203f1a87e70
[]
no_license
BIT-zhaoyang/Java24hr
d577fcb80569666080244a939cd70552eedfae50
e6bb5cc89694d86b326975331ecbc1e3ab2fb2b6
refs/heads/master
2021-07-08T03:30:32.284427
2017-09-28T03:56:55
2017-09-28T03:56:55
103,006,223
0
0
null
null
null
null
UTF-8
Java
false
false
617
java
package io.zhaoyang.java24hr.lesson17; public class TextThread { public static void main(String[] args) { TxtThread tt = new TxtThread(); new Thread(tt).start(); new Thread(tt).start(); new Thread(tt).start(); new Thread(tt).start(); } } class TxtThread implements Runnable { int num = 10; String str = new String(); public void run() { synchronized (str) { while (num > 0) { try { Thread.sleep(1); } catch (Exception e) { e.getMessage(); } System.out.println(Thread.currentThread().getName() + "this is " + num--); } } } }
09fe563525566f549dc2c82f2d6eb1ad8eaf4e70
6554944fac004526e647299fc1573b10cdbaa380
/src/com/example/community_list_post/library/JSONParseraddress.java
e32216ab5da15c72cde9294b1f58fdac7e9aeee6
[]
no_license
lenumtus/Hint
664fdbcd67a8b1792e838afcb34fb7d4c27d9def
55f867c95456844fea4131ef6fd76422b5094479
refs/heads/master
2016-09-05T17:24:18.635875
2015-07-17T08:37:52
2015-07-17T08:37:52
39,239,370
0
0
null
null
null
null
UTF-8
Java
false
false
1,720
java
package com.example.community_list_post.library; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; public class JSONParseraddress { static InputStream is = null; static JSONObject jobj = null; static String json = ""; public JSONParseraddress(){ } public JSONObject makeHttpRequest(String url){ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); try { HttpResponse httpresponse = httpclient.execute(httppost); HttpEntity httpentity = httpresponse.getEntity(); is = httpentity.getContent(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; try { while((line = reader.readLine())!=null){ sb.append(line+"\n"); } is.close(); json = sb.toString(); try { jobj = new JSONObject(json); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jobj; } }
d9917d936f1f6257719a547d8552c28e5e8b8667
94f1d77c19bf1d3e41f1fcdb7a8168e370b4dbe9
/src/main/java/com/miao/miaosha/pojo/Order.java
17d1b621bb707d2e480019b682fb2cb6a406e92d
[]
no_license
Arctic-cat/miaosha
7276c1763a4b6f9f790a2e9ced0d40d3d169f780
5444b8f9cc81a5e7d076c220a5ebba429c60befb
refs/heads/master
2020-03-27T08:25:56.048211
2018-08-27T06:12:30
2018-08-27T06:12:30
146,253,736
0
0
null
null
null
null
UTF-8
Java
false
false
2,101
java
package com.miao.miaosha.pojo; import java.util.Date; public class Order { private Long id; private Long userId; private Long goodsId; private Long deliveryAddrId; private String goodsName; private Integer goodsCount; private Double goodsPrice; private Integer orderChannel; private Integer status; private Date createDate; private Date payDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getGoodsId() { return goodsId; } public void setGoodsId(Long goodsId) { this.goodsId = goodsId; } public Long getDeliveryAddrId() { return deliveryAddrId; } public void setDeliveryAddrId(Long deliveryAddrId) { this.deliveryAddrId = deliveryAddrId; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } public Integer getGoodsCount() { return goodsCount; } public void setGoodsCount(Integer goodsCount) { this.goodsCount = goodsCount; } public Double getGoodsPrice() { return goodsPrice; } public void setGoodsPrice(Double goodsPrice) { this.goodsPrice = goodsPrice; } public Integer getOrderChannel() { return orderChannel; } public void setOrderChannel(Integer orderChannel) { this.orderChannel = orderChannel; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getPayDate() { return payDate; } public void setPayDate(Date payDate) { this.payDate = payDate; } }
52cb17bf148f4f4d71bfae27c903f8411b577d5f
e6be1c458851a19b5f53e86e8505fe07bc5c6014
/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/navigation/locationreferences/LocationReferencesHighlighter.java
622ad18897e9e54a87101879e3026ef93b4bf7a1
[ "Apache-2.0", "GPL-1.0-or-later", "GPL-3.0-only", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
penhoi/ghidra-decompiler
6a950ad56acc467fa4fd771097d068d9785d36e0
151133f957e8fb4172cd6f0f4b750b5948df4c95
refs/heads/master
2020-05-19T16:46:36.863144
2019-07-26T01:17:19
2019-07-26T01:17:19
185,118,431
17
7
Apache-2.0
2019-07-10T10:16:13
2019-05-06T03:36:43
Java
UTF-8
Java
false
false
7,948
java
/* ### * IP: GHIDRA * * 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 ghidra.app.plugin.core.navigation.locationreferences; import java.awt.Color; import docking.widgets.fieldpanel.support.Highlight; import ghidra.GhidraOptions; import ghidra.app.nav.Navigatable; import ghidra.app.services.*; import ghidra.app.util.HighlightProvider; import ghidra.app.util.viewer.field.FieldFactory; import ghidra.framework.options.OptionsChangeListener; import ghidra.framework.options.ToolOptions; import ghidra.framework.plugintool.PluginTool; import ghidra.program.model.address.AddressSet; import ghidra.program.model.data.DataType; import ghidra.program.model.listing.Program; /** * Handles highlighting for {@link LocationReferencesProvider}. */ class LocationReferencesHighlighter { private static final String MARKER_SET_DESCRIPTION = "Shows the location of references " + "currently displayed in the Location References window."; private static final String OPTIONS_TITLE = GhidraOptions.CATEGORY_BROWSER_FIELDS; private static final String HIGHLIGHT_COLOR = "References Highlight" + GhidraOptions.DELIMITER + "Color"; private static Color DEFAULT_HIGHLIGHT_COLOR = new Color(168, 202, 242); private boolean isHighlighting = false; private final Navigatable navigatable; private LocationReferencesProvider provider; private LocationReferencesPlugin locationReferencesPlugin; private HighlightProvider highlightProvider; private MarkerRemover markerRemover; private Color highlightColor; private OptionsChangeListener optionsListener = new OptionsChangeListener() { @Override public void optionsChanged(ToolOptions options, String name, Object oldValue, Object newValue) { if (name.equals(HIGHLIGHT_COLOR)) { highlightColor = (Color) newValue; } } }; LocationReferencesHighlighter(LocationReferencesPlugin locationReferencesPlugin, LocationReferencesProvider provider, Navigatable navigatable) { this.locationReferencesPlugin = locationReferencesPlugin; this.navigatable = navigatable; if (provider == null) { throw new NullPointerException("null provider not allowed."); } this.provider = provider; ToolOptions options = locationReferencesPlugin.getTool().getOptions(OPTIONS_TITLE); options.registerOption(HIGHLIGHT_COLOR, DEFAULT_HIGHLIGHT_COLOR, null, null); highlightColor = options.getColor(HIGHLIGHT_COLOR, DEFAULT_HIGHLIGHT_COLOR); options.addOptionsChangeListener(optionsListener); } void setHighlightingEnabled(boolean enabled) { isHighlighting = enabled; updateHighlights(); } private void updateHighlights() { PluginTool tool = locationReferencesPlugin.getTool(); if (tool == null) { // happens during tool exit return; } if (!navigatable.supportsHighlight()) { return; } Program activeProgram = navigatable.getProgram(); Program providerProgram = provider.getProgram(); // no need to highlight if the active provider is not based upon the current program if (isHighlighting && (activeProgram != providerProgram)) { return; } LocationDescriptor locationDescriptor = provider.getLocationDescriptor(); DataTypeManagerService dataTypeManagerService = tool.getService(DataTypeManagerService.class); if (isHighlighting) { // we know that if the address set is the same, then the marking and highlighting // have not changed AddressSet set = provider.getReferenceAddresses(providerProgram); // markers setHighlightMarkers(tool, set); // listing panel highlights highlightProvider = new LocationReferencesHighlightProvider(); navigatable.setHighlightProvider(highlightProvider, providerProgram); // check for data types (the user may have changed the selected datatype, so // re-select it) selectDataType(dataTypeManagerService, locationDescriptor, true); } else { // markers clearMarkers(); // deselect in data type manager selectDataType(dataTypeManagerService, locationDescriptor, false); } } private void setHighlightMarkers(PluginTool tool, AddressSet addressSet) { if (!navigatable.supportsMarkers()) { return; } clearMarkers(); MarkerService markerService = tool.getService(MarkerService.class); if (markerService == null) { return; // we still work without the marker service } Program program = navigatable.getProgram(); // creating the marker set adds it, so be sure to remove the marker set after we // create it MarkerSet currentMarkerSet = markerService.createPointMarker("References To", MARKER_SET_DESCRIPTION, program, MarkerService.HIGHLIGHT_PRIORITY, false, true, false, highlightColor, null); markerService.removeMarker(currentMarkerSet, program); markerService.setMarkerForGroup(MarkerService.HIGHLIGHT_GROUP, currentMarkerSet, program); currentMarkerSet.add(addressSet); markerRemover = new MarkerRemover(currentMarkerSet, markerService, program); } private void clearMarkers() { if (markerRemover != null) { markerRemover.dispose(); markerRemover = null; } // listing panel highlights Program providerProgram = provider.getProgram(); navigatable.removeHighlightProvider(highlightProvider, providerProgram); } private void selectDataType(DataTypeManagerService dataTypeManagerService, LocationDescriptor locationDescriptor, boolean enable) { if (!(locationDescriptor instanceof DataTypeLocationDescriptor)) { return; } if (dataTypeManagerService == null) { return; } DataTypeLocationDescriptor dataTypeDescriptor = (DataTypeLocationDescriptor) locationDescriptor; // if enabled, then select the data type from the descriptor, otherwise, deselect by using // null DataType locationDataType = null; if (enable) { locationDataType = dataTypeDescriptor.getSourceDataType(); } dataTypeManagerService.setDataTypeSelected(locationDataType); } LocationReferencesProvider getCurrentHighlightProvider() { return provider; } void dispose() { ToolOptions options = locationReferencesPlugin.getTool().getOptions(OPTIONS_TITLE); options.removeOptionsChangeListener(optionsListener); clearMarkers(); } //================================================================================================== // Inner Classes //================================================================================================== private class LocationReferencesHighlightProvider implements HighlightProvider { private final Highlight[] NO_HIGHLIGHTS = new Highlight[0]; // for the Class parameter @Override public Highlight[] getHighlights(String text, Object obj, Class<? extends FieldFactory> fieldFactoryClass, int cursorTextOffset) { if (text == null) { return NO_HIGHLIGHTS; } LocationDescriptor locationDescriptor = provider.getLocationDescriptor(); return locationDescriptor.getHighlights(text, obj, fieldFactoryClass, highlightColor); } } private class MarkerRemover { private final MarkerSet markerSet; private final MarkerService markerSerivce; private final Program program; private MarkerRemover(MarkerSet markerSet, MarkerService markerSerivce, Program program) { this.markerSet = markerSet; this.markerSerivce = markerSerivce; this.program = program; } void dispose() { markerSerivce.removeMarker(markerSet, program); } @Override public String toString() { return "MarkerRemover [MarkerSet=" + markerSet.getName() + "]"; } } }
d8246bf276ab5badbd9679fb7ed22d690439eca1
e7c81560089dc463288452c273dbae594c4fcd43
/src/main/java/org/activiti/engine/impl/jobexecutor/DefaultFailedJobCommandFactory.java
0588918a7d9e8a4545dfdc8542d3941d238e6915
[ "Apache-2.0" ]
permissive
ahwxl/deep
50684f3075fb284f6fb35e20bcc246b4d3ad1e4e
a4836ba0d2b3c4212315929ecec39bbf709d0b35
refs/heads/master
2020-05-22T01:32:28.349692
2019-03-03T04:43:00
2019-03-03T04:43:00
62,808,742
1
0
null
null
null
null
UTF-8
Java
false
false
993
java
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.jobexecutor; import org.activiti.engine.impl.cmd.JobRetryCmd; import org.activiti.engine.impl.interceptor.Command; /** * @author Saeid Mirzaei */ public class DefaultFailedJobCommandFactory implements FailedJobCommandFactory { @Override public Command<Object> getCommand(String jobId, Throwable exception) { return new JobRetryCmd(jobId, exception); } }
55a0545b2d812a4564eeac4f518f30ebde1a0f25
a5d440fa536db569b0ce71224af4702484dc6ccd
/TestsWithExtentReport/src/test/java/phptravels/pages/RegisterPage.java
2718b6218f155d781cf5cfec810b7ca540e74182
[]
no_license
LukArToDo/Testing-phptravels.net-
55206a3ef012f50d834e0e1437d2df07968967c7
2089d7f8e0093191987ec07fdc595d985eaea3ef
refs/heads/master
2021-06-15T15:29:54.940582
2019-06-12T18:18:46
2019-06-12T18:18:46
191,621,175
0
0
null
2021-04-26T19:14:06
2019-06-12T18:04:26
HTML
UTF-8
Java
false
false
3,422
java
package phptravels.pages; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import phptravels.base.BasePage; public class RegisterPage extends BasePage { @FindBy(name="firstname") WebElement firstNameField; @FindBy(name="lastname") WebElement lastNameField; @FindBy(name="phone") WebElement phoneField; @FindBy(name="email") WebElement emailField; @FindBy(name="password") WebElement passwordField; @FindBy(name="confirmpassword") WebElement confirmPasswordField; @FindBy(xpath="//form//button") WebElement signUpBtn_RegisterP; @FindBy(xpath="//div[@class='alert alert-danger']") WebElement errorMessage; // constructor public RegisterPage(WebDriver driver) { super(driver); } // methods for Register Page public RegisterPage goToRegisterPageDirectlyWithLink(String linkRegisterPage) { driver.get(linkRegisterPage); return this; } public RegisterPage goToRegisterPageTroughHomePage(String homePageURL) { return new HomePage(driver) .goToHomePage(homePageURL) .goToRegisterPage(); } public RegisterPage goToRegisterPageTroughLoginPage(String loginPageURL) { return new LoginPage(driver) .goToLoginPageWithLink(loginPageURL) .goToRegisterPageWithSignUpButton(); } public RegisterPage verifyRegisterPage(String registerPageTitle) { verifyPageTitle(registerPageTitle); return this; } public RegisterPage enterFirstName(String firstName) { writeText(firstNameField,firstName); return this; } public RegisterPage enterLastName(String lastName) { writeText(lastNameField, lastName); return this; } public RegisterPage enterMobileNumber(String mobileNumber) { writeText(phoneField, mobileNumber); return this; } public RegisterPage enterEmail(String email) { writeText(emailField, email); return this; } public RegisterPage enterPassword(String password) { writeText(passwordField, password); return this; } public RegisterPage enterConfirmPassword(String password) { writeText(confirmPasswordField, password); return this; } // Note: "click" seleniums method doesn't work with chromedriver public AccountPage signUp(String browser) { if(browser.equalsIgnoreCase("chrome")){ clickChrome(signUpBtn_RegisterP); } else { click(signUpBtn_RegisterP); } return new AccountPage(driver); } public RegisterPage fillAllRegistartionFields(String firstName, String lastName, String email, String password, String confPassword, String mobileNumber) { return enterFirstName(firstName) .enterLastName(lastName) .enterMobileNumber(mobileNumber) .enterEmail(email) .enterPassword(password) .enterConfirmPassword(confPassword); } // methods for error messages verification: public RegisterPage verifyErrorMessage(String expectedText) { assertEqual(errorMessage, expectedText); return this; } public boolean isErrorMesageDisplayed() { try { waitVisibility(errorMessage); return errorMessage.isDisplayed(); }catch(TimeoutException e) { System.out.println("Registration is successuful, error message is not displayed."); System.out.println(e.getMessage()); } return false; } }
610da52ba9e554fef495fde718237e0437288a1c
8870c2c001a4270e944e5e82db6a10c769372e7e
/app/src/main/java/com/blimas/listadetarefas/activity/AdicionarTarefaActivity.java
bd950ac31f4d4335fec96de50cd8acc8d766b982
[]
no_license
brect/ListaDeTarefas-android
893a0873102282ab253a052f9679671afb277c87
6c0b59d1d9b7fb1316161dfe714e56b2869e58bc
refs/heads/master
2020-12-15T14:32:05.910557
2020-01-21T19:17:46
2020-01-21T19:17:46
235,136,645
0
0
null
null
null
null
UTF-8
Java
false
false
3,769
java
package com.blimas.listadetarefas.activity; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.blimas.listadetarefas.R; import com.blimas.listadetarefas.helper.TarefaDAO; import com.blimas.listadetarefas.model.Tarefa; import com.google.android.material.textfield.TextInputEditText; public class AdicionarTarefaActivity extends AppCompatActivity { private TextInputEditText conteudoTarefa; private Tarefa edicaoTarefa; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_adicionar_tarefa); conteudoTarefa = findViewById(R.id.textTarefa); //recupera tarefa se for edicao edicaoTarefa = (Tarefa) getIntent().getSerializableExtra("tarefaEscolhida"); //configura caixa de texto if(edicaoTarefa != null){ conteudoTarefa.setText(edicaoTarefa.getNomeTarefa()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_salvar_tarefa, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (item.getItemId()){ case R.id.itemSalvarTarefa: //Executa acao para salvar o item TarefaDAO tarefaDAO = new TarefaDAO(getApplicationContext()); if (edicaoTarefa != null){//edicao String textoTarefa = conteudoTarefa.getText().toString(); if (!textoTarefa.isEmpty()){ Tarefa tarefa = new Tarefa(); tarefa.setNomeTarefa(textoTarefa); tarefa.setId(edicaoTarefa.getId()); //atualizar no banco de dados if (tarefaDAO.atualizar(tarefa)){ finish(); Toast.makeText(this, "Tarefa atualizada com sucesso", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(this, "Erro ao atualizar a Tarefa", Toast.LENGTH_SHORT).show(); } } }else {//salvar String textoTarefa = conteudoTarefa.getText().toString(); if (!textoTarefa.isEmpty() || textoTarefa != null){ Tarefa tarefa = new Tarefa(); tarefa.setNomeTarefa(textoTarefa); if (tarefaDAO.salvar(tarefa)){ Toast.makeText(this, "Tarefa salva com sucesso", Toast.LENGTH_SHORT).show(); finish(); }else { Toast.makeText(this, "Erro ao salvar a Tarefa", Toast.LENGTH_SHORT).show(); } } } break; } // if (id == R.id.itemSalvarTarefa) { // // //Executa acao para salvar o item // TarefaDAO tarefaDAO = new TarefaDAO(getApplicationContext()); // // Tarefa tarefa = new Tarefa(); // tarefa.setNomeTarefa("Ir ao xurupita"); // tarefaDAO.salvar(tarefa); // // Toast.makeText(this, "Tarefa salva" + tarefa, Toast.LENGTH_SHORT).show(); // return true; // } return super.onOptionsItemSelected(item); } }
[ "0uNn44t1Z8Gd" ]
0uNn44t1Z8Gd
f24585dfcc4b0f7330b120fa500f8b66f9433792
45250cf0eb221ebcac008473ae513781d9bd7ea9
/bufferstuff/src/main/java/tech/bitey/bufferstuff/BufferSpliterators.java
ed648b14e2d309392d2db50ad67a95b27cd76fb5
[]
no_license
biteytech/bufferstuff
ec57fa0e81a9f51ef90c432d63037a04b0c01297
0601f778cff54b9f89b2862a7889ce777fe80843
refs/heads/master
2021-11-17T22:21:00.183880
2021-10-04T03:59:56
2021-10-04T05:15:36
220,116,668
0
0
null
null
null
null
UTF-8
Java
false
false
10,566
java
package tech.bitey.bufferstuff; import java.nio.DoubleBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.util.Comparator; import java.util.Spliterator; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; public class BufferSpliterators { /** * A Spliterator.OfInt designed for use by sources that traverse and split * elements maintained in an unmodifiable {@link IntBuffer}. * <p> * Based on {@code Spliterators.IntArraySpliterator} */ public static final class IntBufferSpliterator implements Spliterator.OfInt { private final IntBuffer buffer; private int index; // current index, modified on advance/split private final int fence; // one past last index private final int characteristics; /** * Creates a spliterator covering all of the given {@link IntBuffer}. * <p> * <b>Note:</b> ignores {@link IntBuffer#position() position} and * {@link IntBuffer#limit() limit}, can pass a {@link IntBuffer#slice() slice} * instead. * * @param buffer the buffer, assumed to be unmodified during * use * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public IntBufferSpliterator(IntBuffer buffer, int additionalCharacteristics) { this(buffer, 0, buffer.capacity(), additionalCharacteristics); } /** * Creates a spliterator covering the given {@link IntBuffer} and range. * * @param buffer the buffer, assumed to be unmodified during * use * @param origin the least index (inclusive) to cover * @param fence one past the greatest index to cover * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public IntBufferSpliterator(IntBuffer buffer, int origin, int fence, int additionalCharacteristics) { this.buffer = buffer; this.index = origin; this.fence = fence; this.characteristics = additionalCharacteristics | Spliterator.SIZED | Spliterator.SUBSIZED; } @Override public OfInt trySplit() { int lo = index, mid = (lo + fence) >>> 1; return (lo >= mid) ? null : new IntBufferSpliterator(buffer, lo, index = mid, characteristics); } @Override public void forEachRemaining(IntConsumer action) { IntBuffer b; int i, hi; // hoist accesses and checks from loop if (action == null) throw new NullPointerException(); if ((b = buffer).capacity() >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) { do { action.accept(b.get(i)); } while (++i < hi); } } @Override public boolean tryAdvance(IntConsumer action) { if (action == null) throw new NullPointerException(); if (index >= 0 && index < fence) { action.accept(buffer.get(index++)); return true; } return false; } @Override public long estimateSize() { return fence - index; } @Override public int characteristics() { return characteristics; } @Override public Comparator<? super Integer> getComparator() { if (hasCharacteristics(Spliterator.SORTED)) return null; throw new IllegalStateException(); } } /** * A Spliterator.OfLong designed for use by sources that traverse and split * elements maintained in an unmodifiable {@link LongBuffer}. * <p> * Based on {@code Spliterators.LongArraySpliterator} */ public static final class LongBufferSpliterator implements Spliterator.OfLong { private final LongBuffer buffer; private int index; // current index, modified on advance/split private final int fence; // one past last index private final int characteristics; /** * Creates a spliterator covering all of the given {@link LongBuffer}. * <p> * <b>Note:</b> ignores {@link LongBuffer#position() position} and * {@link LongBuffer#limit() limit}, can pass a {@link LongBuffer#slice() slice} * instead. * * @param buffer the buffer, assumed to be unmodified during * use * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public LongBufferSpliterator(LongBuffer buffer, int additionalCharacteristics) { this(buffer, 0, buffer.capacity(), additionalCharacteristics); } /** * Creates a spliterator covering the given {@link LongBuffer} and range. * * @param buffer the buffer, assumed to be unmodified during * use * @param origin the least index (inclusive) to cover * @param fence one past the greatest index to cover * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public LongBufferSpliterator(LongBuffer buffer, int origin, int fence, int additionalCharacteristics) { this.buffer = buffer; this.index = origin; this.fence = fence; this.characteristics = additionalCharacteristics | Spliterator.SIZED | Spliterator.SUBSIZED; } @Override public OfLong trySplit() { int lo = index, mid = (lo + fence) >>> 1; return (lo >= mid) ? null : new LongBufferSpliterator(buffer, lo, index = mid, characteristics); } @Override public void forEachRemaining(LongConsumer action) { LongBuffer b; int i, hi; // hoist accesses and checks from loop if (action == null) throw new NullPointerException(); if ((b = buffer).capacity() >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) { do { action.accept(b.get(i)); } while (++i < hi); } } @Override public boolean tryAdvance(LongConsumer action) { if (action == null) throw new NullPointerException(); if (index >= 0 && index < fence) { action.accept(buffer.get(index++)); return true; } return false; } @Override public long estimateSize() { return fence - index; } @Override public int characteristics() { return characteristics; } @Override public Comparator<? super Long> getComparator() { if (hasCharacteristics(Spliterator.SORTED)) return null; throw new IllegalStateException(); } } /** * A Spliterator.OfDouble designed for use by sources that traverse and split * elements maintained in an unmodifiable {@link DoubleBuffer}. * <p> * Based on {@code Spliterators.DoubleArraySpliterator} */ public static final class DoubleBufferSpliterator implements Spliterator.OfDouble { private final DoubleBuffer buffer; private int index; // current index, modified on advance/split private final int fence; // one past last index private final int characteristics; /** * Creates a spliterator covering all of the given {@link DoubleBuffer}. * <p> * <b>Note:</b> ignores {@link DoubleBuffer#position() position} and * {@link DoubleBuffer#limit() limit}, can pass a {@link DoubleBuffer#slice() * slice} instead. * * @param buffer the buffer, assumed to be unmodified during * use * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public DoubleBufferSpliterator(DoubleBuffer buffer, int additionalCharacteristics) { this(buffer, 0, buffer.capacity(), additionalCharacteristics); } /** * Creates a spliterator covering the given {@link DoubleBuffer} and range. * * @param buffer the buffer, assumed to be unmodified during * use * @param origin the least index (inclusive) to cover * @param fence one past the greatest index to cover * @param additionalCharacteristics Additional spliterator characteristics of * this spliterator's source or elements beyond * {@code SIZED} and {@code SUBSIZED} which are * are always reported */ public DoubleBufferSpliterator(DoubleBuffer buffer, int origin, int fence, int additionalCharacteristics) { this.buffer = buffer; this.index = origin; this.fence = fence; this.characteristics = additionalCharacteristics | Spliterator.SIZED | Spliterator.SUBSIZED; } @Override public OfDouble trySplit() { int lo = index, mid = (lo + fence) >>> 1; return (lo >= mid) ? null : new DoubleBufferSpliterator(buffer, lo, index = mid, characteristics); } @Override public void forEachRemaining(DoubleConsumer action) { DoubleBuffer b; int i, hi; // hoist accesses and checks from loop if (action == null) throw new NullPointerException(); if ((b = buffer).capacity() >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) { do { action.accept(b.get(i)); } while (++i < hi); } } @Override public boolean tryAdvance(DoubleConsumer action) { if (action == null) throw new NullPointerException(); if (index >= 0 && index < fence) { action.accept(buffer.get(index++)); return true; } return false; } @Override public long estimateSize() { return fence - index; } @Override public int characteristics() { return characteristics; } @Override public Comparator<? super Double> getComparator() { if (hasCharacteristics(Spliterator.SORTED)) return null; throw new IllegalStateException(); } } }
5ce0644ecdf62fa840fcb92d74370234adf3700d
f00a04bbd0aa66e8dd760122b6a8c7369623d927
/12_scalable/src/test/java/one/diao/com/a12_scalable/ExampleUnitTest.java
8e31952e933e8ce9dedb2c89b1dba183952f615c
[]
no_license
onebee/Pomelo
4b98299bf864467ed568d80b657cf7f9f4a29b71
5a2475ce5eb3f58235f58f5700a32e7be0b27a7c
refs/heads/master
2021-07-09T17:58:45.192751
2020-06-26T07:03:49
2020-06-26T07:03:49
154,244,745
1
0
null
null
null
null
UTF-8
Java
false
false
386
java
package one.diao.com.a12_scalable; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
44292fe2c4dbd8af4d6777da817183c9502c68fc
abf44b5cb797f06add36c920e5532223d1a7cb74
/gen/com/websiteinstantly/flashlight/R.java
88049c488e3d7548e3377875124e52c4d32385c8
[]
no_license
constzi/Flashlight
386905e2b3ccc156983b034b0d3ac96a831dfe4a
61118134764d62344371774961b272b75fc0a023
refs/heads/master
2021-01-15T12:19:05.993708
2012-08-17T22:32:50
2012-08-17T22:32:50
5,458,226
1
0
null
null
null
null
UTF-8
Java
false
false
1,156
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.websiteinstantly.flashlight; public final class R { public static final class attr { } public static final class drawable { public static final int flashlight=0x7f020000; public static final int ic_launcher=0x7f020001; public static final int lightoff=0x7f020002; public static final int lighton=0x7f020003; } public static final class id { public static final int adMain=0x7f050000; public static final int off_btn=0x7f050003; public static final int on_btn=0x7f050001; public static final int surfaceview=0x7f050005; public static final int textView1=0x7f050002; public static final int textView2=0x7f050004; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }
98737e0412c7fa74ef21458139ee2b82dedfdb97
d81685abc1f8ae1cdbfedef32f634954ee67ac16
/_src/Spring Boot - Getting Started_Code/Section 6/l1-6.1-after-section-validation-model/src/test/java/com/packtpub/yummy/rest/BookmarkControllerTest.java
ecf2c9114c0c32655f6074d1bd4bd9fb54a62b35
[ "Apache-2.0" ]
permissive
paullewallencom/spring-978-1-7882-9863-6
96b15102b730fac27a2b31437f4e392b0980619d
b669cf5fa25e6cf045e61fad5541317155f4dfa6
refs/heads/main
2023-02-04T15:16:39.751100
2020-12-27T19:09:45
2020-12-27T19:09:45
319,188,046
0
0
null
null
null
null
UTF-8
Java
false
false
6,234
java
package com.packtpub.yummy.rest; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.packtpub.yummy.model.Bookmark; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.hateoas.Resource; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @Transactional public class BookmarkControllerTest { @Autowired MockMvc mvc; @Autowired ObjectMapper mapper; @Test public void getABookmark() throws Exception { Bookmark input = getSimpleBookmark(); String location = addBookmark(input); Resource<Bookmark> output = getBookmark(location); assertNotNull(output.getContent().getUrl()); assertEquals(input.getUrl(), output.getContent().getUrl()); } @Test public void deleteABookmark() throws Exception { Bookmark input = getSimpleBookmark(); String location = addBookmark(input); mvc.perform( delete(location).accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") ).andDo(print()).andExpect(status().isGone()); mvc.perform( get(location).accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") ).andDo(print()).andExpect(status().isNotFound()); } @Test public void deleteABookmarkTwiceYieldsNotModified() throws Exception { Bookmark input = getSimpleBookmark(); String location = addBookmark(input); mvc.perform( delete(location).accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") ).andDo(print()).andExpect(status().isGone()); mvc.perform( delete(location).accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") ).andDo(print()).andExpect(status().isNotModified()); } @Test public void updateABookmark() throws Exception { Bookmark input = getSimpleBookmark(); String location = addBookmark(input); Resource<Bookmark> output = getBookmark(location); String result = mvc.perform( post(output.getId().getHref()) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") .content(mapper.writeValueAsString(output.getContent().withUrl("http://kulinariweb.de"))) ).andDo(print()).andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); output = mapper.readValue(result, new TypeReference<Resource<Bookmark>>() { }); assertEquals("http://kulinariweb.de", output.getContent().getUrl()); } @Test public void updateABookmarkStaleFails() throws Exception { Bookmark input = getSimpleBookmark(); String location = addBookmark(input); Resource<Bookmark> output = getBookmark(location); mvc.perform( post(output.getId().getHref()) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") .content(mapper.writeValueAsString(output.getContent().withUrl("http://kulinariweb.de"))) ).andDo(print()).andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); mvc.perform( post(output.getId().getHref()) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept("application/hal+json;charset=UTF-8","application/json;charset=UTF-8") .content(mapper.writeValueAsString(output.getContent().withUrl("http://kulinariweb2.de"))) ).andDo(print()).andExpect(status().isConflict()); } @Test public void updateABookmarkFailWrongId() throws Exception { Bookmark input = getSimpleBookmark(); mvc.perform( post("/bookmark/" + UUID.randomUUID()) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept("application/hal+json;charset=UTF-8", "application/json;charset=UTF-8") .content(mapper.writeValueAsString(input)) ) .andDo(print()) .andExpect(status().isNotFound()); } private Bookmark getSimpleBookmark() { return new Bookmark("Packt publishing", "http://packtpub.com"); } private Resource<Bookmark> getBookmark(String location) throws Exception { String result = mvc.perform( get(location) .accept("application/hal+json;charset=UTF-8", "application/json;charset=UTF-8") ).andDo(print()) .andReturn().getResponse().getContentAsString(); return mapper.readValue(result, new TypeReference<Resource<Bookmark>>() { }); } private String addBookmark(Bookmark input) throws Exception { return mvc.perform( post("/bookmarks") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(mapper.writeValueAsString(input)) ).andDo(print()).andExpect(status().isCreated()) .andReturn().getResponse().getHeader("Location"); } }
6b6e9721b0a26a3029ef8d5ab311add5f5f2e1c0
96e0272e8e8052f4060d17f0538370beed6d0d55
/app/src/main/java/com/buaa/tezlikai/smartsh/utils/bitmap/MemoryCacheUtils.java
a9f2a14f2b28492635d30b9bb7e7aea7a63be868
[]
no_license
tezlikai/SmartSH
3fbcffdeaeb34d4ab1cadc29426e1b8d457f64c8
3f3def55fc10589b2461ee973cc44a49ebf77083
refs/heads/master
2021-01-01T03:46:52.434387
2016-04-19T11:31:52
2016-04-19T11:31:52
56,510,986
0
0
null
null
null
null
UTF-8
Java
false
false
1,514
java
package com.buaa.tezlikai.smartsh.utils.bitmap; import android.graphics.Bitmap; import android.support.v4.util.LruCache; /** * 内存缓存工具类 */ public class MemoryCacheUtils { // private HashMap<String, SoftReference<Bitmap>> mMemroyCache = new // HashMap<String, SoftReference<Bitmap>>(); // Android 2.3 (API Level // 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠,建议用LruCache private LruCache<String, Bitmap> mCache; public MemoryCacheUtils() { int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取虚拟机分配的最大内存 // 16M // LRU 最近最少使用, 通过控制内存不要超过最大值(由开发者指定), 来解决内存溢出 mCache = new LruCache<String, Bitmap>(maxMemory / 8) { @Override protected int sizeOf(String key, Bitmap value) { // 计算一个bitmap的大小 int size = value.getRowBytes() * value.getHeight();// 每一行的字节数乘以高度 return size; } }; } public Bitmap getBitmapFromMemory(String url) { // SoftReference<Bitmap> softReference = mMemroyCache.get(url); // if (softReference != null) { // Bitmap bitmap = softReference.get(); // return bitmap; // } return mCache.get(url); } public void setBitmapToMemory(String url, Bitmap bitmap) { // SoftReference<Bitmap> soft = new SoftReference<Bitmap>(bitmap); // mMemroyCache.put(url, soft); mCache.put(url, bitmap); } }
[ "tezlikai163.com" ]
tezlikai163.com
703c665400b06150167427dd33f603580deb8085
e5bd0b75ba54e2a2ce407bba1649f852cf2e5dae
/src/main/java/com/feizi/utils/RegexUtils.java
1514d0799859812cc22a85b6ea1008b2b16a3003
[]
no_license
indrajithbandara/webSpider
c18f524f15d37244c3939079c7ca0599ee1f0170
10acfdc04710bd28968ee26d91f02f656a172564
refs/heads/master
2021-05-10T21:43:48.368368
2016-01-13T06:28:45
2016-01-13T06:28:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,720
java
package com.feizi.utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 正则表达式工具类 * @author ljj * @time 2015年10月22日 下午8:59:35 * TODO */ public final class RegexUtils { private static String ROOT_URL_REGEX = "(http://.*?/)"; private static String CURRENT_URL_REGEX = "(http://.*/)"; private static String CHINESE_REGEX = "([\u4e00-\u9fa5]+)"; /** * 构造方法私有,防止实例化 */ private RegexUtils(){ } /** * 正则匹配结果,每条记录用splitStr进行分割 * @param dealStr * @param regexStr * @param splitStr * @param n * @return */ public static String getString(String dealStr, String regexStr, String splitStr, int n){ String reStr = ""; if(null == dealStr || null == regexStr || n < 1 || dealStr.isEmpty()){ return reStr; } splitStr = (null == splitStr) ? "" : splitStr; Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); StringBuffer stringBuffer = new StringBuffer(); while(matcher.find()){ stringBuffer.append(matcher.group(n).trim()); stringBuffer.append(splitStr); } reStr = stringBuffer.toString(); if("" != splitStr && reStr.endsWith(splitStr)){ reStr = reStr.substring(0, reStr.length() - splitStr.length()); } return reStr; } /** * 正则匹配结果,将所有匹配记录组装成字符串 * @param dealStr * @param regexStr * @param n * @return */ public static String getString(String dealStr, String regexStr, int n){ return getString(dealStr, regexStr, null, n); } /** * 正则匹配第一条结果 * @param dealStr * @param regexStr * @param n * @return */ public static String getFirstString(String dealStr, String regexStr, int n){ if(null == dealStr || null == regexStr || n < 1 || dealStr.isEmpty()){ return ""; } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ return matcher.group(n).trim(); } return ""; } /** * 正则匹配结果,将匹配结果组装成数组 * @param dealStr * @param regexStr * @param n * @return */ public static List<String> getList(String dealStr, String regexStr, int n){ List<String> reArrayList = new ArrayList<String>(); if(dealStr == null || regexStr == null || n < 1 || dealStr.isEmpty()){ return reArrayList; } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ reArrayList.add(matcher.group(n).trim()); } return reArrayList; } /** * 组装网址,网页的URL * @param url * @param currentUrl * @return */ private static String getHttpUrl(String url, String currentUrl){ try { url = encodeUrlCh(url); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if(url.indexOf("http") == 0){ return url; } if(url.indexOf("/") == 0){ return getFirstString(currentUrl, ROOT_URL_REGEX, 1) + url.substring(1); } return getFirstString(currentUrl, CURRENT_URL_REGEX, 1) + url; } /** * 获取和正则匹配的绝对链接地址 * @param dealStr * @param regexStr * @param currentUrl * @param n * @return */ public static List<String> getArrayList(String dealStr, String regexStr, String currentUrl, int n){ List<String> reArrayList = new ArrayList<String>(); if(dealStr == null || regexStr == null || n < 1 || dealStr.isEmpty()){ return reArrayList; } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ reArrayList.add(getHttpUrl(matcher.group(n).trim(), currentUrl)); } return reArrayList; } /** * 将连接地址中的中文进行编码处理 * @param url * @return * @throws UnsupportedEncodingException */ public static String encodeUrlCh(String url) throws UnsupportedEncodingException{ while(true){ String s = getFirstString(url, CHINESE_REGEX, 1); if("".equals(s)){ return url; } url = url.replaceAll(s, URLEncoder.encode(s, "utf-8")); } } /** * 获取全部 * @param dealStr * @param regexStr * @param array 正则位置数组 * @return */ public static List<String[]> getListArray(String dealStr, String regexStr, int[] array){ List<String[]> reArrayList = new ArrayList<String[]>(); if(dealStr == null || regexStr == null || array == null){ return reArrayList; } for (int i = 0; i < array.length; i++) { if(array[i] < 1){ return reArrayList; } } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ String[] str = new String[array.length]; for (int i = 0; i < str.length; i++) { str[i] = matcher.group(array[i]).trim(); } reArrayList.add(str); } return reArrayList; } /** * 获取全部 * @param dealStr * @param regexStr * @param array * @return */ public static List<String> getStringArray(String dealStr, String regexStr, int[] array){ List<String> reStringList = new ArrayList<String>(); if(dealStr == null || regexStr == null || array == null){ return reStringList; } for (int i = 0; i < array.length; i++) { if(array[i] < 1){ return reStringList; } } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { sb.append(matcher.group(array[i]).trim()); } reStringList.add(sb.toString()); } return reStringList; } /** * 获取第一个 * @param dealStr * @param regexStr * @param array 正则位置数组 * @return */ public static String[] getFirstArray(String dealStr, String regexStr, int[] array){ if(dealStr == null || regexStr == null || array == null){ return null; } for (int i = 0; i < array.length; i++) { if(array[i] < 1){ return null; } } Pattern pattern = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(dealStr); while(matcher.find()){ String[] str = new String[array.length]; for (int i = 0; i < str.length; i++) { str[i] = matcher.group(i).trim(); } return str; } return null; } }
01206c886efe67e703b8ba8e954dc573442efbc5
f94efdcdd333a90b2a061fbb446486d78bbbc937
/src/test/java/nl/jqno/equalsverifier/internal/reflection/FieldIterableTest.java
7a5740c6f2bc62c8bfdc3615c898d8824ada4347
[ "Apache-2.0" ]
permissive
don-vip/equalsverifier
0ffa5284bcce9279665c69c5af5c851a946c5127
4f95598c49f7d5c35708012a2229f0cda312f55a
refs/heads/master
2020-03-30T07:04:17.238541
2018-10-07T11:54:22
2018-10-07T11:58:38
150,913,095
0
1
Apache-2.0
2018-09-30T00:10:34
2018-09-30T00:10:34
null
UTF-8
Java
false
false
6,123
java
package nl.jqno.equalsverifier.internal.reflection; import nl.jqno.equalsverifier.testhelpers.types.TypeHelper.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.lang.reflect.Field; import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class FieldIterableTest { private static final Set<Field> FIELD_CONTAINER_FIELDS = createFieldContainerFields(); private static final Set<Field> SUB_FIELD_CONTAINER_FIELDS = createSubFieldContainerFields(); private static final Set<Field> FIELD_AND_SUB_FIELD_CONTAINER_FIELDS = createFieldAndSubFieldContainerFields(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void simpleFields() { Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.of(DifferentAccessModifiersFieldContainer.class)) { actual.add(field); } assertEquals(FIELD_CONTAINER_FIELDS, actual); } @Test public void subAndSuperClassFields() { Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.of(DifferentAccessModifiersSubFieldContainer.class)) { actual.add(field); } assertEquals(FIELD_AND_SUB_FIELD_CONTAINER_FIELDS, actual); } @Test public void onlySubClassFields() { Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.ofIgnoringSuper(DifferentAccessModifiersSubFieldContainer.class)) { actual.add(field); } assertEquals(SUB_FIELD_CONTAINER_FIELDS, actual); } @Test public void noFields() { FieldIterable iterable = FieldIterable.of(NoFields.class); assertFalse(iterable.iterator().hasNext()); } @Test public void superHasNoFields() throws NoSuchFieldException { Set<Field> expected = new HashSet<>(); expected.add(NoFieldsSubWithFields.class.getField("field")); Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.of(NoFieldsSubWithFields.class)) { actual.add(field); } assertEquals(expected, actual); } @Test public void subHasNoFields() { Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.of(EmptySubFieldContainer.class)) { actual.add(field); } assertEquals(FIELD_CONTAINER_FIELDS, actual); } @Test public void classInTheMiddleHasNoFields() throws NoSuchFieldException { Set<Field> expected = new HashSet<>(); expected.addAll(FIELD_CONTAINER_FIELDS); expected.add(SubEmptySubFieldContainer.class.getDeclaredField("field")); Set<Field> actual = new HashSet<>(); for (Field field : FieldIterable.of(SubEmptySubFieldContainer.class)) { actual.add(field); } assertEquals(expected, actual); } @Test public void interfaceTest() { FieldIterable iterable = FieldIterable.of(Interface.class); assertFalse(iterable.iterator().hasNext()); } @Test public void nextAfterLastElement() { Iterator<Field> iterator = FieldIterable.of(DifferentAccessModifiersFieldContainer.class).iterator(); while (iterator.hasNext()) { iterator.next(); } thrown.expect(NoSuchElementException.class); iterator.next(); } @Test public void objectHasNoElements() { FieldIterable iterable = FieldIterable.of(Object.class); assertFalse(iterable.iterator().hasNext()); } @Test public void ignoreSyntheticFields() { FieldIterable iterable = FieldIterable.of(Outer.Inner.class); assertFalse(iterable.iterator().hasNext()); } @Test public void ignoreNonSyntheticCoberturaFields() { FieldIterable iterable = FieldIterable.of(CoberturaContainer.class); List<Field> fields = new ArrayList<>(); for (Field f : iterable) { fields.add(f); } assertEquals(1, fields.size()); assertEquals("i", fields.get(0).getName()); } private static Set<Field> createFieldContainerFields() { Set<Field> result = new HashSet<>(); Class<DifferentAccessModifiersFieldContainer> type = DifferentAccessModifiersFieldContainer.class; try { result.add(type.getDeclaredField("i")); result.add(type.getDeclaredField("j")); result.add(type.getDeclaredField("k")); result.add(type.getDeclaredField("l")); result.add(type.getDeclaredField("I")); result.add(type.getDeclaredField("J")); result.add(type.getDeclaredField("K")); result.add(type.getDeclaredField("L")); } catch (NoSuchFieldException e) { throw new IllegalStateException(e); } return result; } private static Set<Field> createSubFieldContainerFields() { Set<Field> result = new HashSet<>(); Class<DifferentAccessModifiersSubFieldContainer> type = DifferentAccessModifiersSubFieldContainer.class; try { result.add(type.getDeclaredField("a")); result.add(type.getDeclaredField("b")); result.add(type.getDeclaredField("c")); result.add(type.getDeclaredField("d")); } catch (NoSuchFieldException e) { throw new IllegalStateException(e); } return result; } private static Set<Field> createFieldAndSubFieldContainerFields() { Set<Field> result = new HashSet<>(); result.addAll(FIELD_CONTAINER_FIELDS); result.addAll(SUB_FIELD_CONTAINER_FIELDS); return result; } public static final class CoberturaContainer { // CHECKSTYLE: ignore StaticVariableName for 1 line. public static transient int[] __cobertura_counters; @SuppressWarnings("unused") private final int i; public CoberturaContainer(int i) { this.i = i; } } }
d387140daa6a597893516f40fa90d1a84c52d266
cd8471fedd6784ab8e7ad64f1aeb8e2aa00acb9f
/src/main/java/com/myfirstdemo/reactfullwebservice/todo/HardcodedService.java
3588b8be75ef38029155eda01f0fa86c6d625698
[]
no_license
Dineshgangwar123/reactfull-webservice-
deb8546ca5809c5a8749d3eac015e13d2aacffbf
a9d2ad2fba114a69c50c930b6c45770ff5021cc6
refs/heads/main
2023-03-29T20:33:56.439697
2021-03-24T11:20:56
2021-03-24T11:20:56
351,039,360
0
0
null
null
null
null
UTF-8
Java
false
false
1,548
java
package com.myfirstdemo.reactfullwebservice.todo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Service; @Service public class HardcodedService { private static List<Todo> todos = new ArrayList(); private static long id = 0; static { todos.add(new Todo(++id,"dinesh","working",new Date(), false) ); todos.add(new Todo(++id,"dinesh","not working",new Date(), false) ); todos.add(new Todo(++id,"dinesh","working tomorrow",new Date(), false) ); todos.add(new Todo(++id,"dinesh","going to play",new Date(), false) ); todos.add(new Todo(++id,"dinesh","Not Specified",new Date(), false) ); todos.add(new Todo(++id,"dinesh","Learning react ",new Date(), false) ); } public List<Todo> getAll(String username) { List<Todo> todobyUser= new ArrayList(); for(int i=0; i< todos.size(); i++) { if((todos.get(i).getUsername()).equals(username) ) { todobyUser.add(todos.get(i)); } } return todobyUser; } public Todo deleteTodo(long id) { Todo todo=findTodo(id); if(todo==null) { return null; } if(todos.remove(todo)) { return todo; } return null; } public Todo findTodo(long id2) { for(Todo todo:todos) { if(todo.getId()== id2) { return todo; } } return null; } public Todo saveTodo(Todo todo) { if(todo.getId()== 0 || todo.getId()== -1) { todo.setId(++id); todos.add(todo); } else { deleteTodo(todo.getId()); todos.add(todo); } return todo; } }
ee045f93144ddec47a1efc4eda829a36b2ffc1ec
e18a5883d937d81add3e5b16689bf43a36bf59a2
/nemo-renderers/cli-renderer/src/main/java/org/opendaylight/nemo/renderer/cli/CliTrigger.java
1d745e874c5eee8ec2754c775e8bc3a72dc95e54
[]
no_license
telefonicaid/vibnemo
76574c0e786f21f2116ec210bc52f7aeab1e9174
de6b47a0300384b936792a2084ba47d6e2164de4
refs/heads/master
2021-01-18T22:23:36.179487
2017-07-11T11:23:35
2017-07-11T11:23:35
87,051,238
0
1
null
null
null
null
UTF-8
Java
false
false
13,310
java
/* * Copyright (c) 2015 Huawei, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.nemo.renderer.cli; import com.google.common.base.Optional; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.controller.md.sal.binding.api.DataChangeListener; import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope; import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.physical.network.rev151010.PhysicalNetwork; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.physical.network.rev151010.physical.network.PhysicalNodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.physical.network.rev151010.physical.network.physical.nodes.PhysicalNode; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.virtual.network.rev151010.VirtualNetworks; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.virtual.network.rev151010.virtual.networks.VirtualNetwork; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.generic.virtual.network.rev151010.virtual.networks.VirtualNetworkKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.intent.mapping.result.rev151010.IntentVnMappingResults; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.intent.mapping.result.rev151010.VnPnMappingResults; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.intent.mapping.result.rev151010.intent.vn.mapping.results.UserIntentVnMapping; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.intent.mapping.result.rev151010.intent.vn.mapping.results.UserIntentVnMappingKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.intent.mapping.result.rev151010.vn.pn.mapping.results.UserVnPnMapping; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.nemo.common.rev151010.UserId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.nemo.engine.common.rev151010.VirtualNetworkId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.nemo.intent.rev151010.Users; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.nemo.intent.rev151010.users.User; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.nemo.intent.rev151010.users.UserKey; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author Shixing Liu */ public class CliTrigger implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(CliTrigger.class); private final DataBroker dataProvider; private ListenerRegistration<DataChangeListener> userVnPnMappingChangeListenerReg; private final CliBuilder cliBuilder; /** * * @param dataProvider */ public CliTrigger(DataBroker dataProvider) { super(); this.dataProvider = dataProvider; cliBuilder = new CliBuilder(dataProvider); // Register listener registerUserVnPnMappingListener(); LOG.info("Initialized CliTrigger."); } /** * */ private void registerUserVnPnMappingListener() { //build userVnPnMappingIid InstanceIdentifier<UserVnPnMapping> userVnPnMappingIid = InstanceIdentifier .builder(VnPnMappingResults.class) .child(UserVnPnMapping.class) .build(); //register userVnPnMappingChangeListenerReg = dataProvider.registerDataChangeListener( LogicalDatastoreType.CONFIGURATION, userVnPnMappingIid, new UserVnPnMappingChangeListener(), DataChangeScope.BASE); } /** * * @param userId * @return */ private User getUser(UserId userId) { ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<User> userIid = InstanceIdentifier.builder(Users.class) .child(User.class, new UserKey(userId)) .build(); Optional<User> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, userIid).get(); } catch (Exception e) { // TODO Auto-generated catch block LOG.error("Exception:",e); } if (result.isPresent()){ LOG.info("getUser OK"); return (result.get()); }else{ LOG.info("getUser ERROR"); return null; } } /** * * @param userId * @return */ private VirtualNetwork getVirtualNetwork(UserId userId) { VirtualNetworkId virtualNetworkId = new VirtualNetworkId(userId.getValue()); VirtualNetworkKey virtualNetworkKey = new VirtualNetworkKey(virtualNetworkId); ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<VirtualNetwork> virtualNetworkIid = InstanceIdentifier .builder(VirtualNetworks.class) .child(VirtualNetwork.class, virtualNetworkKey) .build(); Optional<VirtualNetwork> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, virtualNetworkIid).get(); } catch (Exception e) { // TODO Auto-generated catch block LOG.error("Exception:",e); } if (result.isPresent()) { LOG.info("getVirtualNetwork OK"); return (result.get()); }else{ LOG.info("getVirtualNetwork ERROR"); return null; } } /** * * @param userId * @return */ private UserIntentVnMapping getUserIntentVnMapping(UserId userId) { ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<UserIntentVnMapping> userIntentVnMappingIid = InstanceIdentifier .builder(IntentVnMappingResults.class) .child(UserIntentVnMapping.class, new UserIntentVnMappingKey(userId)) .build(); Optional<UserIntentVnMapping> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, userIntentVnMappingIid).get(); } catch (Exception e) { // TODO Auto-generated catch block LOG.error("Exception:",e); } if (result.isPresent()) { LOG.info("getUserIntentVnMapping OK"); return (result.get()); }else{ LOG.info("getUserIntentVnMapping ERROR"); return null; } } /** * * @return */ private PhysicalNetwork getPhysicalNetwork() { ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<PhysicalNetwork> physicalNetworkIid = InstanceIdentifier .builder(PhysicalNetwork.class) .build(); Optional<PhysicalNetwork> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.OPERATIONAL, physicalNetworkIid).get(); } catch (Exception e) { // TODO Auto-generated catch block LOG.error("Exception:",e); } if (result.isPresent()) { LOG.info("getPhysicalNetwork OK"); return (result.get()); }else{ LOG.info("getPhysicalNetwork ERROR"); return null; } } /** * A listener implementation. */ private class UserVnPnMappingChangeListener implements DataChangeListener { @Override public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change) { if ( null == change ) { return; } System.out.println(); System.out.println("Data changed for UserVnPnMapping."); System.out.println(); Map<InstanceIdentifier<?>, DataObject> createdData = change.getCreatedData(); if ( null != createdData && !createdData.isEmpty() ) { for ( DataObject dataObject : createdData.values() ) { if ( dataObject instanceof UserVnPnMapping ) { LOG.info("Ready to call function to generate cli execution sequences for related devices."); UserVnPnMapping userVnPnMapping = (UserVnPnMapping)dataObject; UserId userId = userVnPnMapping.getUserId(); User user = getUser(userId); VirtualNetwork virtualNetwork = getVirtualNetwork(userId); UserIntentVnMapping userIntentVnMapping = getUserIntentVnMapping(userId); PhysicalNetwork physicalNetwork = getPhysicalNetwork(); if(null == physicalNetwork) { LOG.info("Physical Network data are not present."); return; } PhysicalNodes physicalNodes= physicalNetwork.getPhysicalNodes(); List<PhysicalNode> physicalNodeList = physicalNodes.getPhysicalNode(); cliBuilder.init(physicalNodeList); cliBuilder.updateCliExecutionSequence(user, virtualNetwork, userIntentVnMapping, userVnPnMapping, physicalNetwork); LOG.info("Already call cliBuilder.updateCliExecutionSequence()."); } } } Map<InstanceIdentifier<?>, DataObject> updatedData = change.getUpdatedData(); if ( null != updatedData && !updatedData.isEmpty() ) { for ( DataObject dataObject : updatedData.values() ) { if ( dataObject instanceof UserVnPnMapping ) { LOG.info("Ready to call function to generate cli execution sequences for related devices."); UserVnPnMapping userVnPnMapping = (UserVnPnMapping)dataObject; UserId userId = userVnPnMapping.getUserId(); // TODO: flowUtils.deleteFlowEntries(userId);?????? User user = getUser(userId); VirtualNetwork virtualNetwork = getVirtualNetwork(userId); UserIntentVnMapping userIntentVnMapping = getUserIntentVnMapping(userId); PhysicalNetwork physicalNetwork = getPhysicalNetwork(); if(physicalNetwork == null) { LOG.info("Physical Network data are not present."); return; } cliBuilder.updateCliExecutionSequence(user, virtualNetwork, userIntentVnMapping, userVnPnMapping, physicalNetwork); LOG.info("Already call cliBuilder.updateCliExecutionSequence()."); } } } Map<InstanceIdentifier<?>, DataObject> originalData = change.getOriginalData(); Set<InstanceIdentifier<?>> removedPaths = change.getRemovedPaths(); if ( null != removedPaths && !removedPaths.isEmpty() ) { DataObject dataObject; for ( InstanceIdentifier<?> instanceId : removedPaths ) { dataObject = originalData.get(instanceId); if ( null != dataObject && dataObject instanceof UserVnPnMapping ) { UserVnPnMapping userVnPnMapping = (UserVnPnMapping)dataObject; // TODO // flowUtils.deleteFlowEntries(userVnPnMapping.getUserId()); } } } return; } } @Override public void close() throws Exception { if ( null != this.userVnPnMappingChangeListenerReg ) { this.userVnPnMappingChangeListenerReg.close(); } if(null != this.cliBuilder){ this.cliBuilder.close(); } return; } }
d068b5741883b848b22be9c7704f3f8374e0ced9
0120c61841c98901617638430497807a456d205a
/graphComponent/Graph.java
e00bbca8d205d44056fc8a1abdbc27cbc4ed72c0
[]
no_license
PercipientCapital/Graph-Search-Arbitrage-Trading
ea52636d872fadd44a38867d7e1b6c7bd0dbc2fa
84115a2b509260a8eae1424f90d1f014757cb573
refs/heads/master
2023-03-16T17:41:36.893350
2020-07-07T13:21:16
2020-07-07T13:21:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,738
java
package graphComponent; import java.util.*; public class Graph { public Graph() { } public List<Node> bellmanFord(List<Edge> edgeList, List<Node> nodeList) { int nodeCount = nodeList.size(); // perform relaxation of all edges for nodeCount - 1 times for(int i = 0; i < nodeCount - 1; i++) { // relaxation for(Edge edge : edgeList) { Node startNode = edge.getFromNode(); if(startNode.getMinDistance() == Integer.MAX_VALUE) continue; double newDistance = startNode.getMinDistance() + edge.getWeight(); if(newDistance < edge.getToNode().getMinDistance()) { edge.getToNode().setMinDistance(newDistance); edge.getToNode().setPreviousNode(startNode); } } } List<Node> cycleList = new ArrayList<>(); // perform one more relaxation to detect negative cycle for(Edge edge : edgeList) { // if there is cycle then build the list of currencies for the cycle if(hasCycle(edge)) { Node node = edge.getFromNode(); while(!node.equals(edge.getToNode())) { cycleList.add(node); node = node.getPreviousNode(); } cycleList.add(edge.getToNode()); } } return cycleList; } // it has negative cycle if the edge can still be relaxed public boolean hasCycle(Edge edge) { double newDistance = edge.getFromNode().getMinDistance() + edge.getWeight(); return newDistance < edge.getToNode().getMinDistance(); } }
[ "https://github.com/JeviTan" ]
https://github.com/JeviTan
3d45f231b7a7902da24c3c4d8e0553c614a77a39
10d66875ff1433f26d4e7f16426cf63a549abed6
/app/src/main/java/com/doan/learnjapanese/DatabaseHelper.java
026db66bd47a257dde5486893cd1e437dd26f5c3
[]
no_license
DucGoody/LearnJapanese
12583ff4401a8482201202de53310d82090c2145
6c6a1cb0195036aa21eaa4cf433ce3ab087fd1f6
refs/heads/master
2021-07-21T01:22:27.774109
2017-10-31T15:06:24
2017-10-31T15:06:24
108,518,493
0
0
null
null
null
null
UTF-8
Java
false
false
2,377
java
package com.doan.learnjapanese; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class DatabaseHelper extends SQLiteOpenHelper { private final Context context; private SQLiteDatabase db; private static final String DB_NAME="tn1.sqlite"; private static final String DB_PATH="/data/data/com.doan.learnjapanese/databases/"+DB_NAME; private static final int VERSION =1; // phương thức khởi tạo 1 tham số public DatabaseHelper(Context context) { super(context, DB_NAME, null, VERSION); this.context=context; } // phương thức mở CSDL public SQLiteDatabase openDB(){ db=SQLiteDatabase.openDatabase(DB_PATH,null,SQLiteDatabase.OPEN_READWRITE); return db; } //phương thức đóng CSDL public void closeDB(){ db.close(); } //thực hiện câu lệnh SQL public void excuteSQL(String q){ openDB(); db.execSQL(q); closeDB(); } // thực hiện truy vấn trả về đối số public Cursor getCursor(String q){ openDB(); return db.rawQuery(q,null); } //sao chép CSDL public void copyDB(){ boolean check=false; try{ File file=new File(DB_PATH); check=file.exists(); if (check){ this.close(); } else if (!check){ this.getReadableDatabase(); InputStream input=context.getAssets().open(DB_NAME); String outFile=DB_PATH; OutputStream output=new FileOutputStream(outFile); byte[]buffer=new byte[1024]; int length; while((length=input.read(buffer))>0){ output.write(buffer,0,length); } output.flush(); output.close(); input.close(); } }catch (Exception e){e.printStackTrace();} } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
3c77942dbeb3dce10289e91c0118e7b8863a46ea
9355a88d487fadd42646f66f03a71174a81e1b66
/src/main/java/cn/smartpolice/workbean/UIUserNode.java
20913c2c135b34c7cd922a8a9495a096fa0bb6c5
[]
no_license
maxiaolin3366/NewSmartPolice
2164a84cf261d2d6f7f2ea8dee9a7b9a0f5f9890
a8456d64556b50d12e32881e0e23d1f3cef11c3e
refs/heads/master
2020-04-28T08:15:12.489237
2019-04-22T08:02:08
2019-04-22T08:02:08
175,119,996
0
0
null
null
null
null
UTF-8
Java
false
false
838
java
package cn.smartpolice.workbean; import org.springframework.stereotype.Component; import java.util.Date; @Component public class UIUserNode { private String ip; private String userType; private Date loginTime; private String username; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
9dfd54a885cf3fb9047bebc4c3a6baaf8f418756
4f662bc759b257ce622996eb04872df44816063b
/web_project_ajax/src/allen/ajax/servlet/CityServlet.java
7d3b4e1aacee16abeeab3386a60611b70c1a56f0
[]
no_license
Allenwll/JavaEE
3e8f9e762cdcfa72e26ce37bfdb5612fafb01cf3
17389d975ff44c1628924f2fb37d3a7f995627db
refs/heads/master
2020-04-02T21:41:55.443364
2018-10-26T09:23:23
2018-10-26T09:23:23
154,808,747
0
0
null
null
null
null
UTF-8
Java
false
false
2,807
java
/** * */ package allen.ajax.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** * @author Allen * * Title: CityServlet * * Description:市 * * Company: * * @date 2016年9月18日 上午10:36:12 * * Email:1303542271 @qq.com */ public class CityServlet extends HttpServlet { /** * 序列化 */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置编码格式 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // response.setHeader("content-type", "text/html;charset=utf-8"); // 获取前端参数 String pCode = request.getParameter("pCode"); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); // 判断 if (pCode.equals("001")) { Map<String, String> c1 = new HashMap<String, String>(); c1.put("name", "石家庄"); c1.put("code", "001001"); Map<String, String> c2 = new HashMap<String, String>(); c2.put("name", "保定"); c2.put("code", "001002"); Map<String, String> c3 = new HashMap<String, String>(); c3.put("name", "张家口"); c3.put("code", "001003"); list.add(c1); list.add(c2); list.add(c3); } else if (pCode.equals("002")) { Map<String, String> c1 = new HashMap<String, String>(); c1.put("name", "海淀区"); c1.put("code", "002001"); Map<String, String> c2 = new HashMap<String, String>(); c2.put("name", "朝阳区"); c2.put("code", "002002"); Map<String, String> c3 = new HashMap<String, String>(); c3.put("name", "昌平区"); c3.put("code", "002003"); list.add(c1); list.add(c2); list.add(c3); } else if (pCode.equals("003")) { Map<String, String> c1 = new HashMap<String, String>(); c1.put("name", "郑州市"); c1.put("code", "003001"); Map<String, String> c2 = new HashMap<String, String>(); c2.put("name", "新乡市"); c2.put("code", "003002"); Map<String, String> c3 = new HashMap<String, String>(); c3.put("name", "洛阳市"); c3.put("code", "003003"); list.add(c1); list.add(c2); list.add(c3); } //设置编码格式 response.setContentType("text/html;charset=utf-8"); //转换成JSON格式 response.getWriter().println(new Gson().toJson(list)); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
ff6e9b8b43415253ef7d5e3dd7433c360a53c6af
c26d471ed3ed6b1d22c30da8e5b0669db383c5ab
/Parent-end-app/app/src/main/java/com/example/user/probbc/SCAdapter.java
9ef39ab9b6f03ea1b938b402c0e3e59a7de91e20
[]
no_license
harshadshinde22/Parent-end-AndroidApp-communicating-with-BusApp
2ebc6d53ea5d24647cdc8975110cfb0664eeb4ed
13c82e6b1522e26fc03b060138663ee5cfb39dc4
refs/heads/master
2021-01-12T23:09:15.045732
2016-11-04T16:29:42
2016-11-04T16:29:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,051
java
package com.example.user.probbc; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Created by Harshad Shinde on 29-01-2016. */ public class SCAdapter extends BaseAdapter{ private final Activity context; private ArrayList<StudentStatusModel> list; public SCAdapter(Context c,ArrayList<StudentStatusModel> list) { context = (Activity) c; this.list = list; } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } @Override public int getViewTypeCount() { return super.getViewTypeCount(); } @Override public long getItemId(int position) { return position; } @Override public int getCount() { return this.list.size(); } @Override public Object getItem(int position) { return this.list.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.row_layout, null, true); ImageView pic = (ImageView) rowView.findViewById(R.id.pic); TextView name = (TextView) rowView.findViewById(R.id.name); TextView status = (TextView) rowView.findViewById(R.id.s_childStatus); name.setText(list.get(position).getStudentName()); status.setText(list.get(position).getStudentStatus()); return rowView; } }
b549afb6fb4b11e2707391b99e8a12ae29f02b70
ddf0d861a600e9271198ed43be705debae15bafd
/src/BinaryTree/dataStructure/BinaryTree.java
55a0d41e2181c2902a8601ae9396171f7d704174
[]
no_license
bibhuty-did-this/MyCodes
79feea385b055edc776d4a9d5aedbb79a9eb55f4
2b8c1d4bd3088fc28820145e3953af79417c387f
refs/heads/master
2023-02-28T09:20:36.500579
2021-02-07T17:17:54
2021-02-07T17:17:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,449
java
package BinaryTree.dataStructure; /** * Tree: * * ~ Some common terms in the trees are as follows: * 1. Root * 2. Child/children * 3. Parent * * ~ Why trees? * 1. Storing hierarchical data * 2. Moderate access/search timing(AVL and Red-Black trees) * 3. Moderate insertion/deletion timing(AVL and Red-Black trees) * 4. No upper limit on number of nodes * * ~ Application of trees are as follows: * 1. Using it in router algorithms */ /** * Binary Tree: * * ~ A tree which has at most 2 children * * ~ Properties of Binary Tree are as follows: * 1. Maximum no of nodes at any level 'l' is 2^(l-1) * 2. Maximum no of nodes in a binary tree of height h is 2^h - 1 * 3. Minimum possible height of a binary tree with N nodes is log2(N+1) * 4. Maximum possible height of a binary tree with N nodes is N * 5. Binary tree with L leaves have at least log2(L+1) levels * 6. No of leaf nodes = No of internal nodes with 2 children + 1 * * ~ Types of Binary Tree are as follows: * 1. Full binary tree: Each and every node has 0 or 2 children * 2. Complete binary tree: All levels are completely filled except for the last level * 3. Perfect binary tree: All internal nodes have 2 children and all leaves are at the same level * 4. Balanced binary tree: Height of the tree is log2(n) where n is the number of nodes(AVL tree and Red-Black tree) * 5. Degenerate or pathological binary tree: Every internal node has 1 child * * ~ Handshaking lemma and related properties: * 1. sum of degree of vertices = 2*(no of edges) * 2. number of vertices with odd degree is always even * 3. for a k ary tree: no of leaf nodes = (k-1)*(no of internal nodes with k nodes) + 1 */ public class BinaryTree{ static class Node{ int data; Node left,right; public Node(int data){ this.data=data; left=right=null; } } static Node root; public BinaryTree(int data){ root=new Node(data); } public BinaryTree(){ root=null; } public static void main(String[] args){ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); } }
7924b2b0544e897252ee38c2c41b245ccd2008e1
2f4a058ab684068be5af77fea0bf07665b675ac0
/utils/com/facebook/pages/identity/module/PageIdentityModule$FetchPageIdentityDataMethodProvider.java
ae6490878316a6cc64af2d588b405ed6cfd8e425
[]
no_license
cengizgoren/facebook_apk_crack
ee812a57c746df3c28fb1f9263ae77190f08d8d2
a112d30542b9f0bfcf17de0b3a09c6e6cfe1273b
refs/heads/master
2021-05-26T14:44:04.092474
2013-01-16T08:39:00
2013-01-16T08:39:00
8,321,708
1
0
null
null
null
null
UTF-8
Java
false
false
896
java
package com.facebook.pages.identity.module; import android.content.res.Resources; import com.facebook.graphql.common.GraphQLHelper; import com.facebook.orca.inject.AbstractProvider; import com.facebook.pages.identity.protocol.FetchPageIdentityDataMethod; class PageIdentityModule$FetchPageIdentityDataMethodProvider extends AbstractProvider<FetchPageIdentityDataMethod> { private PageIdentityModule$FetchPageIdentityDataMethodProvider(PageIdentityModule paramPageIdentityModule) { } public FetchPageIdentityDataMethod a() { return new FetchPageIdentityDataMethod((Resources)b(Resources.class), (GraphQLHelper)b(GraphQLHelper.class)); } } /* Location: /data1/software/apk2java/dex2jar-0.0.9.12/secondary-1.dex_dex2jar.jar * Qualified Name: com.facebook.pages.identity.module.PageIdentityModule.FetchPageIdentityDataMethodProvider * JD-Core Version: 0.6.2 */
d7641ef035525488907924ed8c3b9969f63f004e
b930d6eb78fa5ee782db9904fcd9c11ac46f4cef
/MapReduce/src/main/java/com/atguigu/teacher3/comparable/CMapper.java
b85eb3874ba98470ef770449df371d4c9ca13033
[]
no_license
zj1016875513/first_Maven
16a3ce76977568c67637a6f9d03750e98b9f381b
29ff84891a3ca1a08e3900f2286359a7027a9ea6
refs/heads/master
2023-07-12T16:38:59.409555
2021-08-22T08:21:21
2021-08-22T08:21:21
398,750,346
0
0
null
null
null
null
UTF-8
Java
false
false
813
java
package com.atguigu.teacher3.comparable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; public class CMapper extends Mapper<LongWritable, Text,FlowBean,Text> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //将value转成String String line = value.toString(); //切割数据 String[] phoneInfo = line.split(" "); //封装K,V Text outValue = new Text(phoneInfo[0]); FlowBean outKey = new FlowBean(Long.parseLong(phoneInfo[1]), Long.parseLong(phoneInfo[2]) , Long.parseLong(phoneInfo[3])); //写出K,V context.write(outKey,outValue); } }
d34feaeef8eda371d9bd44a30ad1370b10c56513
5a2548432f325ed8f8a6dfc91741591b486a3fe8
/app/src/main/java/com/example/gding3/maindelivery/RecipeSend.java
3480ee2f477a35790f21206957f99d97040948d9
[]
no_license
firstdreamding/MapsApp
33ac902d7dea63427c41835dd8fcbc4fcc8cb4b7
fd4c908a7aa52db514a154a8814e0bc34c3a36ad
refs/heads/master
2020-04-09T17:06:58.641430
2018-12-13T19:02:45
2018-12-13T19:02:45
160,471,313
0
1
null
null
null
null
UTF-8
Java
false
false
2,114
java
package com.example.gding3.maindelivery; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class RecipeSend extends AppCompatActivity { OkHttpClient client; EditText username; EditText title; EditText recipetext; Button submitButton; private boolean isReached = false; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_send); client = new OkHttpClient(); title = (EditText) findViewById(R.id.titlerecipe); username = (EditText) findViewById(R.id.usernamerecipe); recipetext = (EditText) findViewById(R.id.submitrecipetext); submitButton = (Button) findViewById(R.id.submitrecipe); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Request request = new Request.Builder() .url("http://24.15.230.170/AddRecipe.php?authorid="+username.getText().toString().hashCode()+"&title=\"" + title.getText().toString() + "\"&recipetext=\"" + recipetext.getText().toString() + "\"") .build(); try { Response response = client.newCall(request).execute(); System.out.println(response.toString()); } catch (IOException e) { e.printStackTrace(); } finish(); } }); } }
0bbf6028eef77ec187901df6cd7787957973662e
b80c5461d1edafe7c7d7d820e6359c48b3d4817a
/automationqsp/src/webElementMethods/ClearMethod.java
8122e6438592096d735ec6c1e20089bec8d2e6e0
[]
no_license
SurajSelenium/NEWWCSM5
904e7dadf9a789869ca0ae9123ab155fe4cc0699
04df9bb650196ea646819534d4f9e3ddb2972d47
refs/heads/master
2023-09-04T00:22:38.928016
2021-10-17T04:36:36
2021-10-17T04:36:36
408,683,050
0
0
null
null
null
null
UTF-8
Java
false
false
1,378
java
package webElementMethods; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ClearMethod { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver","./drivers/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); Thread.sleep(3000); driver.get("https://opensource-demo.orangehrmlive.com/"); driver.findElement(By.id("txtUsername")).sendKeys("Admin"); driver.findElement(By.id("txtPassword")).sendKeys("admin123"); driver.findElement(By.id("btnLogin")).click(); Thread.sleep(3000); driver.findElement(By.xpath("//a[.='PIM']")).click(); Thread.sleep(1000); driver.findElement(By.xpath("//a[.='Add Employee']")).click(); Thread.sleep(2000); driver.findElement(By.id("firstName")).sendKeys("abc123"); driver.findElement(By.id("middleName")).sendKeys("xyz123"); driver.findElement(By.id("lastName")).sendKeys("jkl123"); Thread.sleep(3000); //use of clear to clear the text present in the textbox driver.findElement(By.id("employeeId")).clear(); driver.findElement(By.id("employeeId")).sendKeys("18"); driver.findElement(By.id("btnSave")).click(); } }
[ "HP@LAPTOP-SMC8HIAI" ]
HP@LAPTOP-SMC8HIAI
8397556a83975279650f66b9e9fc48d373b0d4dd
363ee22220f58d50e0363f6f326d3d57a53c8c0a
/gestioninventarioapirest/src/main/java/co/com/cidenet/sito/util/ConstanteServicioUsuarios.java
7e75b6d35492fd3126994b82b2d2ae04bcfb2485
[]
no_license
juanbeltran19/cidenet
bb8ef5114e3a649e57c1ee4588ed03b4de753aa4
cf866da0e4245e16f05b229173cc3902164c8d0e
refs/heads/master
2023-04-26T19:08:01.118509
2020-06-06T00:58:45
2020-06-06T00:58:45
269,822,184
0
0
null
2023-04-14T17:57:41
2020-06-06T00:45:36
JavaScript
UTF-8
Java
false
false
1,016
java
/** * Copyright (c) 2020 Cidenet * <br><A HREF=https://www.cidenet.com.co></a></br> * Todos los derechos reservados. */ package co.com.cidenet.sito.util; /** * Clase utilidad que se encarga de manejo valores constantes del servicio de * usuarios * * @version * @author juanpbeltran <br> * <b>Fecha de desarrollo : </b> 05/06/2020 <br> * <b>Fecha de modificacion : </b> 00/00/0000 */ public class ConstanteServicioUsuarios { public static final String CONSTANTE_NULL = null; public static final String CONSTANTE_OK = "OK"; public static final String CONSTANTE_ERROR = "ERROR"; public static final String CONS_MSG_USR = "El usuario no existe registrado en el sistema"; public static final String CONS_URL_USR_EMPLEADO = "http://localhost:8081/cidenetapp/pg/pricing/"; public static final String CONS_URL_USR_VENDEDOR = "http://localhost:8081/clientes.html"; private ConstanteServicioUsuarios() { throw new IllegalStateException("Utilidad ConstanteServicioUsuarios class"); } }
4207ea82be5a9246f287a5d998ee7b1b6bf3d1b6
6081c02663d322f24df58c5b9a05b0f719d93ff5
/Spring-Summary-JWS-client/src/main/java/com/fiberhome/endpoint/ObjectFactory.java
abcb56cee6b5e3e739a63a1bd63042cd546014c7
[]
no_license
SJunZhang/SpringBoot-Summary
71cc8ad85396a810d024812995d66de26d08adbe
558990e547643e3b25fe4efd07c5f1432e13a74f
refs/heads/master
2021-09-09T07:33:58.818089
2018-03-14T08:10:43
2018-03-14T08:10:43
115,466,902
0
2
null
null
null
null
UTF-8
Java
false
false
3,400
java
package com.fiberhome.endpoint; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.fiberhome.endpoint package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _MethodOfTestResponse_QNAME = new QName("http://endpoint.fiberhome.com/", "methodOfTestResponse"); private final static QName _MethodOfTest_QNAME = new QName("http://endpoint.fiberhome.com/", "methodOfTest"); private final static QName _Exception_QNAME = new QName("http://endpoint.fiberhome.com/", "Exception"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.fiberhome.endpoint * */ public ObjectFactory() { } /** * Create an instance of {@link MethodOfTestResponse } * */ public MethodOfTestResponse createMethodOfTestResponse() { return new MethodOfTestResponse(); } /** * Create an instance of {@link MethodOfTest } * */ public MethodOfTest createMethodOfTest() { return new MethodOfTest(); } /** * Create an instance of {@link Exception } * */ public Exception createException() { return new Exception(); } /** * Create an instance of {@link ResultValue } * */ public ResultValue createResultValue() { return new ResultValue(); } /** * Create an instance of {@link RequestValue } * */ public RequestValue createRequestValue() { return new RequestValue(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MethodOfTestResponse }{@code >}} * */ @XmlElementDecl(namespace = "http://endpoint.fiberhome.com/", name = "methodOfTestResponse") public JAXBElement<MethodOfTestResponse> createMethodOfTestResponse(MethodOfTestResponse value) { return new JAXBElement<MethodOfTestResponse>(_MethodOfTestResponse_QNAME, MethodOfTestResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link MethodOfTest }{@code >}} * */ @XmlElementDecl(namespace = "http://endpoint.fiberhome.com/", name = "methodOfTest") public JAXBElement<MethodOfTest> createMethodOfTest(MethodOfTest value) { return new JAXBElement<MethodOfTest>(_MethodOfTest_QNAME, MethodOfTest.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Exception }{@code >}} * */ @XmlElementDecl(namespace = "http://endpoint.fiberhome.com/", name = "Exception") public JAXBElement<Exception> createException(Exception value) { return new JAXBElement<Exception>(_Exception_QNAME, Exception.class, null, value); } }
4860503a2cc76dd92b416f778ddb2dd75008c38a
070a52381c75399da3d0f001cc97218a354bb7b7
/judges/JavaJudge.java
46de637c5cb7a412f50c1d05647c6895ecf218e9
[ "MIT" ]
permissive
THS-CompSci/nebulae
9ee5de0de675d27a665288f66fd6f4dd351bbd23
aa924c77a540e7f133da54a1ab8cb07f64723faa
refs/heads/master
2021-01-21T07:57:10.117027
2015-10-31T22:08:30
2015-10-31T22:08:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,128
java
import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.tools.JavaCompiler; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import javax.tools.ToolProvider; public class JavaJudge { public static void main(String[] args) { if (args.length != 3) { System.out.println("Internal error"); System.exit(-1); } String filePath = args[0]; String className = args[1]; int runTime = Integer.parseInt(args[2]); File codeFile = null; codeFile = new File(filePath + "/" + className + ".java"); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); File classFile = new File(filePath + "/"); try { classFile.createNewFile(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classFile)); } catch (IOException e) { System.out.println("Internal error"); System.exit(-1); } JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjects(codeFile)); if (!task.call()) { System.out.println("Compilation error"); System.exit(1); } URL[] classpaths = new URL[1]; try { classpaths[0] = new URL("file:///" + filePath + "/"); } catch (MalformedURLException e) { System.out.println("Internal error"); System.exit(-1); } URLClassLoader loader = new URLClassLoader(classpaths); try { Class<?> c = loader.loadClass(className); Method main = c.getMethod("main", String[].class); Thread th = new Thread(new Runnable() { @Override public void run() { try { String[] arguments = new String[0]; Object[] invokedArgs = { arguments }; main.invoke(c, invokedArgs); } catch (Throwable thr) { System.out.println("Runtime Error"); System.exit(2); } } }); th.setContextClassLoader(loader); ExecutorService es = Executors.newSingleThreadExecutor(); Future<?> future = es.submit(th); try { future.get(runTime, TimeUnit.SECONDS); } catch (TimeoutException e) { future.cancel(true); System.out.println("Timeout"); System.exit(3); } es.shutdownNow(); } catch (ClassNotFoundException e) { System.out.println("Internal error"); System.exit(-1); } catch (NoSuchMethodException e) { System.out.println("Internal error"); System.exit(-1); } catch (SecurityException e) { System.out.println("Internal error"); System.exit(-1); } catch (InterruptedException e) { System.out.println("Internal error"); System.exit(-1); } catch (ExecutionException e) { System.out.println("Internal error"); System.exit(-1); } } }
73fcec14274fb813c81fea3f4f4f440abde423b3
f24f9e57033a2480c2b118f38ab1b96673af2582
/app/src/main/java/hram/githubtrending/data/prefepences/SharedPreferencesHelper.java
9a57690e7c41a7bebc63326466558d792f7ee209
[]
no_license
hram/GitHubTrending
216c4e5c94bdc66c726c7daae75a170a56993bbb
6b4d83d452202f6e9d04238fa710c399b9dde844
refs/heads/master
2021-07-13T08:04:37.404001
2019-03-23T23:37:13
2019-03-23T23:37:13
84,002,884
1
1
null
2018-07-24T05:30:47
2017-03-05T21:17:39
HTML
UTF-8
Java
false
false
1,248
java
package hram.githubtrending.data.prefepences; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import com.google.gson.Gson; import hram.githubtrending.App; import hram.githubtrending.data.model.SearchParams; /** * @author Evgeny Khramov */ public class SharedPreferencesHelper implements PreferencesHelper { private static final String FILE_NAME = "preferences"; @NonNull private static final Gson GSON = new Gson(); @Override @NonNull public SearchParams getSearchParams() { return GSON.fromJson(pref().getString(SearchParams.class.getName(), GSON.toJson(SearchParams.createEmpty())), SearchParams.class); } @Override public void setSearchParams(@NonNull SearchParams params) { pref().edit().putString(SearchParams.class.getName(), GSON.toJson(params)).apply(); } @Override public void resetSearchParams() { setSearchParams(SearchParams.createEmpty()); } @Override public void clearAppData() { pref().edit().clear().apply(); } private static SharedPreferences pref() { return App.getInstance().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); } }
c2571be574c24ad8edfc58b58effcba482076797
311f1237e7498e7d1d195af5f4bcd49165afa63a
/sourcedata/poi-REL_3_0/src/scratchpad/src/org/apache/poi/hwpf/model/CHPBinTable.java
48c5a9d8b4865827f02cc7754e61215605b02086
[ "Apache-2.0" ]
permissive
DXYyang/SDP
86ee0e9fb7032a0638b8bd825bcf7585bccc8021
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
refs/heads/master
2023-01-11T02:29:36.328694
2019-11-02T09:38:34
2019-11-02T09:38:34
219,128,146
10
1
Apache-2.0
2023-01-02T21:53:42
2019-11-02T08:54:26
Java
UTF-8
Java
false
false
6,010
java
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hwpf.model; import java.util.List; import java.util.ArrayList; import java.io.OutputStream; import java.io.IOException; import org.apache.poi.poifs.common.POIFSConstants; import org.apache.poi.util.LittleEndian; import org.apache.poi.hwpf.model.io.*; import org.apache.poi.hwpf.sprm.SprmBuffer; /** * This class holds all of the character formatting properties. * * @author Ryan Ackley */ public class CHPBinTable { /** List of character properties.*/ protected ArrayList _textRuns = new ArrayList(); public CHPBinTable() { } /** * Constructor used to read a binTable in from a Word document. * * @param documentStream * @param tableStream * @param offset * @param size * @param fcMin */ public CHPBinTable(byte[] documentStream, byte[] tableStream, int offset, int size, int fcMin) { PlexOfCps binTable = new PlexOfCps(tableStream, offset, size, 4); int length = binTable.length(); for (int x = 0; x < length; x++) { GenericPropertyNode node = binTable.getProperty(x); int pageNum = LittleEndian.getInt(node.getBytes()); int pageOffset = POIFSConstants.BIG_BLOCK_SIZE * pageNum; CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage(documentStream, pageOffset, fcMin); int fkpSize = cfkp.size(); for (int y = 0; y < fkpSize; y++) { _textRuns.add(cfkp.getCHPX(y)); } } } public void adjustForDelete(int listIndex, int offset, int length) { int size = _textRuns.size(); int endMark = offset + length; int endIndex = listIndex; CHPX chpx = (CHPX)_textRuns.get(endIndex); while (chpx.getEnd() < endMark) { chpx = (CHPX)_textRuns.get(++endIndex); } if (listIndex == endIndex) { chpx = (CHPX)_textRuns.get(endIndex); chpx.setEnd((chpx.getEnd() - endMark) + offset); } else { chpx = (CHPX)_textRuns.get(listIndex); chpx.setEnd(offset); for (int x = listIndex + 1; x < endIndex; x++) { chpx = (CHPX)_textRuns.get(x); chpx.setStart(offset); chpx.setEnd(offset); } chpx = (CHPX)_textRuns.get(endIndex); chpx.setEnd((chpx.getEnd() - endMark) + offset); } for (int x = endIndex + 1; x < size; x++) { chpx = (CHPX)_textRuns.get(x); chpx.setStart(chpx.getStart() - length); chpx.setEnd(chpx.getEnd() - length); } } public void insert(int listIndex, int cpStart, SprmBuffer buf) { CHPX insertChpx = new CHPX(cpStart, cpStart, buf); if (listIndex == _textRuns.size()) { _textRuns.add(insertChpx); } else { CHPX chpx = (CHPX)_textRuns.get(listIndex); if (chpx.getStart() < cpStart) { CHPX clone = new CHPX(cpStart, chpx.getEnd(), chpx.getSprmBuf()); chpx.setEnd(cpStart); _textRuns.add(listIndex + 1, insertChpx); _textRuns.add(listIndex + 2, clone); } else { _textRuns.add(listIndex, insertChpx); } } } public void adjustForInsert(int listIndex, int length) { int size = _textRuns.size(); CHPX chpx = (CHPX)_textRuns.get(listIndex); chpx.setEnd(chpx.getEnd() + length); for (int x = listIndex + 1; x < size; x++) { chpx = (CHPX)_textRuns.get(x); chpx.setStart(chpx.getStart() + length); chpx.setEnd(chpx.getEnd() + length); } } public List getTextRuns() { return _textRuns; } public void writeTo(HWPFFileSystem sys, int fcMin) throws IOException { HWPFOutputStream docStream = sys.getStream("WordDocument"); OutputStream tableStream = sys.getStream("1Table"); PlexOfCps binTable = new PlexOfCps(4); // each FKP must start on a 512 byte page. int docOffset = docStream.getOffset(); int mod = docOffset % POIFSConstants.BIG_BLOCK_SIZE; if (mod != 0) { byte[] padding = new byte[POIFSConstants.BIG_BLOCK_SIZE - mod]; docStream.write(padding); } // get the page number for the first fkp docOffset = docStream.getOffset(); int pageNum = docOffset/POIFSConstants.BIG_BLOCK_SIZE; // get the ending fc int endingFc = ((PropertyNode)_textRuns.get(_textRuns.size() - 1)).getEnd(); endingFc += fcMin; ArrayList overflow = _textRuns; do { PropertyNode startingProp = (PropertyNode)overflow.get(0); int start = startingProp.getStart() + fcMin; CHPFormattedDiskPage cfkp = new CHPFormattedDiskPage(); cfkp.fill(overflow); byte[] bufFkp = cfkp.toByteArray(fcMin); docStream.write(bufFkp); overflow = cfkp.getOverflow(); int end = endingFc; if (overflow != null) { end = ((PropertyNode)overflow.get(0)).getStart() + fcMin; } byte[] intHolder = new byte[4]; LittleEndian.putInt(intHolder, pageNum++); binTable.addProperty(new GenericPropertyNode(start, end, intHolder)); } while (overflow != null); tableStream.write(binTable.toByteArray()); } }
009b3c5fbee4a727bf16f6d9bacf7d5eba0a9049
fa07532474d8bf67962ec3ec0a52c9a6492d7e26
/AccountManagement5System/app/src/main/java/com/example/accountmanagement5system/ServiceHandling.java
71199181b52546ee05185f4f18cee83481ac2b46
[]
no_license
tiennguyen0910200/HomeAndroid
7b617164ebb7c3c9b625d0906d4fa30233df8d15
301ed91139bd7509bc296e9f35280b20f40ca21b
refs/heads/master
2023-02-14T04:44:32.558178
2021-01-11T12:35:31
2021-01-11T12:35:31
328,658,071
0
0
null
null
null
null
UTF-8
Java
false
false
2,098
java
package com.example.accountmanagement5system; import android.util.Log; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; public class ServiceHandling { public final static int GET = 1; public final static int POST = 2; public <NameValuePair> String call(String url, int method, List<NameValuePair> params) { InputStream is = null; String response = null; try { // http client DefaultHttpClient httpClient = new DefaultHttpClient(); HttpEntity httpEntity = null; HttpResponse httpResponse = null; // Kiểm tra loại method là POST hay GET if (method == POST) { HttpPost httpPost = new HttpPost(url); // thêm tham số if (params != null) { httpPost.setEntity(new UrlEncodedFormEntity(params)); } httpResponse = httpClient.execute(httpPost); } else if (method == GET) { // thêm tham số vào url if (params != null) { String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; } HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); } httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (Exception ex) { Log.d("My error", ex.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); response = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error: " + e.toString()); } return response; } }
d211af9700d761a531ff0bce60b0398ff1ca9c4e
4157bbec9d353b3992a77dbcc807d37149dee9e1
/21_Stacks/opgave02_parenteser/test/MainAppParent.java
11d14c3e6888d4f54194e724fa048437f672bab0
[]
no_license
Mageofdavodo/PRO2_Test
0809c1779b465dca185b657d486c5739b4a70a6f
0e112d0baae49d4ed5dafd39ae04cb32b264ec90
refs/heads/master
2020-04-06T14:21:21.850090
2019-01-15T20:46:21
2019-01-15T20:46:21
157,537,844
0
0
null
null
null
null
UTF-8
Java
false
false
1,072
java
package test; import model.ArrayStack; public class MainAppParent { public static void main(String[] args) { String string = "(3+{5{99{*}}[23[{67}67]]})"; String string2 = "((3+{5{99{*}}[23[{67}67]]})"; System.out.println(checkParenteses(string)); System.out.println(checkParenteses(string2)); } public static boolean checkParenteses(String s) { ArrayStack<Character> stackChar = new ArrayStack<Character>(); for (int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case '(': stackChar.push(s.charAt(i)); break; case '{': stackChar.push(s.charAt(i)); break; case '[': stackChar.push(s.charAt(i)); break; case ')': if (stackChar.peek() == '(') { stackChar.pop(); } break; case '}': if (stackChar.peek() == '{') { stackChar.pop(); } break; case ']': if (stackChar.peek() == '[') { stackChar.pop(); } break; } } if (stackChar.isEmpty()) { return true; } else { return false; } } }
601e2d7a860e79bd08cb11def770ddfd68bde14c
02c28e0a97c15f20b3b5406ee5738122932887c1
/src/reading/lang/StringReading.java
be0386b27b78876fd13a2a15c896d85334520e9f
[]
no_license
fastso/algorithms
58934d1e633adc694172d726989951fb2d3a3628
c7dccffd9af22d456374c1063c0b4f6a38af7afe
refs/heads/master
2022-01-26T00:45:58.754938
2022-01-14T13:02:52
2022-01-14T13:02:52
172,016,988
0
0
null
null
null
null
UTF-8
Java
false
false
633
java
package reading.lang; public class StringReading { public static void main(String... args) { String s1 = "sample"; String s2 = new String("sample"); String s3 = s1; System.out.println(s1.getClass()); System.out.println("s1 | s2 | s3"); System.out.println(s1.hashCode() + " | " + s2.hashCode() + " | " + s3.hashCode()); System.out.println(s1.toString()+ " | " + s2.toString() + " | " + s3.toString()); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); System.out.println(s1 == s3); System.out.println(s1.equals(s3)); } }
45264d624ed99988ed442c918c411e150d82f0db
5c64a22ad10cef705b6bd59ebdf5789f1d729f95
/src/main/java/algorithms/recursion/RecursiveLinearSearch.java
3d6c95c49aaacb0dd512a0a9241f74b5587c9780
[]
no_license
annawyszomi/algorithms
173500650a6cd32df2047509da22131cbc6d3b8b
11b42e6cd8fb46de1a1f8d1612e8051e0c5a5b40
refs/heads/master
2022-07-07T19:11:10.709054
2022-06-30T06:19:26
2022-06-30T06:19:26
233,537,345
0
0
null
2020-10-13T18:48:44
2020-01-13T07:32:38
Java
UTF-8
Java
false
false
590
java
package algorithms.recursion; public class RecursiveLinearSearch { public static void main(String[] args) { // recursiveLinearSearch(new int[]{3,6,7,10,4,15,27},0,15); System.out.println(recursiveLinearSearch(new int[]{3,6,7,10,4,15,27},0,15)); } public static int recursiveLinearSearch(int[] a, int i, int x) { if (i > a.length - 1) { return -1; } else if (a[i] == x) { return i; } else { System.out.println("index at: " + i); return recursiveLinearSearch(a, i + 1, x); } } }
72aec245348611d1f6f119b6d76418c9f9e435ea
a253a15bb062a5841c2be1ffc0736e5211ae3dc7
/src/java/com/eternity/tech/service/impl/EmpServiceImpl.java
f45e0f602d656ce494969a2a23b05a9e4225b51b
[]
no_license
jchonker/yiyuTech
4ad0ea434054a52f2bf726999e76390d5d27de30
c091af6380ccb9014751ee78fadebd7a360d1266
refs/heads/master
2020-04-08T10:24:18.347638
2018-11-27T02:56:38
2018-11-27T02:56:38
159,267,449
0
0
null
null
null
null
UTF-8
Java
false
false
1,469
java
package com.eternity.tech.service.impl; import java.util.ArrayList; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.eternity.tech.mapper.EmpMapper; import com.eternity.tech.pojo.Emp; import com.eternity.tech.service.EmpService; @Service("empService") public class EmpServiceImpl implements EmpService { @Resource(name="empMapper") private EmpMapper empMapper; public void setEmpMapper(EmpMapper empMapper) { this.empMapper = empMapper; } //查询数据库中是否有用户名以及密码 public int selectUser(String username, String password) { empMapper.selectUser(username, password); return 0; } //根据指定的name查询所有的此用户的所有数据 public Emp selectAll(String name) { return empMapper.selectAll(name); } //查询emp表中所有用户名 public ArrayList<String> selectAllName() { return empMapper.selectAllName(); } //根据输入的姓名查询emp表中是否存在此姓名,并且可能有相同的姓名,都查询出来 //搜索框使用 public ArrayList<String> selectName(String name) { return empMapper.selectName(name); } //修改密码 public int updatepassword(String name, String oldpass, String newpass) { //返回执行修改操作的影响行数 return empMapper.updatepassword(name, oldpass, newpass); } }
fd246086df5208e10dc527cdedae00ab5c86f03f
93becb0e207e95d75dbb05c92c08c07402bcc492
/atcoder/2018_7_7/d.java
79f4213d35b30c9feb2074237f1628669215680b
[]
no_license
veqcc/atcoder
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
refs/heads/master
2023-04-14T21:39:29.705256
2023-04-10T02:31:49
2023-04-10T02:31:49
136,691,016
2
0
null
null
null
null
UTF-8
Java
false
false
2,534
java
import java.util.*; public class d { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int s = sc.nextInt(); int t = sc.nextInt(); Long[][] amap = new Long[n][n]; Long[][] bmap = new Long[n][n]; int u, v; Long a, b; for (int i=0; i < m; i++) { u = sc.nextInt(); v = sc.nextInt(); a = sc.nextLong(); b = sc.nextLong(); amap[u-1][v-1] = a; amap[v-1][u-1] = a; bmap[u-1][v-1] = b; bmap[v-1][u-1] = b; } System.out.println("------"); Long[] yenCost = new Long[n]; boolean[] fixed = new boolean[n]; for (int i=0; i < n; i++) { yenCost[i] = Long.MAX_VALUE; fixed[i] = false; } yenCost[s-1] = (long)0; fixed[s-1] = true; while (true) { int min_num = -1; Long min_cost = Long.MAX_VALUE; for (int i=0; i < n; i++) { if (fixed[i] == true && yenCost[i] < min_cost) { min_num = i; min_cost = yenCost[i]; } } for (int i=0; i < n; i++) { yenCost[i] += amap[min_num][i]; fixed[min_num] = true; } boolean res = true; for (int i=0; i < n; i++) { if (fixed[i] == false) { res = false; } } if (res == false) { break; } } Long[] snuukCost = new Long[n]; boolean[] snuukfixed = new boolean[n]; for (int i=0; i < n; i++) { snuukCost[i] = Long.MAX_VALUE; snuukfixed[i] = false; } snuukCost[t-1] = (long)0; while (true) { int min_num = -1; Long min_cost = Long.MAX_VALUE; for (int i=0; i < n; i++) { if (snuukfixed[i] == false && snuukCost[i] < min_cost) { min_num = i; min_cost = snuukCost[i]; } } for (int i=0; i < n; i++) { snuukCost[i] += bmap[min_num][i]; snuukfixed[i] = true; } boolean res = true; for (int i=0; i < n; i++) { if (snuukfixed[i] == false) { res = false; } } if (res == false) { break; } } Long[] ans = new Long[n]; Long min = Long.MAX_VALUE; ans[n-1] = yenCost[n-1] + snuukCost[n-1]; for (int i=n-2; i > 0; i--) { if (yenCost[i] + snuukCost[i] < ans[i+1]) { ans[i] = yenCost[i] + snuukCost[i]; } else { ans[i] = ans[i=1]; } } for (int i=0; i < n; i++) { System.out.println(ans[i]); } } }