blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
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
listlengths
1
1
author_id
stringlengths
0
313
703270105ec05dbf5995fd00449c8d522e72a46f
00f3c912d02fa5a7bbf77470f0dcac37a243db01
/src/main/java/com/aicure/services/model/Role.java
d1d6b57a8c3db578d9a436b4cf17005cab55e52f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dihuangaic/androidsdk
568cb34ef42146766cfe614c284163e1ed0e62a3
cd98293e350e47ea4c5489206204e464cc67f945
refs/heads/master
2022-06-13T05:30:53.196745
2020-04-27T22:50:03
2020-04-27T22:50:03
140,017,164
1
0
Apache-2.0
2022-05-20T20:49:10
2018-07-06T18:15:12
Java
UTF-8
Java
false
false
1,043
java
/** * null */ package com.aicure.services.model; /** * */ public enum Role { SC("SC"), PARTICIPANT("PATIENT"); private String value; private Role(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return Role corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static Role fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (Role enumEntry : Role.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
80e598a7935587503a8239ef3d3190ed15109af7
6dec7bf59ad6a1dcc879086e9c5260cf82fb552a
/Survivor.java
6a1ed95282c80154c97d28ac05a92d1837d8e9f1
[]
no_license
grant/Sugar-Inc-Code-Challenge
40a8a0d68c1324d792eee56ff49cf2d33520016b
b6cde3b5733f61c64906568c9d195c061edb6328
refs/heads/master
2021-01-01T17:09:35.979147
2013-02-09T06:01:28
2013-02-09T06:01:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,862
java
/** * Survivor * * Description: * You are in a room with a circle of 100 chairs. The chairs are numbered sequentially from 1 to 100. * At some point in time, the person in chair #1 will be asked to leave. The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left… the survivor. * Write a program to determine which chair the survivor is sitting in. Please send us the answer and your working code. * * Prints the answer to the survivor problem when there are 100 chairs */ import java.util.ArrayList; public class Survivor { /** * Tests the chair game when there are 100 chairs. * Prints the chair number when there are 100 chairs. */ public static void main(String[] args) { System.out.println(getSurvivorNumber(100)); } /** * Returns the number chair the survivor is sitting in. Chairs are numbered sequentially starting from 1 * The survivor is found by starting at chair 1 and removing every other person, circling in a loop until * * @param int numChairs The number of chairs in the game. Valid numbers are 1 to Integer.MAX_VALUE. * @return The number chair the survivor is sitting in. (-1 if invalid number provided) */ private static int getSurvivorNumber(int numChairs) { // Handle bad input if (numChairs < 1) { return -1; } // Populate chair array list ArrayList<Integer> chairs = new ArrayList<Integer>(); for (int i = 0; i < numChairs; i++) { chairs.add(i + 1); } // Remove all but one elements int chairIndex = 0; while (chairs.size() > 1) { chairs.remove(chairIndex); chairIndex++;// Skip every other chair chairIndex %= chairs.size();// Loop to beginning if necessary } return chairs.get(0); } }
d5913fb9de306727357a1914f38566ef2911fa2d
9ef0134c9aed0d2e4769bc2be2ce26e161334fe7
/Swing_Project/src/Main.java
afecf4e2d5cb8cc802eba8efcdcbac62b41b338c
[]
no_license
wooPedia/Very_Simple_Java_Project
3d57ed6669e6d62c72c55c21d505e6494d14e52c
2fce475881bbd5c6ecb1747873f41b59ec3abb98
refs/heads/master
2022-11-05T18:21:15.259806
2020-06-14T04:50:58
2020-06-14T04:50:58
263,291,812
0
0
null
null
null
null
UHC
Java
false
false
187
java
import java.io.IOException; public class Main { static final int SIZE = 400; // 생성할 학생 수 public static void main(String[] args) throws IOException { new MyFrame(); } }
ade70a80eed80baac7ffbc213ca35a15713641cf
93401c9f11e85cac1f693f240cf8e985912c28c1
/app/src/androidTest/java/me/thirtythreeforty/headsetbattery/ApplicationTest.java
e3aa42ee2c62d78e8d744deca9c2c241e11650a6
[]
no_license
thirtythreeforty/headset-battery
e0d986cf2b7ba58655f19bc81f0a588ee669f0c4
9f4bef46960688b5df43bad1cf17b1071f89eaa9
refs/heads/master
2021-03-30T16:19:45.284024
2016-08-18T19:58:03
2016-08-18T19:58:03
65,968,385
0
0
null
null
null
null
UTF-8
Java
false
false
365
java
package me.thirtythreeforty.headsetbattery; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
ad6bfb13a1ddd63f8ef4ffd4588dfd042a75f112
a63e2c1715c28d60e430d31e2797942e597610a8
/DesignPatterns/src/creational/builder/Coke.java
6d4b0fc98ccfe0db26fbb0e8add01ce38deedf56
[]
no_license
erdogdubeyazit/designpatterns
6d880f82f5b0b874737f8cfa5bbefe942b439339
226e6ade432a2a67c552a4410916561828b126e3
refs/heads/main
2023-02-28T16:08:21.210610
2021-02-16T22:30:12
2021-02-16T22:30:12
339,544,623
0
0
null
null
null
null
UTF-8
Java
false
false
181
java
package creational.builder; public class Coke extends ColdDrink { @Override public String name() { return "Coke"; } @Override public float price() { return 30.0f; } }
[ "beb@localhost" ]
beb@localhost
3179273a6f2b0f820b18e23de2c1c2342b3b2401
03dc99ed440d82a4e201314e936a0a8b95cf6918
/src/oo/heranca/Direcao.java
8656e68169b0255105007551e4d6f385ba1264f9
[]
no_license
GJayme/Java-study
03be1e028c6343fc2c6919bda12008006420aaea
276e16b0d8cb7cc1ac4d2e9212e7959a23ff315c
refs/heads/master
2023-01-14T01:54:08.024309
2020-11-24T18:36:45
2020-11-24T18:36:45
308,909,693
0
0
null
null
null
null
UTF-8
Java
false
false
75
java
package oo.heranca; public enum Direcao { NORTE, LESTE, SUL, OESTE }
f103b5186f8c6748394a62431c8cf5c2d4fa26b4
34ee877c2a28aca211eb9cf2bb9298ac52554f3a
/test/src/dk/brics/tajs/test/TestUnrolling.java
6716810a1ae86238745a486135ff86c0f80c8c81
[ "Apache-2.0" ]
permissive
aliahsan07/TAJS
42ede28305ffa0c6c1da19a6ad4b6a657b84e6bc
387d375c89faf364b227caf6c2bef2cd80dd26bf
refs/heads/master
2021-02-07T16:28:45.267229
2020-04-27T21:47:50
2020-04-27T21:47:50
244,051,462
1
0
Apache-2.0
2020-03-25T13:52:07
2020-02-29T22:35:21
Java
UTF-8
Java
false
false
15,101
java
package dk.brics.tajs.test; import dk.brics.tajs.Main; import dk.brics.tajs.options.Options; import org.junit.Before; import org.junit.Test; public class TestUnrolling { @Before public void before() { Main.reset(); Options.get().enableTest(); Options.get().enableLoopUnrolling(100); } @Test public void loopunrolling_flowgraph_strings() { // reveals ordinary flows Options.get().enableFlowgraph(); Options.get().enableDoNotExpectOrdinaryExit(); Misc.runSource( "'PRE'; for('INIT'; 'COND'; 'INC'){ 'BODY'; } 'POST';"); Misc.checkSystemOutput(); } @Test public void loopunrolling_flowgraph_calls() { // reveals exceptional flows Options.get().enableFlowgraph(); Options.get().enableDoNotExpectOrdinaryExit(); Misc.runSource( "PRE(); for(INIT(); COND(); INC()){ BODY(); } POST();"); Misc.checkSystemOutput(); } @Test public void loopunrolling_flowgraph_continueBreak() { Options.get().enableFlowgraph(); Options.get().enableDoNotExpectOrdinaryExit(); Misc.runSource( "'PRE'; for('INIT'; 'COND'; 'INC'){ 'BODY0'; if('CONTINUE'){continue;} 'BODY1'; if('BREAK'){break;}; 'BODY2';} 'POST';"); Misc.checkSystemOutput(); } @Test public void loopunrolling_flowgraph_continue2() { Options.get().enableFlowgraph(); Options.get().enableDoNotExpectOrdinaryExit(); Misc.runSource( "while1: while('COND1'){ while2: while('COND2'){continue while2;}}"); Misc.checkSystemOutput(); } @Test public void loopunrolling_flowgraph_labelledcontinue() { Options.get().enableFlowgraph(); Misc.runSource( "function labelled(){label: while('COND'){continue label;}}", "function unlabelled(){while('COND'){continue;}}"); Misc.checkSystemOutput(); } @Test public void deadWhileLoop() { Misc.runSource( "var v = true;", "while(false){ v = false; }", "TAJS_assert(v);"); } @Test public void deadForLoop() { Misc.runSource( "var v = true;", "while(false){ v = false; }", "TAJS_assert(v);"); } @Test public void counterWhileLoop() { Misc.runSource( "var i = 0;", "while(i < 5){ i++; }", "TAJS_assert(i === 5);"); } @Test public void smallCounterForLoop() { Misc.runSource( "for(var i = 0; i === 0; i++){ ", "}", "TAJS_assert(i === 1);"); } @Test public void smallCounterForLoopWLoopVariableFunctionCallRead() { Misc.runSource( "for(var i = 0; i < 3; i++){ (function(){i;})(); }", "TAJS_assert(i === 3);"); } @Test public void smallCounterForLoopWLoopVariableFunctionCallReadWrite() { Misc.runSource( "for(var i = 0; i < 3; i++){ (function(){i = i;})(); }", "TAJS_assert(i === 3);"); } @Test public void smallCounterForLoopWObjectAllocation_1() { Misc.runSource( "var o;", "for(var i = 0; i < 1; i++){ o = {}; }", "TAJS_assert(o, 'isNotASummarizedObject');"); } @Test public void smallCounterForLoopWObjectAllocation_2() { Misc.runSource( "var o;", "for(var i = 0; i < 2; i++){ o = {}; }", "TAJS_assert(o, 'isNotASummarizedObject');", ""); } @Test public void smallCounterForLoopWObjectAllocation_3() { Misc.runSource( "var o;", "for(var i = 0; i < 3; i++){ o = {}; }", "TAJS_assert(o, 'isNotASummarizedObject');"); } @Test public void smallCounterWrite() { Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ j = i; }", "TAJS_assert(j === 2);"); } @Test public void smallCounterForLoopWFunctionAllocation() { Misc.runSource( "var o;", "for(var i = 0; i < 3; i++){ o = function(){}; }", "TAJS_assert(o, 'isNotASummarizedObject');"); } @Test public void smallCounterForLoopWFunctionCall() { Misc.runSource( "var o;", "for(var i = 0; i < 3; i++){ o = (function(){ return {};})(); }", "TAJS_assert(o, 'isNotASummarizedObject');"); } @Test public void smallCounterForLoopWOuterVariableFunctionCallRead() { // should not crash Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ (function(){j;})(); }"); } @Test public void smallCounterForLoopWOuterVariableFunctionCallWriteConstant() { Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ (function(){j = 1;})(); }", "TAJS_assert(j === 1);"); } @Test public void smallCounterForLoopWOuterVariableFunctionCallWrite() { Options.get().enableNoPolymorphic(); Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ (function(){j = i;})(); }", "TAJS_assert(j, 'isMaybeNumUInt');"); } @Test public void smallCounterForLoopWOuterVariableFunctionCallReadWrite() { Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ (function(){j++;})(); }", "TAJS_assert(j, 'isMaybeNumUInt');"); } @Test public void smallCounterForLoopWInnerVariableFunctionCallRead() { // should not crash Misc.runSource( "for(var i = 0; i < 3; i++){ var j = 0; (function(){j;})(); }"); } @Test public void smallCounterForLoopWInnerVariableFunctionCallWriteConstant() { Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ var j = 0; (function(){j = 1;})(); TAJS_assert(j === 1); }"); } @Test public void smallCounterForLoopWInnerVariableFunctionCallWrite() { Misc.runSource( "var j = 0;", "for(var i = 0; i < 3; i++){ var j = 0; (function(){j = i;})(); TAJS_assert(j, 'isMaybeSingleNum||isMaybeNumUInt'); }"); } @Test public void smallCounterForLoopWInnerVariableFunctionCallReadWrite() { Misc.runSource( "for(var i = 0; i < 3; i++){ var j = 0; (function(){j++;})(); TAJS_assert(j === 1);}"); } @Test public void counterForLoop() { Misc.runSource( "for(var i = 0; i < 5; i++){ }", "TAJS_assert(i === 5);"); } @Test public void counterForLoopInFunction() { Misc.runSource( "(function(){", " for(var i = 0; i < 5; i++){ }", " TAJS_assert(i === 5);", "})();"); } @Test public void counterForLoopThroughClosures() { Misc.runSource( "var i;", "(function(){", " for(i = 0; i < 5; i++){ }", "})();", "TAJS_assert(i === 5);"); } @Test public void sequencedCounterForLoops() { Misc.runSource( "for(var i = 0; i < 5; i++){ }", "for(; i < 10; i++){ }", "TAJS_assert(i === 10);"); } @Test public void sequencedForLoopThroughClosures() { Misc.runSource( "var i;", "(function(){", " for(i = 0; i < 5; i++){ }", "})();", "(function(){", " for(; i < 10; i++){ }", "})();", "TAJS_assert(i === 10);"); } @Test public void nestedCounterForLoop() { Misc.runSource( "var k = 0;", "for(var i = 0; i < 5; i++){", " for(var j = 0; j < 5; j++){", " k++;", " }", "}", "TAJS_assert(i === 5);", "TAJS_assert(j === 5);", "TAJS_assert(k === 25);"); } @Test public void nestedCounterForLoopWithCalls() { Misc.runSource( "function f(){}", "var k = 0;", "for(var i = 0; i < 5; i++){", " f();", " for(var j = 0; j < 5; j++){", " f();", " k++;", " f();", " }", " f();", "}", "TAJS_assert(i === 5);", "TAJS_assert(j === 5);", "TAJS_assert(k === 25);"); } @Test public void nestedCounterForLoopWithReadingCalls() { Misc.runSource( "var k = 0;", "function f(){k;}", "for(var i = 0; i < 5; i++){", " f();", " for(var j = 0; j < 5; j++){", " f();", " k++;", " f();", " }", " f();", "}", "TAJS_assert(i === 5);", "TAJS_assert(j === 5);", "TAJS_assert(k === 25);"); } @Test public void nestedDeterminacyChecks() { Misc.runSource( "var c1 = true; var c2 = true;", "for(var i = 0; c1; i++){", " TAJS_assert(c1);", " c1 = i < 5;", " for(var j = 0; c2; j++){", " TAJS_assert(c2);", " c2 = j < 5;", " }", "}", "TAJS_assert(!c1);", "TAJS_assert(!c2);"); } @Test public void nestedDeterminacyChecks_2() { Misc.runSource( "var c1 = true; var c2 = true;", "var c1_copy = c1; var c2_copy = c2;", "for(var i = 0; c1_copy; i++){", " TAJS_assert(c1);", " c1 = i < 5;", " c1_copy = c1;", " for(var j = 0; c2_copy; j++){", " TAJS_assert(c2);", " c2 = j < 5;", " c2_copy = c2;", " }", "}", "TAJS_assert(!c1);", "TAJS_assert(!c2);"); } @Test public void breakInCounterForLoop() { Misc.runSource( "for(var i = 0; i < 5; i++){", " if(i === 4){ break; }", "}", "TAJS_assert(i === 4);"); } @Test public void indeterminateForLoop() { Misc.runSource( "var i = 0;", "for(;TAJS_make('AnyBool');){ i++; }", "TAJS_assert(i, 'isMaybeNumUInt');", "TAJS_assert(i, 'isMaybeSingleNum', false);"); } @Test public void indeterminateStdForLoop() { Misc.runSource( "for(var i = 0;TAJS_make('AnyBool'); i++){ }", "TAJS_assert(i, 'isMaybeNumUInt');", "TAJS_assert(i, 'isMaybeSingleNum', false);"); } @Test public void indeterminateWhileLoop() { Misc.runSource( "var i = 0;", "while(TAJS_make('AnyBool')){ i++; }", "TAJS_assert(i, 'isMaybeNumUInt');", "TAJS_assert(i, 'isMaybeSingleNum', false);"); } @Test public void indeterminateWhileLoop_InFunction() { Misc.runSource( "var i = 0;", "(function(){", " while(TAJS_make('AnyBool')){ i++; }", "})();", "TAJS_assert(i, 'isMaybeNumUInt');", "TAJS_assert(i, 'isMaybeSingleNum', false);"); } @Test public void stringShrinkingWhileLoop_empty() { Misc.runSource( "var s = 'abcdefg';", "while(s){ s = s.substring(1); }", "TAJS_assert(s === '');"); } @Test public void stringShrinkingWhileLoop_nonEmpty() { Misc.runSource( "var s = 'abcdefg';", "while(s.length !== 1){ s = s.substring(1); }", "TAJS_assert(s === 'g');"); } @Test public void closureVariable() { Misc.runSource( "var f;", "for(var i = 0; i < 5; i++){", " f = function(){ return i;}; ", "}", "TAJS_assert(f, 'isNotASummarizedObject');", "TAJS_assert(f() === i);", "TAJS_assert(f() === 5);"); } @Test public void fixedClosureVariable() { Misc.runSource( "var f;", "for(var i = 0; i < 5; i++){", " f = (function(j){return function(){ return j;}})(i); ", "}", "TAJS_assert(f, 'isNotASummarizedObject');", "TAJS_assert(f() === 4);"); } @Test public void nestedThroughCall_small() { Options.get().enableLoopUnrolling(0); Misc.runSource( "function f(){", " for(var j = 0; j < 1; j++){", " }", "}", "for(var i = 0; i < 2; i++){", " f();", "}"); } @Test public void nestedThroughCall_big() { Options.get().enableLoopUnrolling(10); Misc.runSource("function f(){", " for(var j = 0; j < 5; j++){", " }", "}", "for(var i = 0; i < 5; i++){", " f();", "}"); } @Test public void loopunrolling_flowgraph_strings_do() { // reveals ordinary flows Options.get().enableFlowgraph(); Options.get().enableDoNotExpectOrdinaryExit(); Misc.runSource("'PRE'; do { 'BODY'; } while ( 'COND' ) 'POST';"); Misc.checkSystemOutput(); } @Test public void almostDeadDoLoop() { Misc.runSource("var v = true;", "do{", " TAJS_assert(v);", " v = false;", "} while (false) ", "TAJS_assert(!v);"); } @Test public void zeroCounterDoLoop() { Misc.runSource("var i = 0;", "do { i++; } while (i < 0)", "TAJS_assert(i === 1);"); } @Test public void smallCounterDoLoop() { Misc.runSource("var i = 0;", "do { i++; } while (i < 1)", "TAJS_assert(i === 1);"); } @Test public void counterDoLoop() { Misc.runSource("var i = 0;", "do { i++; } while (i < 5)", "TAJS_assert(i === 5);"); } }
e05bb15840798dedd310e801c37952b9cdc6a212
284b11f65fcfc109dc72cdf8ee681a32d1a4401c
/app/src/main/java/com/assignment/abhijeet/models/StudentsDataSource.java
3a09958bd9abc9962c4e477fc72a152f58256afc
[]
no_license
abhijeetvader9287/assignment
39a69d100e2c71a6ea49de4271ddb4762b8b612b
545239189b8eda0d548d1b0b0772262c5bea78d7
refs/heads/master
2021-01-19T19:35:57.958885
2017-04-16T16:28:52
2017-04-16T16:28:52
88,426,569
0
0
null
null
null
null
UTF-8
Java
false
false
642
java
package com.assignment.abhijeet.models; import android.support.annotation.NonNull; import java.util.List; /** * The interface Students data source. */ interface StudentsDataSource { /** * Gets students. * * @return the students */ List<Student> getStudents(); /** * Save student boolean. * * @param Student the student * @return the boolean */ boolean saveStudent(@NonNull Student Student); /** * Check student boolean. * * @param StudentName the student name * @return the boolean */ boolean checkStudent(@NonNull String StudentName); }
f2cbec9be71f977732086ceb06854426717b33d1
8deb692b144a55b391273c17e8023d67209fb97a
/src/main/java/com/narvar/commerce/tools/assertion/shopify/service/ShopifyProductService.java
5cbb3a5b8736061beadff7f5a54e971b4e0238de
[]
no_license
kunalArneja/assertion-tools
c8c30c816847fcb8a327c561a3f73b1564297084
f8f3b00dcfede84f1f00988333123ce25e77bf45
refs/heads/master
2021-06-16T21:30:15.841811
2020-01-28T08:14:11
2020-01-28T08:14:11
210,532,715
0
0
null
2021-06-04T02:12:34
2019-09-24T06:53:04
Java
UTF-8
Java
false
false
6,931
java
/* * * Copyright (c) 2019 Narvar Inc. * All rights reserved * */ package com.narvar.commerce.tools.assertion.shopify.service; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.narvar.commerce.tools.assertion.shopify.constants.ShopifyEndpoints; import com.narvar.commerce.tools.assertion.shopify.constants.Headers; import com.narvar.commerce.tools.assertion.shopify.constants.ShopifyRequestConstants; import com.narvar.commerce.tools.assertion.shopify.domain.ShopifyProduct; import com.narvar.commerce.tools.assertion.shopify.domain.ShopifyProducts; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Service public class ShopifyProductService { private static final Logger LOG = LoggerFactory.getLogger(ShopifyProductService.class); private HttpClient httpClient; private ObjectMapper objectMapper; @Autowired ShopifyProductService() { this.httpClient = HttpClientBuilder.create().build(); this.objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } public List<ShopifyProduct> getProducts(String storeName, String accessToken, LocalDateTime startDate, LocalDateTime endDate) throws Exception { ShopifyProduct firstProduct = getFirstProduct(storeName, accessToken, startDate, endDate); ShopifyProduct lastProduct = getLastProduct(storeName, accessToken, startDate, endDate); Long sinceId = firstProduct.getId() - 1L; Long endId = lastProduct.getId(); Long currentStartIndex = sinceId; List<ShopifyProduct> shopifyProductList = new ArrayList<>(); while (currentStartIndex <= endId) { String uri = ShopifyUrl.builder() .urlPath(ShopifyEndpoints.PRODUCT.API_ROOT_JSON) .updateAtMin(startDate) .updateAtMax(endDate) .sortOrderKey(ShopifyRequestConstants.SortOrderKey.CREATED_AT) .sortOrder(ShopifyRequestConstants.SortOrder.ASC) .sinceId(currentStartIndex) .limit(250) .status(ShopifyRequestConstants.Status.ANY) .build(); HttpGet request = new HttpGet("https://" + storeName + uri); request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); request.addHeader(Headers.ACCESS_TOKEN, accessToken); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatusLine().getStatusCode()); } ShopifyProducts shopifyProducts = objectMapper.readValue(response.getEntity().getContent(), ShopifyProducts.class); shopifyProductList.addAll(shopifyProducts.getShopifyProductList()); LOG.info("Total Number of Products Fetched : " + shopifyProductList.size()); if (shopifyProducts.getShopifyProductList().size() > 0) { currentStartIndex = shopifyProducts.getShopifyProductList().get(shopifyProducts.getShopifyProductList().size() - 1).getId(); } else { currentStartIndex += 250; } TimeUnit.MILLISECONDS.sleep(500); } return shopifyProductList; } public ShopifyProduct getFirstProduct(String storeName, String accessToken, LocalDateTime startDate, LocalDateTime endDate) throws Exception { String uri = ShopifyUrl.builder() .urlPath(ShopifyEndpoints.PRODUCT.API_ROOT_JSON) .limit(1) .updateAtMin(startDate) .updateAtMax(endDate) .sortOrderKey(ShopifyRequestConstants.SortOrderKey.CREATED_AT) .sortOrder(ShopifyRequestConstants.SortOrder.ASC) .status(ShopifyRequestConstants.Status.ANY) .build(); HttpGet request = new HttpGet("https://" + storeName + uri); request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); request.addHeader(Headers.ACCESS_TOKEN, accessToken); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatusLine().getStatusCode()); } ShopifyProducts shopifyProducts = objectMapper.readValue(response.getEntity().getContent(), ShopifyProducts.class); if (shopifyProducts.getShopifyProductList().size() > 0) { return shopifyProducts.getShopifyProductList().get(0); } return null; } public ShopifyProduct getLastProduct(String storeName, String accessToken, LocalDateTime startDate, LocalDateTime endDate) throws Exception { String uri = ShopifyUrl.builder() .urlPath(ShopifyEndpoints.PRODUCT.API_ROOT_JSON) .limit(1) .updateAtMin(startDate) .updateAtMax(endDate) .sortOrderKey(ShopifyRequestConstants.SortOrderKey.CREATED_AT) .sortOrder(ShopifyRequestConstants.SortOrder.DESC) .status(ShopifyRequestConstants.Status.ANY) .build(); HttpGet request = new HttpGet("https://" + storeName + uri); request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); request.addHeader(Headers.ACCESS_TOKEN, accessToken); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed with HTTP error code : " + response.getStatusLine().getStatusCode()); } ShopifyProducts shopifyProducts = objectMapper.readValue(response.getEntity().getContent(), ShopifyProducts.class); if (shopifyProducts.getShopifyProductList().size() > 0) { return shopifyProducts.getShopifyProductList().get(0); } return null; } }
8e9ade4704f524669b23140bd3956ccf454ffbc9
6ce1c7316a190d6ff41f3a0a94101f8c1e823679
/src/HashTreeSet.java
a32e238ac4a58872ad29eb093ae6eb23cbb4a4cd
[]
no_license
njustesen/AStarPathfinder
c3e6dbae39ed3716513e73d87a047576ede18a28
4b8d8a48f834f57b0dd17b24a7e8f62cd9dfa4b5
refs/heads/master
2021-01-01T16:35:45.130427
2012-12-12T00:20:20
2012-12-12T00:20:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,987
java
import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class HashTreeSet implements Set<Tile> { TreeSet<Tile> treeSet; HashSet<Tile> hashSet; public HashTreeSet(){ treeSet = new TreeSet<Tile>(new Comparator<Tile>() { @Override public int compare(Tile o1, Tile o2) { int score = o1.getFScore() - o2.getFScore(); if (score == 0){ return -1; } return score; } }); hashSet = new HashSet<Tile>(); } public Tile pollFirst(){ Tile t = treeSet.pollFirst(); hashSet.remove(t); return t; } @Override public boolean add(Tile e) { treeSet.add(e); hashSet.add(e); return false; } @Override public boolean addAll(Collection<? extends Tile> c) { treeSet.addAll(c); hashSet.addAll(c); return false; } @Override public void clear() { treeSet.clear(); hashSet.clear(); } @Override public boolean contains(Object o) { return hashSet.contains(o); } @Override public boolean containsAll(Collection<?> c) { return hashSet.containsAll(c); } @Override public boolean isEmpty() { return hashSet.isEmpty(); } @Override public Iterator<Tile> iterator() { return hashSet.iterator(); } @Override public boolean remove(Object o) { if (hashSet.remove(o) && treeSet.remove(o)){ return true; } else { return false; } } @Override public boolean removeAll(Collection<?> c) { if (hashSet.removeAll(c) && treeSet.removeAll(c)){ return true; } else { return false; } } @Override public boolean retainAll(Collection<?> c) { if (hashSet.retainAll(c) && treeSet.retainAll(c)){ return true; } else { return false; } } @Override public int size() { return hashSet.size(); } @Override public Object[] toArray() { return hashSet.toArray(); } @Override public <T> T[] toArray(T[] a) { return hashSet.toArray(a); } }
2fbc0ae7d76cf12aa270c7a4a04ba4db521c59c9
bcd42082740cc81d69fc63bb5f07983212953bf5
/src/main/java/com/hush/service/ComService.java
daa9bf6e528f7371544aabc35595a3fa8957fd56
[]
no_license
luxf1234/New
f57369388b5954328a376e33f48b3e5fec76d779
79c60c3cdac2414e2b0dd8a4f3f731bc7abe197f
refs/heads/master
2020-04-13T13:40:09.034933
2018-12-27T02:40:48
2018-12-27T02:40:48
163,238,495
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package com.hush.service; import java.util.List; import com.hush.pojo.Community; public interface ComService { List<Community> comlist(String comName); String add(String comName); String deleteByName(String comName); }
82cd41fab8ec601e0b8290e779c9c680202d4459
ebe15bcd062006ee539b8710778025f8409626ef
/srcAD/org/openbravo/erpWindows/BusinessPartner/LocationAddress.java
13ed5424e463b06a99fbc874eecf6d8749901b09
[]
no_license
yovannyr/openz
c323f3d4d8d28f18bdbcb7dd6f1fea1a2bd88b77
52449b70f88390343e9ed83ea7525f5ce637d9ec
refs/heads/master
2021-01-10T01:09:48.468259
2016-04-05T08:21:21
2016-04-05T08:21:21
55,480,328
0
0
null
null
null
null
UTF-8
Java
false
false
52,420
java
package org.openbravo.erpWindows.BusinessPartner; import org.openbravo.erpCommon.utility.*; import org.openbravo.data.FieldProvider; import org.openbravo.utils.FormatUtilities; import org.openbravo.utils.Replace; import org.openbravo.base.secureApp.HttpSecureAppServlet; import org.openbravo.base.secureApp.VariablesSecureApp; import org.openbravo.base.exception.OBException; import org.openbravo.scheduling.ProcessBundle; import org.openbravo.scheduling.ProcessRunner; import org.openbravo.erpCommon.businessUtility.WindowTabs; import org.openbravo.xmlEngine.XmlDocument; import java.util.Vector; import java.util.StringTokenizer; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.sql.Connection; import org.apache.log4j.Logger; import org.apache.commons.fileupload.FileItem; import org.openz.view.*; import org.openz.model.*; import org.openz.controller.callouts.CalloutStructure; import org.openz.view.Formhelper; import org.openz.view.Scripthelper; import org.openz.view.templates.ConfigureButton; import org.openz.view.templates.ConfigureInfobar; import org.openz.view.templates.ConfigurePopup; import org.openz.view.templates.ConfigureSelectBox; import org.openz.view.templates.ConfigureFrameWindow; import org.openz.util.LocalizationUtils; import org.openz.util.UtilsData; import org.openz.controller.businessprocess.DocActionWorkflowOptions; import org.openbravo.data.Sqlc; public class LocationAddress extends HttpSecureAppServlet { private static final long serialVersionUID = 1L; private static Logger log4j = Logger.getLogger(LocationAddress.class); private static final String windowId = "123"; private static final String tabId = "222"; private static final String defaultTabView = "RELATION"; private static final int accesslevel = 3; private static final double SUBTABS_COL_SIZE = 15; public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { TableSQLData tableSQL = null; VariablesSecureApp vars = new VariablesSecureApp(request); Boolean saveRequest = (Boolean) request.getAttribute("autosave"); this.setWindowId(windowId); this.setTabId(tabId); if(saveRequest != null && saveRequest){ String currentOrg = vars.getStringParameter("inpadOrgId"); String currentClient = vars.getStringParameter("inpadClientId"); boolean editableTab = (!org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), tabId) && (currentOrg.equals("") || Utility.isElementInList(Utility.getContext(this, vars,"#User_Org", windowId, accesslevel), currentOrg)) && (currentClient.equals("") || Utility.isElementInList(Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),currentClient))); OBError myError = new OBError(); String commandType = request.getParameter("inpCommandType"); String strcBpartnerLocationId = request.getParameter("inpcBpartnerLocationId"); String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); if (editableTab) { int total = 0; if(commandType.equalsIgnoreCase("EDIT") && !strcBpartnerLocationId.equals("")) total = saveRecord(vars, myError, 'U', strPC_BPartner_ID); else total = saveRecord(vars, myError, 'I', strPC_BPartner_ID); if (!myError.isEmpty() && total == 0) throw new OBException(myError.getMessage()); } vars.setSessionValue(request.getParameter("mappingName") +"|hash", vars.getPostDataHash()); vars.setSessionValue(tabId + "|Header.view", "EDIT"); return; } try { tableSQL = new TableSQLData(vars, this, tabId, Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel), Utility.getContext(this, vars, "#User_Client", windowId), Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y")); } catch (Exception ex) { ex.printStackTrace(); } String strOrderBy = vars.getSessionValue(tabId + "|orderby"); if (!strOrderBy.equals("")) { vars.setSessionValue(tabId + "|newOrder", "1"); } if (vars.commandIn("DEFAULT")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID", ""); String strC_BPartner_Location_ID = vars.getGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID", ""); if (strPC_BPartner_ID.equals("")) { strPC_BPartner_ID = getParentID(vars, strC_BPartner_Location_ID); if (strPC_BPartner_ID.equals("")) throw new ServletException("Required parameter :" + windowId + "|C_BPartner_ID"); vars.setSessionValue(windowId + "|C_BPartner_ID", strPC_BPartner_ID); refreshParentSession(vars, strPC_BPartner_ID); } String strView = vars.getSessionValue(tabId + "|LocationAddress.view"); if (strView.equals("")) { strView = defaultTabView; if (strView.equals("EDIT")) { if (strC_BPartner_Location_ID.equals("")) strC_BPartner_Location_ID = firstElement(vars, tableSQL); if (strC_BPartner_Location_ID.equals("")) strView = "RELATION"; } } if (strView.equals("EDIT")) printPageEdit(response, request, vars, false, strC_BPartner_Location_ID, strPC_BPartner_ID, tableSQL); else printPageDataSheet(response, vars, strPC_BPartner_ID, strC_BPartner_Location_ID, tableSQL); } else if (vars.commandIn("DIRECT") || vars.commandIn("DIRECTRELATION")) { String strC_BPartner_Location_ID = vars.getStringParameter("inpDirectKey"); if (strC_BPartner_Location_ID.equals("")) strC_BPartner_Location_ID = vars.getRequiredGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID"); else vars.setSessionValue(windowId + "|C_BPartner_Location_ID", strC_BPartner_Location_ID); String strPC_BPartner_ID = getParentID(vars, strC_BPartner_Location_ID); vars.setSessionValue(windowId + "|C_BPartner_ID", strPC_BPartner_ID); vars.setSessionValue("220|Business Partner.view", "EDIT"); refreshParentSession(vars, strPC_BPartner_ID); if (vars.commandIn("DIRECT")){ vars.setSessionValue(tabId + "|LocationAddress.view", "EDIT"); printPageEdit(response, request, vars, false, strC_BPartner_Location_ID, strPC_BPartner_ID, tableSQL); } if (vars.commandIn("DIRECTRELATION")){ vars.setSessionValue(tabId + "|LocationAddress.view", "RELATION"); printPageDataSheet(response, vars, strPC_BPartner_ID, strC_BPartner_Location_ID, tableSQL); } } else if (vars.commandIn("TAB")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID", false, false, true, ""); vars.removeSessionValue(windowId + "|C_BPartner_Location_ID"); refreshParentSession(vars, strPC_BPartner_ID); String strView = vars.getSessionValue(tabId + "|LocationAddress.view"); String strC_BPartner_Location_ID = ""; if (strView.equals("")) { strView = defaultTabView; if (strView.equals("EDIT")) { strC_BPartner_Location_ID = firstElement(vars, tableSQL); if (strC_BPartner_Location_ID.equals("")) strView = "RELATION"; } } if (strView.equals("EDIT")) { if (strC_BPartner_Location_ID.equals("")) strC_BPartner_Location_ID = firstElement(vars, tableSQL); printPageEdit(response, request, vars, false, strC_BPartner_Location_ID, strPC_BPartner_ID, tableSQL); } else printPageDataSheet(response, vars, strPC_BPartner_ID, "", tableSQL); } else if (vars.commandIn("SEARCH")) { vars.getRequestGlobalVariable("inpParamName", tabId + "|paramName"); String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); vars.removeSessionValue(windowId + "|C_BPartner_Location_ID"); String strC_BPartner_Location_ID=""; String strView = vars.getSessionValue(tabId + "|LocationAddress.view"); if (strView.equals("")) strView=defaultTabView; if (strView.equals("EDIT")) { strC_BPartner_Location_ID = firstElement(vars, tableSQL); if (strC_BPartner_Location_ID.equals("")) { // filter returns empty set strView = "RELATION"; // switch to grid permanently until the user changes the view again vars.setSessionValue(tabId + "|LocationAddress.view", strView); } } if (strView.equals("EDIT")) printPageEdit(response, request, vars, false, strC_BPartner_Location_ID, strPC_BPartner_ID, tableSQL); else printPageDataSheet(response, vars, strPC_BPartner_ID, strC_BPartner_Location_ID, tableSQL); } else if (vars.commandIn("RELATION")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID", ""); vars.setSessionValue(tabId + "|LocationAddress.view", "RELATION"); printPageDataSheet(response, vars, strPC_BPartner_ID, strC_BPartner_Location_ID, tableSQL); } else if (vars.commandIn("NEW")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); printPageEdit(response, request, vars, true, "", strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("EDIT")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); @SuppressWarnings("unused") // In Expense Invoice tab this variable is not used, to be fixed String strC_BPartner_Location_ID = vars.getGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID", ""); vars.setSessionValue(tabId + "|LocationAddress.view", "EDIT"); setHistoryCommand(request, "EDIT"); printPageEdit(response, request, vars, false, strC_BPartner_Location_ID, strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("NEXT")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getRequiredStringParameter("inpcBpartnerLocationId"); String strNext = nextElement(vars, strC_BPartner_Location_ID, tableSQL); printPageEdit(response, request, vars, false, strNext, strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("PREVIOUS")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getRequiredStringParameter("inpcBpartnerLocationId"); String strPrevious = previousElement(vars, strC_BPartner_Location_ID, tableSQL); printPageEdit(response, request, vars, false, strPrevious, strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("FIRST_RELATION")) { vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); vars.setSessionValue(tabId + "|LocationAddress.initRecordNumber", "0"); response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); } else if (vars.commandIn("PREVIOUS_RELATION")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strInitRecord = vars.getSessionValue(tabId + "|LocationAddress.initRecordNumber"); String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId); int intRecordRange = strRecordRange.equals("")?0:Integer.parseInt(strRecordRange); if (strInitRecord.equals("") || strInitRecord.equals("0")) { vars.setSessionValue(tabId + "|LocationAddress.initRecordNumber", "0"); } else { int initRecord = (strInitRecord.equals("")?0:Integer.parseInt(strInitRecord)); initRecord -= intRecordRange; strInitRecord = ((initRecord<0)?"0":Integer.toString(initRecord)); vars.setSessionValue(tabId + "|LocationAddress.initRecordNumber", strInitRecord); } vars.removeSessionValue(windowId + "|C_BPartner_Location_ID"); vars.setSessionValue(windowId + "|C_BPartner_ID", strPC_BPartner_ID); response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); } else if (vars.commandIn("NEXT_RELATION")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strInitRecord = vars.getSessionValue(tabId + "|LocationAddress.initRecordNumber"); String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId); int intRecordRange = strRecordRange.equals("")?0:Integer.parseInt(strRecordRange); int initRecord = (strInitRecord.equals("")?0:Integer.parseInt(strInitRecord)); if (initRecord==0) initRecord=1; initRecord += intRecordRange; strInitRecord = ((initRecord<0)?"0":Integer.toString(initRecord)); vars.setSessionValue(tabId + "|LocationAddress.initRecordNumber", strInitRecord); vars.removeSessionValue(windowId + "|C_BPartner_Location_ID"); vars.setSessionValue(windowId + "|C_BPartner_ID", strPC_BPartner_ID); response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); } else if (vars.commandIn("FIRST")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strFirst = firstElement(vars, tableSQL); printPageEdit(response, request, vars, false, strFirst, strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("LAST_RELATION")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strLast = lastElement(vars, tableSQL); printPageDataSheet(response, vars, strPC_BPartner_ID, strLast, tableSQL); } else if (vars.commandIn("LAST")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strLast = lastElement(vars, tableSQL); printPageEdit(response, request, vars, false, strLast, strPC_BPartner_ID, tableSQL); } else if (vars.commandIn("SAVE_NEW_RELATION", "SAVE_NEW_NEW", "SAVE_NEW_EDIT")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); OBError myError = new OBError(); int total = saveRecord(vars, myError, 'I', strPC_BPartner_ID); if (!myError.isEmpty()) { response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW"); } else { if (myError.isEmpty()) { myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsInserted"); myError.setMessage(total + " " + myError.getMessage()); vars.setMessage(tabId, myError); } if (vars.commandIn("SAVE_NEW_NEW")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW"); else if (vars.commandIn("SAVE_NEW_EDIT")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT"); else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); } } else if (vars.commandIn("SAVE_EDIT_RELATION", "SAVE_EDIT_NEW", "SAVE_EDIT_EDIT", "SAVE_EDIT_NEXT")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getRequiredGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID"); OBError myError = new OBError(); int total = saveRecord(vars, myError, 'U', strPC_BPartner_ID); if (!myError.isEmpty()) { response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT"); } else { if (myError.isEmpty()) { myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated"); myError.setMessage(total + " " + myError.getMessage()); vars.setMessage(tabId, myError); } if (vars.commandIn("SAVE_EDIT_NEW")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW"); else if (vars.commandIn("SAVE_EDIT_EDIT")) response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT"); else if (vars.commandIn("SAVE_EDIT_NEXT")) { String strNext = nextElement(vars, strC_BPartner_Location_ID, tableSQL); vars.setSessionValue(windowId + "|C_BPartner_Location_ID", strNext); response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT"); } else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); } /* } else if (vars.commandIn("DELETE_RELATION")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getRequiredInStringParameter("inpcBpartnerLocationId"); String message = deleteRelation(vars, strC_BPartner_Location_ID, strPC_BPartner_ID); if (!message.equals("")) { bdError(request, response, message, vars.getLanguage()); } else { vars.removeSessionValue(windowId + "|cBpartnerLocationId"); vars.setSessionValue(tabId + "|LocationAddress.view", "RELATION"); response.sendRedirect(strDireccion + request.getServletPath()); }*/ } else if (vars.commandIn("DELETE")) { String strPC_BPartner_ID = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); String strC_BPartner_Location_ID = vars.getRequiredStringParameter("inpcBpartnerLocationId"); //LocationAddressData data = getEditVariables(vars, strPC_BPartner_ID); int total = 0; OBError myError = null; if (org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), tabId)) { myError = Utility.translateError(this, vars, vars.getLanguage(), Utility.messageBD(this, "NoWriteAccess", vars.getLanguage())); vars.setMessage(tabId, myError); } else { try { total = LocationAddressData.delete(this, strC_BPartner_Location_ID, strPC_BPartner_ID, Utility.getContext(this, vars, "#User_Client", windowId, accesslevel), Utility.getContext(this, vars, "#User_Org", windowId, accesslevel)); } catch(ServletException ex) { myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); if (!myError.isConnectionAvailable()) { bdErrorConnection(response); return; } else vars.setMessage(tabId, myError); } if (myError==null && total==0) { myError = Utility.translateError(this, vars, vars.getLanguage(), Utility.messageBD(this, "NoWriteAccess", vars.getLanguage())); vars.setMessage(tabId, myError); } vars.removeSessionValue(windowId + "|cBpartnerLocationId"); vars.setSessionValue(tabId + "|LocationAddress.view", "RELATION"); } if (myError==null) { myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsDeleted"); myError.setMessage(total + " " + myError.getMessage()); vars.setMessage(tabId, myError); } response.sendRedirect(strDireccion + request.getServletPath()); } else if (vars.getCommand().toUpperCase().startsWith("BUTTON") || vars.getCommand().toUpperCase().startsWith("SAVE_BUTTON")) { pageErrorPopUp(response); } else pageError(response); } /* String deleteRelation(VariablesSecureApp vars, String strC_BPartner_Location_ID, String strPC_BPartner_ID) throws IOException, ServletException { log4j.debug("Deleting records"); Connection conn = this.getTransactionConnection(); try { if (strC_BPartner_Location_ID.startsWith("(")) strC_BPartner_Location_ID = strC_BPartner_Location_ID.substring(1, strC_BPartner_Location_ID.length()-1); if (!strC_BPartner_Location_ID.equals("")) { strC_BPartner_Location_ID = Replace.replace(strC_BPartner_Location_ID, "'", ""); StringTokenizer st = new StringTokenizer(strC_BPartner_Location_ID, ",", false); while (st.hasMoreTokens()) { String strKey = st.nextToken(); if (LocationAddressData.deleteTransactional(conn, this, strKey, strPC_BPartner_ID)==0) { releaseRollbackConnection(conn); log4j.warn("deleteRelation - key :" + strKey + " - 0 records deleted"); } } } releaseCommitConnection(conn); } catch (ServletException e) { releaseRollbackConnection(conn); e.printStackTrace(); log4j.error("Rollback in transaction"); return "ProcessRunError"; } return ""; } */ private LocationAddressData getEditVariables(Connection con, VariablesSecureApp vars, String strPC_BPartner_ID) throws IOException,ServletException { LocationAddressData data = new LocationAddressData(); ServletException ex = null; try { data.cBpartnerId = vars.getStringParameter("inpcBpartnerId"); data.cBpartnerIdr = vars.getStringParameter("inpcBpartnerId_R"); data.name = vars.getStringParameter("inpname"); data.deviantBpName = vars.getStringParameter("inpdeviantBpName"); data.isactive = vars.getStringParameter("inpisactive", "N"); data.cLocationId = vars.getStringParameter("inpcLocationId"); data.cLocationIdr = vars.getStringParameter("inpcLocationId_R"); data.phone = vars.getStringParameter("inpphone"); data.phone2 = vars.getStringParameter("inpphone2"); data.fax = vars.getStringParameter("inpfax"); data.isshipto = vars.getStringParameter("inpisshipto", "N"); data.isbillto = vars.getStringParameter("inpisbillto", "N"); data.istaxlocation = vars.getStringParameter("inpistaxlocation", "N"); data.isheadquarter = vars.getStringParameter("inpisheadquarter", "N"); data.uidnumber = vars.getStringParameter("inpuidnumber"); data.eoriidentification = vars.getStringParameter("inpeoriidentification"); data.cTaxId = vars.getStringParameter("inpcTaxId"); data.cTaxIdr = vars.getStringParameter("inpcTaxId_R"); data.cSalesregionId = vars.getStringParameter("inpcSalesregionId"); data.cSalesregionIdr = vars.getStringParameter("inpcSalesregionId_R"); data.upc = vars.getStringParameter("inpupc"); data.ispayfrom = vars.getStringParameter("inpispayfrom", "N"); data.cBpartnerLocationId = vars.getRequestGlobalVariable("inpcBpartnerLocationId", windowId + "|C_BPartner_Location_ID"); data.adOrgId = vars.getRequestGlobalVariable("inpadOrgId", windowId + "|AD_Org_ID"); data.adClientId = vars.getRequestGlobalVariable("inpadClientId", windowId + "|AD_Client_ID"); data.isremitto = vars.getStringParameter("inpisremitto", "N"); data.createdby = vars.getUser(); data.updatedby = vars.getUser(); data.adUserClient = Utility.getContext(this, vars, "#User_Client", windowId, accesslevel); data.adOrgClient = Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel); data.updatedTimeStamp = vars.getStringParameter("updatedTimestamp"); data.cBpartnerId = vars.getGlobalVariable("inpcBpartnerId", windowId + "|C_BPartner_ID"); } catch(ServletException e) { vars.setEditionData(tabId, data); throw e; } // Behavior with exception for numeric fields is to catch last one if we have multiple ones if(ex != null) { vars.setEditionData(tabId, data); throw ex; } return data; } private LocationAddressData[] getRelationData(LocationAddressData[] data) { if (data!=null) { for (int i=0;i<data.length;i++) { data[i].cBpartnerId = FormatUtilities.truncate(data[i].cBpartnerId, 44); data[i].name = FormatUtilities.truncate(data[i].name, 50); data[i].deviantBpName = FormatUtilities.truncate(data[i].deviantBpName, 50); data[i].cLocationId = FormatUtilities.truncate(data[i].cLocationId, 50); data[i].phone = FormatUtilities.truncate(data[i].phone, 13); data[i].phone2 = FormatUtilities.truncate(data[i].phone2, 20); data[i].fax = FormatUtilities.truncate(data[i].fax, 20); data[i].uidnumber = FormatUtilities.truncate(data[i].uidnumber, 20); data[i].eoriidentification = FormatUtilities.truncate(data[i].eoriidentification, 20); data[i].cTaxId = FormatUtilities.truncate(data[i].cTaxId, 32); data[i].cSalesregionId = FormatUtilities.truncate(data[i].cSalesregionId, 44); data[i].upc = FormatUtilities.truncate(data[i].upc, 30); data[i].cBpartnerLocationId = FormatUtilities.truncate(data[i].cBpartnerLocationId, 10); data[i].adOrgId = FormatUtilities.truncate(data[i].adOrgId, 44); data[i].adClientId = FormatUtilities.truncate(data[i].adClientId, 44);} } return data; } private void refreshParentSession(VariablesSecureApp vars, String strPC_BPartner_ID) throws IOException,ServletException { BusinessPartnerData[] data = BusinessPartnerData.selectEdit(this, vars.getSessionValue("#AD_SqlDateTimeFormat"), vars.getLanguage(), strPC_BPartner_ID, Utility.getContext(this, vars, "#User_Client", windowId), Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel)); if (data==null || data.length==0) return; vars.setSessionValue(windowId + "|AD_Client_ID", data[0].adClientId); vars.setSessionValue(windowId + "|AD_Org_ID", data[0].adOrgId); vars.setSessionValue(windowId + "|Value", data[0].value); vars.setSessionValue(windowId + "|C_BPartner_ID", data[0].cBpartnerId); vars.setSessionValue(windowId + "|C_BPartner_ID", strPC_BPartner_ID); //to ensure key parent is set for EM_* cols FieldProvider dataField = null; // Define this so that auxiliar inputs using SQL will work } private String getParentID(VariablesSecureApp vars, String strC_BPartner_Location_ID) throws ServletException { String strPC_BPartner_ID = LocationAddressData.selectParentID(this, strC_BPartner_Location_ID); if (strPC_BPartner_ID.equals("")) { log4j.error("Parent record not found for id: " + strC_BPartner_Location_ID); throw new ServletException("Parent record not found"); } return strPC_BPartner_ID; } private void refreshSessionEdit(VariablesSecureApp vars, FieldProvider[] data) { if (data==null || data.length==0) return; vars.setSessionValue(windowId + "|C_BPartner_Location_ID", data[0].getField("cBpartnerLocationId")); vars.setSessionValue(windowId + "|AD_Org_ID", data[0].getField("adOrgId")); vars.setSessionValue(windowId + "|AD_Client_ID", data[0].getField("adClientId")); } private void refreshSessionNew(VariablesSecureApp vars, String strPC_BPartner_ID) throws IOException,ServletException { LocationAddressData[] data = LocationAddressData.selectEdit(this, vars.getSessionValue("#AD_SqlDateTimeFormat"), vars.getLanguage(), strPC_BPartner_ID, vars.getStringParameter("inpcBpartnerLocationId", ""), Utility.getContext(this, vars, "#User_Client", windowId), Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel)); if (data==null || data.length==0) return; refreshSessionEdit(vars, data); } private String nextElement(VariablesSecureApp vars, String strSelected, TableSQLData tableSQL) throws IOException, ServletException { if (strSelected == null || strSelected.equals("")) return firstElement(vars, tableSQL); if (tableSQL!=null) { String data = null; try{ String strSQL = ModelSQLGeneration.generateSQLonlyId(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>(), 0, 0); ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValuesOnlyId()); data = execquery.selectAndSearch(ExecuteQuery.SearchType.NEXT, strSelected, tableSQL.getKeyColumn()); } catch (Exception e) { log4j.error("Error getting next element", e); } if (data!=null) { if (data!=null) return data; } } return strSelected; } private int getKeyPosition(VariablesSecureApp vars, String strSelected, TableSQLData tableSQL) throws IOException, ServletException { if (log4j.isDebugEnabled()) log4j.debug("getKeyPosition: " + strSelected); if (tableSQL!=null) { String data = null; try{ String strSQL = ModelSQLGeneration.generateSQLonlyId(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>(),0,0); ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValuesOnlyId()); data = execquery.selectAndSearch(ExecuteQuery.SearchType.GETPOSITION, strSelected, tableSQL.getKeyColumn()); } catch (Exception e) { log4j.error("Error getting key position", e); } if (data!=null) { // split offset -> (page,relativeOffset) int absoluteOffset = Integer.valueOf(data); int page = absoluteOffset / TableSQLData.maxRowsPerGridPage; int relativeOffset = absoluteOffset % TableSQLData.maxRowsPerGridPage; log4j.debug("getKeyPosition: absOffset: " + absoluteOffset + "=> page: " + page + " relOffset: " + relativeOffset); String currPageKey = tabId + "|" + "currentPage"; vars.setSessionValue(currPageKey, String.valueOf(page)); return relativeOffset; } } return 0; } private String previousElement(VariablesSecureApp vars, String strSelected, TableSQLData tableSQL) throws IOException, ServletException { if (strSelected == null || strSelected.equals("")) return firstElement(vars, tableSQL); if (tableSQL!=null) { String data = null; try{ String strSQL = ModelSQLGeneration.generateSQLonlyId(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>(),0,0); ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValuesOnlyId()); data = execquery.selectAndSearch(ExecuteQuery.SearchType.PREVIOUS, strSelected, tableSQL.getKeyColumn()); } catch (Exception e) { log4j.error("Error getting previous element", e); } if (data!=null) { return data; } } return strSelected; } private String firstElement(VariablesSecureApp vars, TableSQLData tableSQL) throws IOException, ServletException { if (tableSQL!=null) { String data = null; try{ String strSQL = ModelSQLGeneration.generateSQLonlyId(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>(),0,1); ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValuesOnlyId()); data = execquery.selectAndSearch(ExecuteQuery.SearchType.FIRST, "", tableSQL.getKeyColumn()); } catch (Exception e) { log4j.debug("Error getting first element", e); } if (data!=null) return data; } return ""; } private String lastElement(VariablesSecureApp vars, TableSQLData tableSQL) throws IOException, ServletException { if (tableSQL!=null) { String data = null; try{ String strSQL = ModelSQLGeneration.generateSQLonlyId(this, vars, tableSQL, (tableSQL.getTableName() + "." + tableSQL.getKeyColumn() + " AS ID"), new Vector<String>(), new Vector<String>(),0,0); ExecuteQuery execquery = new ExecuteQuery(this, strSQL, tableSQL.getParameterValuesOnlyId()); data = execquery.selectAndSearch(ExecuteQuery.SearchType.LAST, "", tableSQL.getKeyColumn()); } catch (Exception e) { log4j.error("Error getting last element", e); } if (data!=null) return data; } return ""; } private void printPageDataSheet(HttpServletResponse response, VariablesSecureApp vars, String strPC_BPartner_ID, String strC_BPartner_Location_ID, TableSQLData tableSQL) throws IOException, ServletException { if (log4j.isDebugEnabled()) log4j.debug("Output: dataSheet"); String strParamName = vars.getSessionValue(tabId + "|paramName"); if (vars.getSessionValue(windowId + "|C_BPartner_ID").isEmpty()) vars.setSessionValue(windowId + "|C_BPartner_ID", vars.getStringParameter("inpcBpartnerId")); boolean hasSearchCondition=false; vars.removeEditionData(tabId); if (!(strParamName.equals(""))) hasSearchCondition=true; String strOffset = "0"; //vars.getSessionValue(tabId + "|offset"); String selectedRow = "0"; if (!strC_BPartner_Location_ID.equals("")) { selectedRow = Integer.toString(getKeyPosition(vars, strC_BPartner_Location_ID, tableSQL)); } String[] discard={"isNotFiltered","isNotTest"}; if (hasSearchCondition) discard[0] = new String("isFiltered"); if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest"); XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/erpWindows/BusinessPartner/LocationAddress_Relation", discard).createXmlDocument(); ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "LocationAddress", false, "document.frmMain.inpcBpartnerLocationId", "grid", "..", "".equals("Y"), "BusinessPartner", strReplaceWith, false); toolbar.prepareRelationTemplate("N".equals("Y"), hasSearchCondition, !vars.getSessionValue("#ShowTest", "N").equals("Y"), false, Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y")); xmlDocument.setParameter("toolbar", toolbar.toString()); xmlDocument.setParameter("keyParent", strPC_BPartner_ID); StringBuffer orderByArray = new StringBuffer(); vars.setSessionValue(tabId + "|newOrder", "1"); String positions = vars.getSessionValue(tabId + "|orderbyPositions"); orderByArray.append("var orderByPositions = new Array(\n"); if (!positions.equals("")) { StringTokenizer tokens=new StringTokenizer(positions, ","); boolean firstOrder = true; while(tokens.hasMoreTokens()){ if (!firstOrder) orderByArray.append(",\n"); orderByArray.append("\"").append(tokens.nextToken()).append("\""); firstOrder = false; } } orderByArray.append(");\n"); String directions = vars.getSessionValue(tabId + "|orderbyDirections"); orderByArray.append("var orderByDirections = new Array(\n"); if (!positions.equals("")) { StringTokenizer tokens=new StringTokenizer(directions, ","); boolean firstOrder = true; while(tokens.hasMoreTokens()){ if (!firstOrder) orderByArray.append(",\n"); orderByArray.append("\"").append(tokens.nextToken()).append("\""); firstOrder = false; } } orderByArray.append(");\n"); // } xmlDocument.setParameter("selectedColumn", "\nvar selectedRow = " + selectedRow + ";\n" + orderByArray.toString()); xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n"); xmlDocument.setParameter("windowId", windowId); xmlDocument.setParameter("KeyName", "cBpartnerLocationId"); xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";"); xmlDocument.setParameter("theme", vars.getTheme()); //xmlDocument.setParameter("buttonReference", Utility.messageBD(this, "Reference", vars.getLanguage())); try { WindowTabs tabs = new WindowTabs(this, vars, tabId, windowId, false); xmlDocument.setParameter("parentTabContainer", tabs.parentTabs()); xmlDocument.setParameter("mainTabContainer", tabs.mainTabs()); xmlDocument.setParameter("childTabContainer", tabs.childTabs()); NavigationBar nav = new NavigationBar(this, vars.getLanguage(), "LocationAddress_Relation.html", "BusinessPartner", "W", strReplaceWith, tabs.breadcrumb()); xmlDocument.setParameter("navigationBar", nav.toString()); LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(), "LocationAddress_Relation.html", strReplaceWith); xmlDocument.setParameter("leftTabs", lBar.relationTemplate()); } catch (Exception ex) { throw new ServletException(ex); } { OBError myMessage = vars.getMessage(tabId); vars.removeMessage(tabId); if (myMessage!=null) { xmlDocument.setParameter("messageType", myMessage.getType()); xmlDocument.setParameter("messageTitle", myMessage.getTitle()); xmlDocument.setParameter("messageMessage", myMessage.getMessage()); } } if (vars.getLanguage().equals("en_US")) xmlDocument.setParameter("parent", LocationAddressData.selectParent(this, strPC_BPartner_ID)); else xmlDocument.setParameter("parent", LocationAddressData.selectParentTrl(this, strPC_BPartner_ID)); xmlDocument.setParameter("grid", Utility.getContext(this, vars, "#RecordRange", windowId)); xmlDocument.setParameter("grid_Offset", strOffset); xmlDocument.setParameter("grid_SortCols", positions); xmlDocument.setParameter("grid_SortDirs", directions); xmlDocument.setParameter("grid_Default", selectedRow); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println(xmlDocument.print()); out.close(); } private void printPageEdit(HttpServletResponse response, HttpServletRequest request, VariablesSecureApp vars,boolean boolNew, String strC_BPartner_Location_ID, String strPC_BPartner_ID, TableSQLData tableSQL) throws IOException, ServletException { if (log4j.isDebugEnabled()) log4j.debug("Output: edit"); HashMap<String, String> usedButtonShortCuts; usedButtonShortCuts = new HashMap<String, String>(); String strOrderByFilter = vars.getSessionValue(tabId + "|orderby"); String orderClause = " C_BPartner_Location.IsTaxLocation, C_BPartner_Location.Name"; if (strOrderByFilter==null || strOrderByFilter.equals("")) strOrderByFilter = orderClause; /*{ if (!strOrderByFilter.equals("") && !orderClause.equals("")) strOrderByFilter += ", "; strOrderByFilter += orderClause; }*/ String strCommand = null; LocationAddressData[] data=null; XmlDocument xmlDocument=null; FieldProvider dataField = vars.getEditionData(tabId); vars.removeEditionData(tabId); String strParamName = vars.getSessionValue(tabId + "|paramName"); boolean hasSearchCondition=false; if (!(strParamName.equals(""))) hasSearchCondition=true; String strParamSessionDate = vars.getGlobalVariable("inpParamSessionDate", Utility.getTransactionalDate(this, vars, windowId), ""); String buscador = ""; String[] discard = {"", "isNotTest"}; if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest"); if (dataField==null) { if (!boolNew) { discard[0] = new String("newDiscard"); data = LocationAddressData.selectEdit(this, vars.getSessionValue("#AD_SqlDateTimeFormat"), vars.getLanguage(), strPC_BPartner_ID, strC_BPartner_Location_ID, Utility.getContext(this, vars, "#User_Client", windowId), Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel)); if (!strC_BPartner_Location_ID.equals("") && (data == null || data.length==0)) { response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION"); return; } refreshSessionEdit(vars, data); strCommand = "EDIT"; } if (boolNew || data==null || data.length==0) { discard[0] = new String ("editDiscard"); strCommand = "NEW"; data = new LocationAddressData[0]; } else { discard[0] = new String ("newDiscard"); } } else { if (dataField.getField("cBpartnerLocationId") == null || dataField.getField("cBpartnerLocationId").equals("")) { discard[0] = new String ("editDiscard"); strCommand = "NEW"; boolNew = true; } else { discard[0] = new String ("newDiscard"); strCommand = "EDIT"; } } if (dataField==null) { if (boolNew || data==null || data.length==0) { refreshSessionNew(vars, strPC_BPartner_ID); data = LocationAddressData.set(strPC_BPartner_ID, LocationAddressData.selectDef2958_0(this, strPC_BPartner_ID), Utility.getDefault(this, vars, "IsTaxLocation", "N", "123", "222", "N", dataField), "Y", Utility.getDefault(this, vars, "AD_Org_ID", "@AD_Org_ID@", "123", "222", "", dataField), Utility.getDefault(this, vars, "UPC", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "Phone2", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "Deviant_Bp_Name", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "IsBillTo", "Y", "123", "222", "N", dataField), Utility.getDefault(this, vars, "Fax", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "AD_Client_ID", "@AD_CLIENT_ID@", "123", "222", "", dataField), Utility.getDefault(this, vars, "IsHeadquarter", "N", "123", "222", "N", dataField), Utility.getDefault(this, vars, "Name", ".", "123", "222", "", dataField), Utility.getDefault(this, vars, "Eoriidentification", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "IsPayFrom", "Y", "123", "222", "N", dataField), Utility.getDefault(this, vars, "Phone", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "C_Location_ID", "", "123", "222", "", dataField), LocationAddressData.selectDef2959_1(this, Utility.getDefault(this, vars, "C_Location_ID", "", "123", "222", "", dataField)), Utility.getDefault(this, vars, "Uidnumber", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "C_Tax_ID", "''", "123", "222", "", dataField), Utility.getDefault(this, vars, "IsRemitTo", "Y", "123", "222", "N", dataField), Utility.getDefault(this, vars, "CreatedBy", "", "123", "222", "", dataField), LocationAddressData.selectDef2955_2(this, Utility.getDefault(this, vars, "CreatedBy", "", "123", "222", "", dataField)), Utility.getDefault(this, vars, "IsShipTo", "Y", "123", "222", "N", dataField), Utility.getDefault(this, vars, "C_SalesRegion_ID", "", "123", "222", "", dataField), Utility.getDefault(this, vars, "UpdatedBy", "", "123", "222", "", dataField), LocationAddressData.selectDef2957_3(this, Utility.getDefault(this, vars, "UpdatedBy", "", "123", "222", "", dataField)), ""); } } else { data = new LocationAddressData[1]; java.lang.Object ref1= dataField; data[0]=(LocationAddressData) ref1; data[0].created=""; data[0].updated=""; } String currentPOrg=BusinessPartnerData.selectOrg(this, strPC_BPartner_ID); String currentOrg = (boolNew?"":(dataField!=null?dataField.getField("adOrgId"):data[0].getField("adOrgId"))); if (!currentOrg.equals("") && !currentOrg.startsWith("'")) currentOrg = "'"+currentOrg+"'"; String currentClient = (boolNew?"":(dataField!=null?dataField.getField("adClientId"):data[0].getField("adClientId"))); if (!currentClient.equals("") && !currentClient.startsWith("'")) currentClient = "'"+currentClient+"'"; boolean editableTab = (!org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), tabId) && (currentOrg.equals("") || Utility.isElementInList(Utility.getContext(this, vars, "#User_Org", windowId, accesslevel),currentOrg)) && (currentClient.equals("") || Utility.isElementInList(Utility.getContext(this, vars, "#User_Client", windowId, accesslevel), currentClient))); if (Formhelper.isTabReadOnly(this, vars, tabId)) editableTab=false; ToolBar toolbar = new ToolBar(this, editableTab, vars.getLanguage(), "LocationAddress", (strCommand.equals("NEW") || boolNew || (dataField==null && (data==null || data.length==0))), "document.frmMain.inpcBpartnerLocationId", "", "..", "".equals("Y"), "BusinessPartner", strReplaceWith, true, false, false, Utility.hasTabAttachments(this, vars, tabId, strC_BPartner_Location_ID)); toolbar.prepareEditionTemplate("N".equals("Y"), hasSearchCondition, vars.getSessionValue("#ShowTest", "N").equals("Y"), "STD", Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y")); // set updated timestamp to manage locking mechanism String updatedTimestamp=""; if (!boolNew) { updatedTimestamp=(dataField != null ? dataField.getField("updatedTimeStamp") : data[0].getField("updatedTimeStamp")); } this.setUpdatedtimestamp(updatedTimestamp); // this.setOrgparent(currentPOrg); this.setCommandtype(strCommand); try { WindowTabs tabs = new WindowTabs(this, vars, tabId, windowId, true, (strCommand.equalsIgnoreCase("NEW"))); response.setContentType("text/html; charset=UTF-8"); PrintWriter output = response.getWriter(); Connection conn = null; Scripthelper script = new Scripthelper(); if (boolNew) script.addHiddenfieldWithID("newdatasetindicator", "NEW"); else script.addHiddenfieldWithID("newdatasetindicator", ""); script.addHiddenfieldWithID("enabledautosave", "Y"); script.addMessage(this, vars, vars.getMessage(tabId)); Formhelper fh=new Formhelper(); String strLeftabsmode="EDIT"; String focus=fh.TabGetFirstFocusField(this,tabId); String strSkeleton = ConfigureFrameWindow.doConfigureWindowMode(this,vars,Sqlc.TransformaNombreColumna(focus),tabs.breadcrumb(), "Form Window",null,strLeftabsmode,tabs,"_Relation",toolbar.toString()); String strTableStructure=""; if (editableTab||tabId.equalsIgnoreCase("800026")) strTableStructure=fh.prepareTabFields(this, vars, script, tabId,data[0], Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y")); else strTableStructure=fh.prepareTabFieldsRO(this, vars, script, tabId,data[0], Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y")); strSkeleton=Replace.replace(strSkeleton, "@CONTENT@", strTableStructure ); script.addOnload("setProcessingMode('window', false);"); strSkeleton = script.doScript(strSkeleton, "",this,vars); output.println(strSkeleton); vars.removeMessage(tabId); output.close(); } catch (Exception ex) { throw new ServletException(ex); } } void printPageButtonFS(HttpServletResponse response, VariablesSecureApp vars, String strProcessId, String path) throws IOException, ServletException { log4j.debug("Output: Frames action button"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); XmlDocument xmlDocument = xmlEngine.readXmlTemplate( "org/openbravo/erpCommon/ad_actionButton/ActionButtonDefaultFrames").createXmlDocument(); xmlDocument.setParameter("processId", strProcessId); xmlDocument.setParameter("trlFormType", "PROCESS"); xmlDocument.setParameter("language", "defaultLang = \"" + vars.getLanguage() + "\";\n"); xmlDocument.setParameter("type", strDireccion + path); out.println(xmlDocument.print()); out.close(); } private String getDisplayLogicContext(VariablesSecureApp vars, boolean isNew) throws IOException, ServletException { log4j.debug("Output: Display logic context fields"); String result = "var strShowAudit=\"" +(isNew?"N":Utility.getContext(this, vars, "ShowAudit", windowId)) + "\";\n"; return result; } private String getReadOnlyLogicContext(VariablesSecureApp vars) throws IOException, ServletException { log4j.debug("Output: Read Only logic context fields"); String result = ""; return result; } private String getShortcutScript( HashMap<String, String> usedButtonShortCuts){ StringBuffer shortcuts = new StringBuffer(); shortcuts.append(" function buttonListShorcuts() {\n"); Iterator<String> ik = usedButtonShortCuts.keySet().iterator(); Iterator<String> iv = usedButtonShortCuts.values().iterator(); while(ik.hasNext() && iv.hasNext()){ shortcuts.append(" keyArray[keyArray.length] = new keyArrayItem(\"").append(ik.next()).append("\", \"").append(iv.next()).append("\", null, \"altKey\", false, \"onkeydown\");\n"); } shortcuts.append(" return true;\n}"); return shortcuts.toString(); } private int saveRecord(VariablesSecureApp vars, OBError myError, char type, String strPC_BPartner_ID) throws IOException, ServletException { LocationAddressData data = null; int total = 0; if (org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(this, vars.getRole(), tabId)) { OBError newError = Utility.translateError(this, vars, vars.getLanguage(), Utility.messageBD(this, "NoWriteAccess", vars.getLanguage())); myError.setError(newError); vars.setMessage(tabId, myError); } else { Connection con = null; try { con = this.getTransactionConnection(); data = getEditVariables(con, vars, strPC_BPartner_ID); data.dateTimeFormat = vars.getSessionValue("#AD_SqlDateTimeFormat"); String strSequence = ""; if(type == 'I') { strSequence = SequenceIdData.getUUID(); if(log4j.isDebugEnabled()) log4j.debug("Sequence: " + strSequence); data.cBpartnerLocationId = strSequence; } if (Utility.isElementInList(Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),data.adClientId) && Utility.isElementInList(Utility.getContext(this, vars, "#User_Org", windowId, accesslevel),data.adOrgId)){ if(type == 'I') { total = data.insert(con, this); } else { //Check the version of the record we are saving is the one in DB if (LocationAddressData.getCurrentDBTimestamp(this, data.cBpartnerLocationId).equals( vars.getStringParameter("updatedTimestamp"))) { total = data.update(con, this); } else { myError.setMessage(Replace.replace(Replace.replace(Utility.messageBD(this, "SavingModifiedRecord", vars.getLanguage()), "\\n", "<br/>"), "&quot;", "\"")); myError.setType("Error"); vars.setSessionValue(tabId + "|concurrentSave", "true"); } } } else { OBError newError = Utility.translateError(this, vars, vars.getLanguage(), Utility.messageBD(this, "NoWriteAccess", vars.getLanguage())); myError.setError(newError); } releaseCommitConnection(con); CrudOperations.UpdateCustomFields(tabId, data.cBpartnerLocationId, vars, this); } catch(Exception ex) { OBError newError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage()); myError.setError(newError); try { releaseRollbackConnection(con); } catch (final Exception e) { //do nothing } } if (myError.isEmpty() && total == 0) { OBError newError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError"); myError.setError(newError); } vars.setMessage(tabId, myError); if(!myError.isEmpty()){ if(data != null ) { if(type == 'I') { data.cBpartnerLocationId = ""; } else { } vars.setEditionData(tabId, data); } } else { vars.setSessionValue(windowId + "|C_BPartner_Location_ID", data.cBpartnerLocationId); } } return total; } public String getServletInfo() { return "Servlet LocationAddress. This Servlet was made by Wad constructor"; } // End of getServletInfo() method }
c29979fef650a6372a34a7556b147d1025856cec
cc4d254ace9fbb01333537a33d752ae535ef28c2
/Testing/app/src/main/java/com/adityadua/testing/MainActivity.java
52b1106f93b29834ab0219b1dc37f40ed0225ded
[]
no_license
aditya-dua/Android19May
511531d4324b39c6e34257b8d60adfa803afa826
f36fc49d67a76e75294443697d33cd5d98d89738
refs/heads/master
2020-03-18T17:17:21.005919
2018-09-02T04:21:45
2018-09-02T04:21:45
135,018,910
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
package com.adityadua.testing; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
873b735fe3701c5a73737f0f64875c27e9a9567e
36b22198fbda941e8fe519ba48deb7b305999ad2
/src/com/javarush/test/level33/lesson15/big01/Helper.java
85e7477403a146096a073b6d97e59ae695492d25
[]
no_license
VladislavKrets/JavaRushHomeWork
d44cac84c0a4b9637e9fd95a4fbc623c29afb301
97048dad0075d79a4746f73fb7e1511c2cc428f6
refs/heads/master
2021-01-21T16:48:06.256024
2017-05-20T18:07:43
2017-05-20T18:07:43
91,831,681
0
0
null
null
null
null
UTF-8
Java
false
false
458
java
package com.javarush.test.level33.lesson15.big01; import java.math.BigInteger; import java.security.SecureRandom; /** * Created by lollipop on 19.07.2016. */ public class Helper { private static SecureRandom random = new SecureRandom();; public static String generateRandomString() { return new BigInteger(130, random).toString(32); } public static void printMessage(String message) { System.out.println(message); } }
97c3768af6a0a9edd01072ef1668ff79df14c2a8
8528f9e13c26c275adbeaf25eb1cf4673ead9d9c
/common/src/main/java/com/huayue/common/enums/check/Check.java
2180e015a91799de5a4996fc5e0a44da854164ed
[]
no_license
huayue1012243788QQ/practice
3760ab5e38c3523545ddf64da2f8b955ca36e2fd
7965d9fb8cb00436a1a1dc42b26a6a9c468a5eef
refs/heads/master
2020-04-30T14:29:40.745752
2019-04-25T08:05:04
2019-04-25T08:05:04
142,087,658
1
0
null
null
null
null
UTF-8
Java
false
false
166
java
package com.huayue.common.enums.check; /** * @author huayue. * @email [email protected] * @date 2019/2/18. */ public enum Check { CHECKED, UNCHECKED }
a4ca2a552603ff56c1417a02f7d181f150b2d714
d8d23c6b0b2af190009188dd03aa036473e8b717
/urule-core/src/main/java/com/bstek/urule/model/rule/lhs/BaseCriteria.java
6d17750000f5e74f01787b2819da6490129f07c2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wuranjia/myRule
30b3fdb73659221c32f88c968449de0b5cc29ded
6fd0cd6c13ac23ad7f678dda9def8b553d72901e
refs/heads/master
2022-12-16T09:45:05.495146
2019-10-17T02:10:21
2019-10-17T02:10:21
215,682,587
1
0
Apache-2.0
2022-12-10T03:12:54
2019-10-17T02:05:48
JavaScript
UTF-8
Java
false
false
1,101
java
/******************************************************************************* * Copyright 2017 Bstek * * 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.bstek.urule.model.rule.lhs; import java.util.List; import com.bstek.urule.runtime.rete.EvaluationContext; /** * @author Jacky.gao * @since 2016年8月15日 */ public interface BaseCriteria { EvaluateResponse evaluate(EvaluationContext context,Object obj,List<Object> allMatchedObjects); String getId(); }
d6e5f1544a159086e05e56b637f614970b79f4a1
5ecd15baa833422572480fad3946e0e16a389000
/framework/MCS-Open/subsystems/runtime/main/api/java/com/volantis/mcs/papi/impl/RegionElementImpl.java
8d9af3400a4efa1291e07d3a8bb27a5a8cecbe0f
[]
no_license
jabley/volmobserverce
4c5db36ef72c3bb7ef20fb81855e18e9b53823b9
6d760f27ac5917533eca6708f389ed9347c7016d
refs/heads/master
2021-01-01T05:31:21.902535
2009-02-04T02:29:06
2009-02-04T02:29:06
38,675,289
0
1
null
null
null
null
UTF-8
Java
false
false
9,315
java
/* This file is part of Volantis Mobility Server. Volantis Mobility Server is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Volantis Mobility Server is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Volantis Mobility Server.  If not, see <http://www.gnu.org/licenses/>. */ /* ---------------------------------------------------------------------------- * $Header: /src/voyager/com/volantis/mcs/papi/RegionElement.java,v 1.8 2003/03/20 15:15:31 sumit Exp $ * ---------------------------------------------------------------------------- * (c) Volantis Systems Ltd 2001. * ---------------------------------------------------------------------------- * Change History: * * Date Who Description * --------- --------------- ----------------------------------------------- * 02-Nov-01 Paul VBM:2001102403 - Created. * 19-Nov-01 Paul VBM:2001110202 - Skip the region if the page * is fragmented and it is not part of the * current fragment. * 19-Dec-01 Paul VBM:2001120506 - Renamed from * tags.RegionElement and made compatible with * PAPI elements. * 02-Jan-02 Paul VBM:2002010201 - Use log4j for logging. * 18-Mar-02 Ian VBM:2002031203 Changed log4j Category from * class to string. * 22-Feb-02 Paul VBM:2002021802 - Fixed ordering of call to * super.elementReset. * 22-Oct-02 Geoff VBM:2002102102 - Backed out the last change * for VBM:2002091203. * 11-Mar-03 Steve VBM:2003022403 - Added public api doclet tags * 20-Mar-03 sumit VBM:2003031809 - Wrapped logger.debug * statements in if(logger.isDebugEnabled()) block * 23-Apr-03 Steve VBM:2003041606 - Override hasMixedContent() to * return false * 19-May-03 Chris W VBM:2003051902 - hasMixedContent() made package * protected. * ---------------------------------------------------------------------------- */ package com.volantis.mcs.papi.impl; import com.volantis.mcs.context.ContextInternals; import com.volantis.mcs.context.MarinerPageContext; import com.volantis.mcs.context.MarinerRequestContext; import com.volantis.mcs.layouts.NDimensionalIndex; import com.volantis.mcs.layouts.Region; import com.volantis.mcs.localization.LocalizationFactory; import com.volantis.mcs.papi.PAPIAttributes; import com.volantis.mcs.papi.PAPIException; import com.volantis.mcs.papi.RegionAttributes; import com.volantis.mcs.protocols.FormatReference; import com.volantis.mcs.protocols.layouts.RegionInstance; import com.volantis.mcs.runtime.FormatReferenceParser; import com.volantis.synergetics.localization.ExceptionLocalizer; import com.volantis.synergetics.log.LogDispatcher; /** * An initial implementation of a PAPI style element class. * It has no state, so only one instance needs to be created. It may be * advisable to add some state in which case it needs to be managed. */ public class RegionElementImpl extends AbstractExprElementImpl { /** * Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(RegionElementImpl.class); /** * Used to retrieve localized exception messages. */ private static final ExceptionLocalizer exceptionLocalizer = LocalizationFactory.createExceptionLocalizer( RegionElementImpl.class); /** * The RegionInstance which this element uses. */ private RegionInstance regionInstance; /** * Flag which indicates whether the elementStart method returned * SKIP_ELEMENT_BODY. */ private boolean skipped; // Javadoc inherited. protected int exprElementStart( MarinerRequestContext context, PAPIAttributes papiAttributes) throws PAPIException { MarinerPageContext pageContext = ContextInternals.getMarinerPageContext(context); RegionAttributes attributes = (RegionAttributes) papiAttributes; if (logger.isDebugEnabled()) { logger.debug("RegionElement start " + attributes.getName()); } String regionName = attributes.getName(); if (regionName == null) { logger.error("region-name-missing"); throw new PAPIException( exceptionLocalizer.format("region-name-missing")); } FormatReference formatRef = FormatReferenceParser.parse(regionName, pageContext); Region region = pageContext.getRegion(formatRef.getStem()); NDimensionalIndex regionIndex = formatRef.getIndex(); if (region == null) { logger.info("region-missing", new Object[]{attributes.getName()}); skipped = true; return SKIP_ELEMENT_BODY; } regionInstance = (RegionInstance) pageContext.getFormatInstance( region, regionIndex); if (regionInstance.ignore()) { skipped = true; return SKIP_ELEMENT_BODY; } pageContext.pushContainerInstance(regionInstance); // Fake an open element so that whitespace is handled normally since we // have no element to represent pane at the moment. pageContext.getCurrentOutputBuffer() .handleOpenElementWhitespace(); return PROCESS_ELEMENT_BODY; } // Javadoc inherited. protected int exprElementEnd( MarinerRequestContext context, PAPIAttributes papiAttributes) throws PAPIException { MarinerPageContext pageContext = ContextInternals.getMarinerPageContext(context); // Fake a close element so that whitespace is handled normally since we // have no element to represent pane at the moment. pageContext.getCurrentOutputBuffer() .handleCloseElementWhitespace(); RegionAttributes attributes = (RegionAttributes) papiAttributes; if (logger.isDebugEnabled()) { logger.debug("RegionElement end " + attributes.getName()); } if (skipped) { return CONTINUE_PROCESSING; } pageContext.popContainerInstance(regionInstance); return CONTINUE_PROCESSING; } // Javadoc inherited from super class. public void elementReset(MarinerRequestContext context) { regionInstance = null; skipped = false; super.elementReset(context); } // Javadoc inherited from super class. boolean hasMixedContent() { return false; } } /* =========================================================================== Change History =========================================================================== $Log$ 03-Oct-05 9673/1 pduffin VBM:2005092906 Added support for targeting content at layout using styles 24-Jun-05 8878/1 emma VBM:2005062306 Building calls to the styling engine into the framework and fixing NPE 20-Jun-05 8483/2 emma VBM:2005052410 Migrate styling to use the new styling support framework (still using CSSEmulator to style underneath) 02-Jun-05 8005/4 pduffin VBM:2005050404 Moved dom to its own subsystem 05-May-05 8005/1 pduffin VBM:2005050404 Separated DOM from within runtime into its own subsystem, move concrete DOM objects out of API, replaced with interfaces and factories, removed pooling 24-May-05 8123/7 ianw VBM:2005050906 Fix accurev merge issues 18-May-05 8196/2 ianw VBM:2005051203 Refactored PAPI to seperate out implementation 05-Apr-05 7459/3 tom VBM:2005032101 Added SmartClientSkin protocol 04-Apr-05 7459/1 tom VBM:2005032101 Added SmartClientSkin protocol 08-Dec-04 6416/3 ianw VBM:2004120703 New Build 08-Dec-04 6416/1 ianw VBM:2004120703 New Build 29-Nov-04 6232/4 doug VBM:2004111702 Refactored Logging framework 05-Nov-04 6112/2 byron VBM:2004062909 Rename FormatContext et al to something more appropriate given recent changes. 02-Nov-04 5882/1 ianw VBM:2004102008 Split Code generators and move NDimensionalIndex for new build 29-Jun-04 4713/7 geoff VBM:2004061004 Support iterated Regions (make format contexts per format instance) 21-Jun-04 4713/3 geoff VBM:2004061004 Support iterated Regions (commit prototype for safety) 19-Feb-04 2789/3 tony VBM:2004012601 refactored localised logging to synergetics 12-Feb-04 2789/1 tony VBM:2004012601 Localised logging (and exceptions) 13-Aug-03 958/1 chrisw VBM:2003070704 implemented expr attribute on papi elements =========================================================================== */
[ "iwilloug@b642a0b7-b348-0410-9912-e4a34d632523" ]
iwilloug@b642a0b7-b348-0410-9912-e4a34d632523
1b56dcb090fd9c2bd3359877fdfc44975bb589dc
3d1773a8ee1457eb50f1839914b6f236aecea45f
/src/array2/MiniAbsoluteDifferent.java
e45c945580e65d0ee84f171617af7ee708119972
[]
no_license
anujpachauri/datastrature
5ee0d143d214f7313665ccaf650b50041a80eebd
be07b0b98d1e187af2b2e6819418a134532fe0ff
refs/heads/master
2021-06-29T04:18:56.077138
2020-03-14T20:39:37
2020-03-14T20:39:37
174,789,437
0
0
null
2020-10-13T20:21:40
2019-03-10T07:04:22
Java
UTF-8
Java
false
false
1,051
java
package array2; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Anuj Pachauri * * 1:53:09 am */ public class MiniAbsoluteDifferent { public static List<List<Integer>> absoluteDiff(int nums[]) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<>(); int min = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 1; i++) { List<Integer> list1 = new ArrayList<>(); int mindi = Math.abs(nums[i] - nums[i + 1]); min = Math.min(min, mindi); } for (int i = 0; i < nums.length - 1; i++) { List<Integer> list1 = new ArrayList<>(); int mindi = Math.abs(nums[i] - nums[i + 1]); if (min == mindi) { list1.add(nums[i]); list1.add(nums[i + 1]); list.add(list1); } } System.out.println(" Minimum Difference : " + min); return list; } public static void main(String[] args) { int nums[] = { 4, 2, 1, 3 }; int nums1[] = { 1, 3, 6, 10, 15 }; absoluteDiff(nums); absoluteDiff(nums1); } }
1c52ee5d7fd5af5f9a1f0a84309dd30bb2946671
326d5d42687f21884d5fc1f40a0e60c8ac21a274
/src/main/java/com/earandap/vehiculos/domain/nomenclador/Nomenclador.java
85e735f034c7d9c15fe55947b0ff7a3c83b771bf
[]
no_license
fdbatista/seguridad-vial
a6c50599ebde83012e4910ff9587a0b8c43f512a
ed628db23fac3b93a1428de161909d516f10a709
refs/heads/master
2020-04-14T18:29:56.307471
2019-01-03T20:45:26
2019-01-03T20:45:26
164,021,251
1
0
null
null
null
null
UTF-8
Java
false
false
2,096
java
package com.earandap.vehiculos.domain.nomenclador; import java.io.Serializable; import org.hibernate.annotations.DiscriminatorOptions; import javax.persistence.*; /** * @Autor Eduardo Aranda * @Version 0.1 */ @Entity @Table(name = "nomenclador") @SequenceGenerator(sequenceName = "nomenclador_seq", name = "SEQ_NOMENCLADOR") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "nomenclador_tipo", discriminatorType = DiscriminatorType.STRING) @DiscriminatorOptions(force = true) public class Nomenclador implements Serializable { @Id @Column(name = "nomenclador_id") @GeneratedValue(generator = "SEQ_NOMENCLADOR", strategy = GenerationType.AUTO) private long id; @Column(name = "nomenclador_codigo") private String codigo; @Column(name = "nomenclador_descripcion") private String descripcion; @Column(name = "nomenclador_tipo", insertable = false, updatable = false) protected String tipo; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Nomenclador other = (Nomenclador) obj; if (this.id != other.id) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (int) (this.id ^ (this.id >>> 32)); return hash; } }
93de9602d9a2126ab9b3792ef510ec18e0c2e083
35b710e9bc210a152cc6cda331e71e9116ba478c
/tc-unused/src/main/java/com/topcoder/web/openaim/dao/hibernate/DocumentDAOHibernate.java
4ffdb5164111f2facba43e08f53e8233e31efaac
[]
no_license
appirio-tech/tc1-tcnode
d17649afb38998868f9a6d51920c4fe34c3e7174
e05a425be705aca8f530caac1da907d9a6c4215a
refs/heads/master
2023-08-04T19:58:39.617425
2016-05-15T00:22:36
2016-05-15T00:22:36
56,892,466
1
8
null
2022-04-05T00:47:40
2016-04-23T00:27:46
Java
UTF-8
Java
false
false
490
java
package com.topcoder.web.openaim.dao.hibernate; import com.topcoder.web.common.dao.hibernate.Base; import com.topcoder.web.openaim.dao.DocumentDAO; import com.topcoder.web.openaim.model.Document; /** * @author dok * @version $Revision: 68803 $ Date: 2005/01/01 00:00:00 * Create Date: Aug 1, 2006 */ public class DocumentDAOHibernate extends Base implements DocumentDAO { public Document find(Long id) { return (Document) super.find(Document.class, id); } }
1a41c5b5db83baf7e4247ea3316f0b3d028fba67
978841603b5b3e849996d6f0f3586f7b00bb4c1d
/sell_project/src/main/java/com/xmcc/controller/WeiXinController.java
0e46ad1b229a76bded72df17909499f45c694e4f
[]
no_license
806969786/project
db78c4f8594bf59a304ec33d90d806002ce63a9a
72f09193eecb19d563e068583ddadb13b7a10f10
refs/heads/master
2022-10-22T12:36:48.811084
2019-07-06T02:32:45
2019-07-06T02:32:45
192,695,368
0
1
null
2022-10-12T20:28:40
2019-06-19T08:52:34
Java
UTF-8
Java
false
false
953
java
package com.xmcc.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("weixin") @Slf4j public class WeiXinController { @RequestMapping("getCode") private void getCode(@RequestParam("code") String code){ log.info("进入getCode回调方法"); log.info("获得当前微信用户的授权码为:{}",code); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcec0b9e65c084712&secret=05a7e861c1985ced86af77fb8f7163bc&code="+code+"&grant_type=authorization_code"; RestTemplate restTemplate = new RestTemplate(); String forObject = restTemplate.getForObject(url, String.class); System.out.println(forObject); } }
45b497743403cff2f9ce2400a6b316a23fe91b2d
8b7cae4f0eed8fe2b55e48a4474a087b95a48b42
/src/cn/zhouchenxi/xxqp/controller/connectServer.java
4eeef59c0e0d17ebff2c40a71a19cc09358063da
[]
no_license
dawn520/xxqp
a7d1005b24ac9e72f8c3b7b9eb66136afcfad3ff
322bfd5e82aed85d0ed9a594535e013e26f2a9fb
refs/heads/master
2021-06-11T13:06:43.049108
2017-02-10T12:36:41
2017-02-10T12:36:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,420
java
package cn.zhouchenxi.xxqp.controller; import sun.misc.BASE64Encoder; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by zhouchenxi on 2016/3/5. * 连接到到服务器的类的封装 * 2016/4/15更新 */ public class connectServer { public static HashMap getData(String requestUrl,String method, HashMap map) { HashMap remap = new HashMap<>(); try { // 请求的地址 String spec = requestUrl; // 根据地址创建URL对象 URL url = new URL(spec); // 根据URL对象打开链接 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // 设置请求的方式 urlConnection.setRequestMethod(method); // 设置请求的超时时间 urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); // 遍历map输出为要传递的数据 String data =""; int isFirst = 1; for (Object obj : map.keySet()) { Object value = map.get(obj); if(isFirst==1) { data = obj.toString() + "=" + URLEncoder.encode(value.toString(), "UTF-8"); }else{ data = data + "&" + obj.toString() + "=" + URLEncoder.encode(value.toString(), "UTF-8"); } isFirst++; } // 设置请求的头 urlConnection.setRequestProperty("Connection", "keep-alive"); // 设置请求的头 urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置请求的头 urlConnection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length)); // 设置请求的头 urlConnection .setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0"); urlConnection.setDoOutput(true); // 发送POST请求必须设置允许输出 urlConnection.setDoInput(true); // 发送POST请求必须设置允许输入 //setDoInput的默认值就是true urlConnection.connect(); //获取输出流 OutputStream os = urlConnection.getOutputStream(); os.write(data.getBytes()); os.flush(); os.close(); if (urlConnection.getResponseCode() == 200) { // 获取响应的输入流对象 InputStream is = urlConnection.getInputStream(); // 创建字节输出流对象 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 定义读取的长度 int len; // 定义缓冲区 byte buffer[] = new byte[1024]; // 按照缓冲区的大小,循环读取 while ((len = is.read(buffer)) != -1) { // 根据读取的长度写入到os对象中 baos.write(buffer, 0, len); } // 释放资源 is.close(); baos.close(); // 返回字符串 final String result = new String(baos.toByteArray()); // System.out.println(result.toString()); remap.put("data", result); remap.put("state", 1);//返回状态为1,连接服务器成功 } else { remap.put("state",0);//返回状态为0,连接服务器失败 } } catch (UnsupportedEncodingException e) { remap.put("state",0); // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { remap.put("state",0); // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { remap.put("state",0); // TODO Auto-generated catch block e.printStackTrace(); } return remap; } }
92aa59877bcdc92d52670be5c58db3fa92744cdd
5f7f699f9d66aa3762b5286c26a3214a34a862b2
/Effective_Java/src/enumWithAnnotation/item34/OperationTest.java
793a1237e5ace420096c47446fe351c1e1c74391
[]
no_license
w32807/Effective_Java
41659857029bd0eef7d65f064b34eba9998c0b4d
fd27152cb342cafec9f3660ce4d3dc955a6de97f
refs/heads/master
2023-06-12T09:34:39.478918
2021-07-04T01:15:05
2021-07-04T01:15:05
382,617,137
0
0
null
null
null
null
UTF-8
Java
false
false
956
java
package enumWithAnnotation.item34; public class OperationTest { public static void main(String[] args) { double x = Double.parseDouble("2"); double y = Double.parseDouble("4"); for(Operation op : Operation.values()) { System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y)); } System.out.println(Operation.fromString("+").isPresent() ? Operation.fromString("+").get() : "값 없음"); System.out.println(Operation.fromString("++").isPresent() ? Operation.fromString("++").get() : "값 없음"); System.out.println(Operation.TIMES); System.out.println(PayrollDay.MONDAY.pay(500,10)); System.out.println(PayrollDay.TUESDAY.pay(500, 10)); System.out.println(PayrollDay.WEDNESDAY.pay(500,10)); System.out.println(PayrollDay.THURSDAY.pay(500, 10)); System.out.println(PayrollDay.FRIDAY.pay(500, 10)); System.out.println(PayrollDay.SATURDAY.pay(500, 10)); System.out.println(PayrollDay.SUNDAY.pay(500, 10)); } }
d7ac3aa302dceee8b313256a63550b5c5bbb0e0a
e9c2f8cdcee975a5900ecdc12e50aefc1f8be813
/spring-framework/test/org/springframework/jmx/AbstractJmxTests.java
ec98b00a54192a91bbac169d2921af661ff5de2d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
z-dp/springsource
feee1c285667098b72ff65c95a5e8fa5e2aa4b07
e217eeb091c27834409ac5ee55b690b8e669c2e8
refs/heads/master
2020-04-10T03:19:35.581789
2018-12-07T04:10:04
2018-12-07T04:10:04
160,766,989
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
/* * Created on Jul 5, 2004 */ package org.springframework.jmx; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Rob Harrop */ public abstract class AbstractJmxTests extends AbstractMBeanServerTests { private ClassPathXmlApplicationContext ctx; protected void onSetUp() throws Exception { ctx = new ClassPathXmlApplicationContext(getApplicationContextPath()); } protected String getApplicationContextPath() { return "org/springframework/jmx/applicationContext.xml"; } protected ApplicationContext getContext() { return this.ctx; } }
4416172aa8191910f8ebecd629a9baca62fb9528
bfe5b59ae79a198900ff5b26edcfbed24f55ea20
/src/main/java/hello/Application.java
aa99be5f7cdde13925678a9445768f72d29678d9
[]
no_license
learniteasy/spring-data-REST-demo
1076abbe8e50ab4ae2de644f6e40ef2dd2470961
f5dcf81986e9bdfa2afa4b34efde4f2507fbe83d
refs/heads/master
2020-04-20T12:29:07.217587
2019-02-03T01:18:50
2019-02-03T01:18:50
168,844,500
0
0
null
null
null
null
UTF-8
Java
false
false
740
java
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Spring Data REST builds on top of Spring MVC. It creates a collection of * Spring MVC controllers, JSON converters, and other beans needed to provide a * RESTful front end. These components link up to the Spring Data JPA backend. * Using Spring Boot this is all autoconfigured; if you want to investigate how * that works, you could start by looking at the RepositoryRestMvcConfiguration * in Spring Data REST. * * @author arahee001c * */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
3e45d633bc41ad289ca3a977fc569d02c38e1c4c
3b1979bea7d7e2afbac769f2bdf4fcca0612044a
/bearmaps/hw4/AStarSolver.java
21df451c1336607f7e2c32d8bf068bd9cd678005
[]
no_license
jiangdada1221/Bearmap
ff7449d3db17b7a308e73e0fb708e02950158c9e
20939bdee94e7acc8f38982f1f57730f73ec27e4
refs/heads/master
2021-07-11T12:35:09.517989
2020-11-03T09:26:05
2020-11-03T09:26:05
212,182,637
1
1
null
null
null
null
UTF-8
Java
false
false
3,403
java
package bearmaps.hw4; import bearmaps.proj2ab.ArrayHeapMinPQ; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AStarSolver<Vertex> implements ShortestPathsSolver<Vertex>{ private double distance; double timeUsed; HashMap<Vertex, Double> disTo; HashMap<Vertex, Vertex> edgeTo; ArrayHeapMinPQ<Vertex> pq; int state; Vertex start; Vertex end; int num; public AStarSolver(AStarGraph<Vertex> input, Vertex start, Vertex end, double timeout) { this.start = start; this.end = end; num = 0; pq = new ArrayHeapMinPQ<>(); pq.add(start,0); disTo = new HashMap<>(); edgeTo = new HashMap<>(); disTo.put(start,0.0);edgeTo.put(start,start); state = 0; // 0 means solved, 1 means unsolved, 2 means timeout double time1 = System.currentTimeMillis(); while (true) { Vertex p = pq.removeSmallest(); num++; if (p.equals(end)) break; for (WeightedEdge<Vertex> edge: input.neighbors(p)) { Vertex q = edge.to();double w = edge.weight(); if (disTo.get(q) == null) { disTo.put(q,w+disTo.get(p)); edgeTo.put(q,p); pq.add(q,disTo.get(p)+w+input.estimatedDistanceToGoal(q,end)); }else { if (disTo.get(p)+w< disTo.get(q)) { disTo.replace(q,disTo.get(p)+w); edgeTo.replace(q,p); if (pq.contains(q)) pq.changePriority(q,disTo.get(q)+input.estimatedDistanceToGoal(q,end)); else pq.add(q,disTo.get(q) + input.estimatedDistanceToGoal(q,end)); } } } if (System.currentTimeMillis() - time1 > timeout*1000){ timeUsed = 0; state = 2; break; } if (pq.size()==0) { timeUsed = 1; break; } } if (state == 0) timeUsed = (System.currentTimeMillis() - time1)/1000; } @Override public SolverOutcome outcome() { if (state == 0) return SolverOutcome.SOLVED; else if (state == 1) return SolverOutcome.UNSOLVABLE; else return SolverOutcome.TIMEOUT; } @Override public List<Vertex> solution() { List<Vertex> result = new ArrayList<>(); if (outcome().equals(SolverOutcome.UNSOLVABLE) || outcome().equals(SolverOutcome.TIMEOUT)) return result; // Vertex start = edgeTo.get() result.add(end); Vertex get = edgeTo.get(end); while (get != start) { result.add(get); get = edgeTo.get(get); } result.add(start); return result; } @Override public double solutionWeight() { return disTo.get(end); } @Override public int numStatesExplored() { return num; } @Override public double explorationTime() { return this.timeUsed; } public static void main(String[] args) { HashMap<String,Integer> hash = new HashMap<>(); System.out.println(hash.get("1")); } }
2e4069e0dda10fd91c38109ba29da276035b6d88
9ad211e5d970441e3af0c34f8f2b4c04b3fa8e38
/src/main/java/com/banckom/game/model/Position.java
9a21926cf2348e22de2ab82cb475052ef7613a9d
[]
no_license
ayarmakovich/game-exercise
686f33ecc5414989deed1888743fd5afec899d35
02dee00b16ea14417c5cf773d5bb1445ce755206
refs/heads/master
2020-03-22T18:03:16.845577
2018-07-13T10:53:48
2018-07-13T10:53:48
140,433,755
0
0
null
null
null
null
UTF-8
Java
false
false
1,290
java
package com.banckom.game.model; /** * A position (x,y) on the playing area * * @author a-yarmakovich */ public class Position { private double x; private double y; private long timestamp; /** * Constructs a new position * @param x an x value * @param y an y value * @param timestamp a timestamp */ public Position(double x, double y, long timestamp) { this.x = x; this.y = y; this.timestamp = timestamp; } /** * Gets the x value * @return the x value */ public double getX() { return x; } /** * Sets an x value * @param x a new x value */ public void setX(double x) { this.x = x; } /** * Gets the y value * @return the y value */ public double getY() { return y; } /** * Sets an y value * @param y a new x value */ public void setY(double y) { this.y = y; } /** * Gets the timestamp * @return the timestamp */ public long getTimestamp() { return timestamp; } /** * Sets a timestamp * @param timestamp a new timestamp */ public void setTimestamp(long timestamp) { this.timestamp = timestamp; } }
bcdc9dc429f220068aa72519b8541374eb3550f3
0fc66d95abdb51334479fee012f0ae8364958c52
/src/InsertionSort.java
e90ca25b1426bc2f6b1ea7d4db8800692d0123ea
[]
no_license
LucasLuigiT/java-sorting
9358abf71bdcfa0cc6ff0d6dc8f58da291f87ab4
69a57dee2e2c64d01f42d51f1ca766e0f73b3f7a
refs/heads/master
2022-11-20T17:11:15.112039
2019-04-29T18:51:00
2019-04-29T18:51:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
900
java
import java.util.ArrayList; import java.util.Arrays; public class InsertionSort { static int comparacoes = 0; public InsertionSort() { this.comparacoes = comparacoes; } public static int[] insertionSort(int[] vetor){ for (int i = 0; i < vetor.length; i++){ int num = vetor[i]; for (int j = i - 1; j >= 0 && vetor[j] > num; j--){ vetor[j + 1] = vetor[j]; vetor[j] = num; comparacoes++; } } return vetor; } static ArrayList ordenar(ArrayList lista){ ArrayList listaOrdenada = new ArrayList(); for (Object n: lista) { int[] copia = (int[]) n; int[] vetorOrdenado = Arrays.copyOf(copia, copia.length); listaOrdenada.add(insertionSort(vetorOrdenado)); } return listaOrdenada; } }
5beca0d339f105d1b97e16e0817f76a39681db50
33a345069e6c5c12ade7bd677a93b9f4a69d4949
/src/com/nostalgi/engine/scene/IMaterial.java
baad27175e8528fc14342e1ef226f248073c5ac2
[]
no_license
madebykrol/Nostalgi
5449f346808b093fb9a1d39c80061ab9c49d9aab
eac2cc2f9b0d843dbea5a72e1385e77c5ed2f902
refs/heads/master
2021-01-01T17:43:04.029657
2019-11-11T10:30:38
2019-11-11T10:30:38
19,542,301
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package com.nostalgi.engine.scene; import java.nio.FloatBuffer; import com.nostalgi.math.ColorRGBA; public interface IMaterial { public ColorRGBA getColor(); public void setColor(ColorRGBA color); }
5b4baf15b48074cdedf61cd960d39ce33e3a5911
136861504b03447fdec987c6982f41615aea157c
/Word_Loan.java
db4da539601dd406bd0c56252a82d4949cc4591e
[]
no_license
da-hyeon/HangleKing
6e08ac06be9fca2de87c79407fc2caa6465bb139
52c228d4ae826214bda08ddcf19c41118c1039b0
refs/heads/master
2020-03-22T15:46:41.785503
2018-07-09T15:53:46
2018-07-09T15:53:46
140,276,040
0
0
null
null
null
null
UTF-8
Java
false
false
2,050
java
package com.hangleking.hdh.hangleking; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Display; import android.view.WindowManager; import java.util.Random; public class Word_Loan { public int nW_x, nW_y ; // 단어 좌표 public int sW_x, sW_y ; // 단어 크기 public int m_rad; public Bitmap LoanWord; // 단어 이미지 public long lastTime_LoanWord; // 경과 시간 public boolean dead = false; // 터질것인지 여부 public int alpha = 255; // 이미지의 Alpha (투명도) public int index = (int) (Math.random() * 4); //단어개수만큼 랜덤ㄱ public static final int ran[]= { R.drawable.loanword_bag , R.drawable.loanword_game , R.drawable.loanword_gas , R.drawable.loanword_godu , R.drawable.loanword_gomu }; private int res = ran[index]; //res에 ran에서 랜덤으로 하나 뽑은것을 저장 //---------------------------------- // 생성자 //---------------------------------- public Word_Loan(int _x, int _y , Context context){ Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); nW_x = _x; nW_y = _y; sW_x = display.getWidth() / 5; //이미지의 x축 크기 sW_y = display.getHeight() / 5; //이미지의 y축 크기 m_rad = ((sW_x^2 + sW_y^2) / 3); LoanWord = BitmapFactory.decodeResource(context.getResources(), res); //이미지생성 LoanWord = Bitmap.createScaledBitmap(LoanWord, sW_x, sW_y, true); //크기조정 lastTime_LoanWord = System.currentTimeMillis (); // 현재 시각 } //---------------------------------- // Alpha값 변경 //---------------------------------- public boolean WordLoan_MeltHole() { alpha -= 5; if (alpha <= 0) return true; else return false; } }
5b3ef16803656772c09762d54588645b827bc022
b5b41e68812a831b490aa3ec8239b9dfaa6c8d1c
/src/common/ast/StringLiteral.java
b7e10110868d28b0edae64dc26d1709d1cfbea8f
[]
no_license
helensgit/stone-copy
49ce12e08a8ee0dbaef6ed99937a248c1e61495e
ee375c1a9eb52b30c88a875eb8896fae54af31bd
refs/heads/master
2021-01-20T19:40:23.408399
2016-07-28T02:11:31
2016-07-28T02:11:31
63,512,155
0
0
null
2016-07-28T02:11:32
2016-07-17T03:02:55
Java
UTF-8
Java
false
false
434
java
package common.ast; import common.env.Environment; import common.token.Token; public class StringLiteral extends ASTLeaf { public StringLiteral(Token token) { super(token); } public String value() { return getToken().getText(); } @Override public Object eval(Environment env) { return value(); } @Override public String toString() { return "stringliteral:" + super.toString(); } }
0e50b42891e9772abaf7cec850c25bfa2c721cda
9cebb2dd3e334df12b46c07de0ad34695b33eb22
/hhsoft-model/src/main/java/com/hhsoft/cloud/model/user/constants/CredentialType.java
124d42ea9e4b85d3f8bce150870c69dde40860e9
[]
no_license
JasonBiaos/cloud-myself
b5792faa7b9ace83361d32a6f3bffe3a60c9f000
bb3b42de3c9d63fa8365d0076d3ade0f72612485
refs/heads/master
2020-04-28T09:05:53.522166
2019-04-25T08:34:56
2019-04-25T08:34:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.hhsoft.cloud.model.user.constants; /** * @ClassName: CredentialType * @Description 用户账号类型 * @Author Jason Biao * @Date 2019/3/21 13:49 * @Version 1.0 **/ public enum CredentialType { /** * 用户名 */ USERNAME, /** * 手机号 */ PHONE, /** * 微信openid */ WECHAT_OPENID, }
[ "bxc" ]
bxc
fe9a8f9bc2b10b9925ef243b3b0a6e2060c0c88f
7010d83d2a1d0f86379fc8d4a5e5897ef45ecab5
/server/sms-svc/src/main/java/com/simple/sms/SmsApplication.java
e7c9d329e94b543d116e5459a42a7f1a48e973fb
[ "MIT" ]
permissive
windwithlife/meetinglive
6260fd604b904a2b4c8dad96a753d7fdc2ee9af9
baaa65a6a8761ca76c5448a7e45d2ce73f9b8eb8
refs/heads/master
2022-12-04T08:29:16.315018
2020-08-28T03:57:25
2020-08-28T03:57:25
272,113,878
0
0
null
null
null
null
UTF-8
Java
false
false
441
java
package com.simple.sms; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class SmsApplication { public static void main(String[] args) { SpringApplication.run(SmsApplication.class, args); } }
ae4d529b47cf687a74110975b4d8b39fc271c86c
88fd524acdc5462602f00ae01a4af60d6c452bba
/app/src/main/java/com/ragabaat/myclinic/admin/TeamActivity.java
6182f24b2f747aec78fd0577f83d5c1bc4b88395
[]
no_license
ElhadiRagabaat/Clinic
945556d449774dcd4983732a1abe650236435bd5
4930fc8b8b23bb93a3ef6d3ac4434f4314794cc2
refs/heads/master
2023-02-02T00:55:14.923887
2020-12-13T22:53:33
2020-12-13T22:53:33
321,176,457
0
0
null
null
null
null
UTF-8
Java
false
false
2,893
java
package com.ragabaat.myclinic.admin; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.ragabaat.myclinic.R; import java.util.ArrayList; import java.util.List; public class TeamActivity extends AppCompatActivity { private FloatingActionButton fab; private RecyclerView recyclerView; private ProgressBar progressBar; private DatabaseReference reference,dbRef; private List<TeamData> list; private TeamAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_team); fab = findViewById(R.id.fabTeam); recyclerView = findViewById(R.id.teamList); progressBar = findViewById(R.id.progressBar); reference = FirebaseDatabase.getInstance().getReference().child("team"); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(TeamActivity.this,AddTeamActivity.class)); } }); uploadTeamDetails(); } private void uploadTeamDetails() { dbRef = reference; dbRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { list = new ArrayList<TeamData>(); for (DataSnapshot snapshot:dataSnapshot.getChildren()){ TeamData data = snapshot.getValue(TeamData.class); list.add(data); } recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(TeamActivity.this)); adapter = new TeamAdapter(list, TeamActivity.this); adapter.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); recyclerView.setAdapter(adapter); } @Override public void onCancelled(@NonNull DatabaseError error) { progressBar.setVisibility(View.GONE); Toast.makeText(TeamActivity.this,error.getMessage(),Toast.LENGTH_LONG).show(); } }); } }
36cdeb1e7f8da378082061da3f0cb911cb3581b2
2b3c4200491e15d6d1ad9a7ca3f14f7a93a0e20c
/src/main/java/com/sda/groupa/shippingcostcalculator/exchangeRateCalculator/model/CurrencyCode.java
d7f2993537b398eeb4ccf012744c075fba21e7f7
[]
no_license
nowickiark/ShippingCostCalculator
1d403d8cb445e7e73cc9476b9f05e4654d5adbb3
f769d71c950fb48e4a5857067342ca176352d51f
refs/heads/master
2021-06-26T05:54:04.637877
2019-12-05T19:11:16
2019-12-05T19:11:16
206,940,997
2
0
null
2021-03-31T21:41:58
2019-09-07T08:46:12
HTML
UTF-8
Java
false
false
169
java
package com.sda.groupa.shippingcostcalculator.exchangeRateCalculator.model; public enum CurrencyCode { PLN, EUR, GBP, CZK, NOK, CHF, HUF, SEK, UAH, DKK, RUB, USD }
c936beaa7b629406e5d6d4e0cd159b6581647894
af4c9c7b85a165b8a3bf2cd16a7f12a41f08e61a
/MyService/app/src/main/java/org/mv/service/MainActivity.java
b0a438485e580012bfc1b5386dbde8143792b0e0
[]
no_license
kartmon61/android
7d68b757f851957dd63e9589c8c9cab342db7c9a
a91a72d5dbdad7f96be05b88e7bbb73177e69a7d
refs/heads/master
2020-06-17T07:42:50.262787
2019-09-13T11:30:07
2019-09-13T11:30:07
195,849,538
0
0
null
null
null
null
UTF-8
Java
false
false
1,738
java
package org.mv.service; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.editText); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = editText.getText().toString(); Intent intent = new Intent(getApplicationContext(),MyService.class); intent.putExtra("command","show"); intent.putExtra("name",name); startService(intent); } }); Intent passedIntent = getIntent(); processCommand(passedIntent); } //메인 액티비티가 이미 만들어져 있는 상태에서 확인할수 있는 메소드 @Override protected void onNewIntent(Intent intent) { processCommand(intent); super.onNewIntent(intent); } private void processCommand(Intent intent){ if(intent != null){ String command = intent.getStringExtra("command"); String name = intent.getStringExtra("name"); Toast.makeText(this,"서비스로부터 전달받은 데이터 : " +command + ", " + name,Toast.LENGTH_LONG).show(); } } }
c59bed8f835990067a7d529fb37f50e7c5b2074a
e18ec261aa812df781924b408c1939455b16d914
/entity-essentials-api/src/main/java/org/jayware/e2/assembly/api/TreeManager.java
2439d01ab2ed26d2f74be364bdf9c0dab45a6ae8
[ "Apache-2.0" ]
permissive
jayware/entity-essentials
f30cf173cc804b7886378160cb177c7bb77c3bd9
4d4ad6060caa4f5694ac1566faf954a71f81eb9f
refs/heads/master
2021-01-19T02:27:50.822578
2017-11-04T22:32:11
2017-11-04T22:32:11
48,580,815
6
1
null
null
null
null
UTF-8
Java
false
false
1,195
java
/** * Entity Essentials -- A Component-based Entity System * * Copyright (C) 2017 Elmar Schug <[email protected]>, * Markus Neubauer <[email protected]> * * 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.jayware.e2.assembly.api; import org.jayware.e2.entity.api.EntityRef; import org.jayware.e2.event.api.Result; import java.util.List; public interface TreeManager { TreeNode createTreeNodeFor(EntityRef pendant) throws TreeManagerException; void deleteTreeNode(TreeNode node) throws TreeManagerException; List<TreeNode> findChildrenOf(TreeNode node); Result<List<TreeNode>> queryChildrenOf(TreeNode node); }
847b3d28fc4167a64fdb90adbedacc66cf66b301
7cf0dcc2a3b76570823eb1c72f3976bcdd965fb2
/_testers_SomModules/src/org/NooLab/demoiinstances/A1_SomFluid_Application_Applet.java
824f900cf6ba3fafece2c40873971523a4b0491c
[]
no_license
Girshwick/noolabsomfluid
ecfb3525b81795048095249d972366e9626682f0
d1418e02f6db3ef6d1134670797357e26f5bc3ce
refs/heads/master
2021-01-25T05:21:37.894854
2012-11-05T18:53:02
2012-11-05T18:53:02
34,005,834
0
0
null
null
null
null
UTF-8
Java
false
false
18,525
java
package org.NooLab.demoiinstances; import processing.core.*; import org.NooLab.field.FieldIntf; import org.NooLab.somfluid.SomAppFactoryClientIntf; import org.NooLab.somfluid.SomApplicationIntf; import org.NooLab.somfluid.SomApplicationResults; import org.NooLab.somfluid.SomFluid; import org.NooLab.somfluid.SomFluidClassTaskIntf; import org.NooLab.somfluid.SomFluidFactory; import org.NooLab.somfluid.SomFluidFactoryClassifierIntf; import org.NooLab.somfluid.SomFluidMonoResultsIntf; import org.NooLab.somfluid.SomFluidProperties; import org.NooLab.somfluid.app.up.IniProperties; import org.NooLab.somfluid.app.up.SomFluidStartup; import org.NooLab.somfluid.clapp.SomAppModelLoader; import org.NooLab.somfluid.clapp.SomAppProperties; import org.NooLab.somfluid.clapp.SomAppUsageIntf; import org.NooLab.somfluid.clapp.SomApplicationEventIntf; import org.NooLab.somfluid.core.engines.det.ClassificationSettings; import org.NooLab.somfluid.properties.PersistenceSettings; import org.NooLab.somfluid.tasks.SomFluidMonoTaskIntf; import org.NooLab.somfluid.tasks.SomFluidTask; import org.NooLab.somtransform.algo.externals.AlgorithmPluginsLoader; import org.NooLab.structures.InstanceProcessControlIntf; import org.NooLab.utilities.callback.ProcessFeedBackContainerIntf; import org.NooLab.utilities.files.DFutils; import org.NooLab.utilities.files.PathFinder; import org.NooLab.utilities.logging.LogControl; /** * * This applet demonstrates the application of a SomFluid model to new data; * * here, the data source is just a file, of course, it could be a data base, * a stream or whatsoever * * the results are collected and indexed by a double key, a globally unique identifier * and a local long serial numerical id (whose start value can be set); * * indexing of results is on the level of individual records and * on the level of source accesses. * * */ public class A1_SomFluid_Application_Applet extends PApplet{ private static final long serialVersionUID = 8918471551051086099L; SomModuleInstanceA1 somInstance ; String sourceForProperties = ""; public void setup(){ background( 208,188,188); draw(); // put this on top of any application: it cares for a well-defined base directory try { SomFluidStartup.setApplicationID("soapp", this.getClass()); } catch (Exception e) { e.printStackTrace(); } showKeyCommands(); // start this in its own thread... // use LogControl to control output of log messages LogControl.globeScope = 2; // 1=local definitions default = 2 LogControl.Level = 2 ; // the larger the more detailed logging... (could be really verbose!) // testPowerSet(); } public void draw(){ background( 208,188,188); } public void keyPressed() { if (key=='c'){ // start a classification directly, a data set must be available // uses the last model, if available boolean rB=false; looping = false; this.noLoop(); if (SomFluidStartup.getLastProjectName().length()==0){ rB = openProject( ) ; key=0; }else{ rB=true; } if ((rB) && (SomFluidStartup.getLastDataSet().length()==0)){ rB = SomFluidStartup.introduceDataSet().length() > 0; } IniProperties.saveIniProperties() ; looping = true; this.loop() ; if (rB){ rB = SomFluidStartup.checkClassifierSetting(); } if ((rB) && (SomFluidStartup.getLastProjectName().length()>0) && (SomFluidStartup.getLastDataSet().length()>0)){ startEngines(); }else{ System.err.println(""); } } if (key=='s'){ // start the service for streaming "wireless" classification System.err.println("Not yet implemented."); } if (key=='d'){ looping = false; this.noLoop(); SomFluidStartup.introduceDataSet(); IniProperties.saveIniProperties() ; System.err.println("The following file has been selected as data source for classification : "+ SomFluidStartup.getLastDataSet() ); System.err.println("The project path is currently set to : " + (IniProperties.fluidSomProjectBasePath+"/"+SomFluidStartup.getLastProjectName()).replace("//", "/")); looping = true; this.loop() ; } if (key=='o'){ try { looping = false; this.noLoop(); SomFluidStartup.selectActiveProject() ; looping = true; this.loop() ; } catch (Exception e) { } } if (key=='p'){ //select a different base folder for projects looping = false; this.noLoop(); try { SomFluidStartup.selectProjectHome(); } catch (Exception e) { e.printStackTrace(); } looping = true; this.loop() ; } if (key=='z'){ interrupSomFluidProcess(); } if (key=='x'){ // somInstance. ... System.exit(0); } } private void showKeyCommands(){ println(); println("Welcome to FluidSom Demo !\n"); println("the following key commands are available for minimalistic user-based control..."); println(); println(" c -> start classification of data, if necessary, file & folder will be offered for selection"); println(); println(" d -> declare data set (as file) "); println(" s -> start as service "); println(); println(" o -> open project "); println(" p -> select project space (where all projects are located)"); println(); println(" z -> interrupt the current process, export current results and write persistent models "); println(" x -> exit"); println(); println("------------------------------------------------------------------"); } private void startEngines(){ println(); println("starting..."); println(); System.out.println("data source : " + SomFluidStartup.getLastDataSet() ); System.out.println("project name : " + SomFluidStartup.getLastProjectName() ); System.out.println("project space : " + IniProperties.fluidSomProjectBasePath); println(); somInstance = new SomModuleInstanceA1( FieldIntf._INSTANCE_TYPE_CLASSIFIER, SomFluidFactory._GLUE_MODULE_ENV_NONE, sourceForProperties ) ; somInstance.startInstance() ; } private void interrupSomFluidProcess(){ somInstance.issueUserbreak(); } private boolean openProject(){ boolean rB=false; looping = false; this.noLoop(); // that's mandatory, otherwise, the dialog won't be drawn try { SomFluidStartup.selectActiveProject(); rB=true; } catch (Exception e) { rB=false; } looping = true; this.loop() ; // http://code.google.com/p/processing/source/checkout return rB; } } // ============================================================================ /** * * this object could be instantiated by the glue layer, if there is the correct information available * * * * */ class SomModuleInstanceA1 implements Runnable, // for messages from the engine to the outer application layers like this module SomApplicationEventIntf{ SomFluidFactoryClassifierIntf sfcFactory; SomAppFactoryClientIntf _sfaFactory ; SomAppProperties soappProperties; SomApplicationIntf somApp ; SomFluidProperties sfProperties; InstanceProcessControlIntf somProcessControl ; String dataSource = ""; int instanceType = FieldIntf._INSTANCE_TYPE_CLASSIFIER ; int glueModuleMode = 0; String sourceForProperties = ""; // initial number of nodes in the SOM lattice Thread smiThrd; // ------------------------------------------------------------------------ public SomModuleInstanceA1( int instancetype, int glueMode, String propertiesSource ){ instanceType = instancetype; glueModuleMode = glueMode ; sourceForProperties = propertiesSource; smiThrd = new Thread(this, "SomApp"); } // ------------------------------------------------------------------------ public void startInstance(){ smiThrd.start(); } public void run() { classifyData(0); // via ini properties } public void issueUserbreak() { // somProcessControl.interrupt(0); } public String classifyData(int index){ SomApplicationResults somResult; SomAppModelLoader somLoader; String guid=""; if (instanceType == FieldIntf._INSTANCE_TYPE_CLASSIFIER){ dataSource = SomFluidStartup.getLastDataSet(); // just the simple name, sth like "bank_C.txt" // try { prepareSomFluidClassifier(); somApp = sfcFactory.createSomApplication( soappProperties ) ; // last settings... will be started by TaskDispatcher in SomFluid // sfTask contains a Guid ??? SomFluidClassTaskIntf sfTask = (SomFluidClassTaskIntf)sfcFactory.createTask( instanceType ); // sfTask.setStartMode(1) ; // producing the task = putting the task into the queue sfcFactory.produce( sfTask ); guid = sfTask.getGuid(); // safe this to the map index-guid } catch (Exception e) { e.printStackTrace(); } } // instance = _INSTANCE_TYPE_CLASSIFIER ? return guid; } private void explicitlySettingAppProperties(){ AlgorithmPluginsLoader lap; // loading "builtinscatalog.xml" which is necessary for global indexing and activation of built-in algorithms soappProperties.setAlgorithmsConfigPath("D:/dev/java/somfluid/plugins/"); // here we need an absolute path, the file is needed also for advanced auto assignments of built-in algorithms, // even if there are no custom algorithms soappProperties.getPluginSettings().setBaseFilePath("D:/dev/java/somfluid/plugins/", "catalog.xml") ; soappProperties.setPluginsAllowed(true) ; // could be controlled form the outside in a dynamic manner try { if (soappProperties.isPluginsAllowed()){ lap = new AlgorithmPluginsLoader(soappProperties, true); if (lap.isPluginsAvailable()) { lap.load(); } } // feedback about how much plugins loaded ... } catch (Exception e) { e.printStackTrace(); } soappProperties.setInstanceType( instanceType ) ; // "very" global: SomFluidFactory._INSTANCE_TYPE_CLASSIFIER = 7 // in this folder there should be ZIPs containing model packages or sub-folders containing the model files soappProperties.setBaseModelFolder( SomFluidStartup.getProjectBasePath(), SomFluidStartup.getLastProjectName(), "models") ; // or, less elegant + flexible, by dedicated string: // soappProperties.setBaseModelFolder("D:/data/projects/_classifierTesting/bank2/models"); // this refers to the name of the project as it is contained in the model file!! // on first loading, a catalog of available model will be created for faster access if it does not exists soappProperties.setActiveModel( SomFluidStartup.getLastProjectName() ); // sth like "bank2", i.e. just the name, it must exist as a sub-directory soappProperties.setIndexVariables( new String[]{"Id","Mahnung_TV"}); // the user might be using a compound/structured key for identification, so we map such compound id // if one of those does not exist, it will be disregarded silently // !!! note that they are not used as index at all, the are just routed through // soappProperties.setIndexVariableColumnIndexes( new int[]{0}); // alternatively (& less controlled) we could provide the list of columns // containing such index information, these indices refer to the provided data !!! // if those usage parameters are not set, the values will be taken from the model soappProperties.setRequiredConfidenceBySupport(8); soappProperties.setRiskLevelByECR(0.25) ; // if there are several model packages of the same name in the "BaseModelFolder", this // will control the mode of selection from those // soappProperties.setModelSelectionMode( SomAppProperties._MODELSELECT_VERSION,"0" ); soappProperties.setModelSelectionMode( SomAppProperties._MODELSELECT_LATEST ); soappProperties.setModelSelectionMode( SomAppProperties._MODELSELECT_BEST ); soappProperties.setModelSelectionCriteria( SomAppProperties._MODELSELECT_TARGETLABEL, "intermediate") ; // if such a label can be found, it is used as a criterion // alternatively, we set the active model to blank here, and provide the package name ; // whenever the active model name is given (and existing) it will be preferred! // clappProperties.setActiveModel(""); // clappProperties.setModelPackageName("1"); // this directory or zip-packages must exist and will be turned into /* we also need a selection mode that allows to hold multiple models, according to criteria: all of them require to provide the max number of models to be loaded - set of variables sets, SomAppProperties._MODELSELECT_MULTI_ASSIGNATES requires to provide those sets advantage: if a record contains missing values in some of the variables, we can try to select the matching model - distinctiveness of metric across models SomAppProperties._MODELSELECT_MULTI_DISTINCTSTRUC requires to provide distinctiveness criteria (number of mismatches of intensions of models) - etc. */ /* * basically we may provide 2 modes: explicit call = project mode, and waiting * * project : requires a source file by absolute path * * service : requires a service mode incl parameter: * file-based * - via supervised directory, a result file will be returned to that directory * queue-based via listener to internal port based delivery (TCP), * an external application may send / receive requests for * - confirmation of feature vector * - data tables of any size according to that vector * by containment of field labels, for each record a GUID will be returned * - get results upon request */ soappProperties.setWorkingMode( SomAppProperties._WORKINGMODE_PROJECT ) ; if ( soappProperties.getWorkingMode() == SomAppProperties._WORKINGMODE_PROJECT){ // could be any location, no preferred directory necessary, but it must exist, of course // soappProperties.setDataSourceFile("D:/data/projects/_classifierTesting/bank2/data/bank_C.txt"); soappProperties.setDataSourceFile( SomFluidStartup.getLastDataSet() ); } // if ( soappProperties.getWorkingMode() == SomAppProperties._WORKINGMODE_SERVICEFILE ){ // could be any directory, if it does not exists, it will be created soappProperties.setSupervisedDirectory( SomFluidStartup.getProjectBasePath(),SomFluidStartup.getLastProjectName(), "service"); // clappProperties.addSupervisedFilename("<namefilter>"); } // soappProperties.setInstanceType( instanceType ) ; } private void prepareSomFluidClassifier() throws Exception { String prjName, path ; soappProperties = SomAppProperties.getInstance( sourceForProperties ); soappProperties.connectGeneralProperties(); explicitlySettingAppProperties(); // does the source exist? // IniProperties. prjName = SomFluidStartup.getLastProjectName() ; // "bank2" path = IniProperties.fluidSomProjectBasePath; // TODO ... if not, exit from here via Exception sfcFactory = (SomFluidFactoryClassifierIntf) SomFluidFactory.get(soappProperties); sfcFactory.setMessagePort(this) ; somApp = sfcFactory.createSomApplication( soappProperties ); String msgProcessGuid = somApp.getMessageProcessGuid(); // a Guid that identifies the process as the master process for progress (and other) messages } @Override public void onProcessStarted( SomFluidTask sfTask, int applicationId, String pid) { if (applicationId == FieldIntf._INSTANCE_TYPE_CLASSIFIER ){ System.err.println("A classification task has been started (id: " +pid+") for task Id <"+sfTask.getGuidID()+">."); } } // ------------------------------------------------------------------------ // in a decoupled environment, these messages have to be passed through a message service, // then re-elicited by the receptor module @Override public void onClassificationPerformed(Object resultObject) { System.out.println("client received event message <onClassificationPerformed()> ") ; } // call back event that provides access to the results of a modeling SOM @Override public void onResultsCalculated( SomFluidMonoResultsIntf results ) { // System.out.println("client received event message <onResultsCalculated()> ") ; } @Override public void onCalculation(double fractionPerformed) { // in case of large tasks } @Override public void onStatusMessage(SomFluidTask sfTask, int applicationId, int errcode, String msg) { } @Override public void onProgress( ProcessFeedBackContainerIntf processFeedBackContainer ) { // processFeedBackContainer contains a guid about the master process, information about the originating object, a base message, and the progress state) double progress = processFeedBackContainer.getCompletionProgress(); String procId = processFeedBackContainer.getMessageProcessID() ; String loopingObj = processFeedBackContainer.getHostingObjectName(); if (progress>50)processFeedBackContainer.setDisplayMode( ProcessFeedBackContainerIntf._DISPLAY_SMOOTH ); // we may delegate the task of displaying back to the progress display helper processFeedBackContainer.pushDisplay( loopingObj ); } }
[ "[email protected]@5e08b179-1489-47ab-2bb8-484ae94cf756" ]
[email protected]@5e08b179-1489-47ab-2bb8-484ae94cf756
912886edca6d45c08ff5afa89275128fee3b52c5
d404e053342df7097a01cd1a91451a1ceff2075e
/fhdp/fhdp-commons/fhdp-commons-transport/src/main/java/pl/fhframework/dp/transport/dto/operations/OperationDtoQuery.java
81f5af99f65b3a0453acc6d32414ceb8eb0c2ef5
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
assecopl/fh
b7baef104c9e5fe936f2e30eaa9c103abf35e523
d53df8afb872999deae9733b26501451524fcee3
refs/heads/develop
2023-09-02T02:29:19.877030
2023-08-30T11:11:39
2023-08-30T11:11:39
196,387,011
9
16
Apache-2.0
2023-05-15T07:30:01
2019-07-11T12:08:38
Java
UTF-8
Java
false
false
736
java
package pl.fhframework.dp.transport.dto.operations; import lombok.Getter; import lombok.Setter; import pl.fhframework.dp.transport.dto.commons.BaseDtoQuery; import pl.fhframework.dp.transport.enums.NullableBooleanEnum; import pl.fhframework.dp.transport.enums.PerformerEnum; import java.time.LocalDateTime; @Getter @Setter public class OperationDtoQuery extends BaseDtoQuery { private String operationCode; private LocalDateTime formalDateFrom; private LocalDateTime formalDateTo; private NullableBooleanEnum hasAnnotation = NullableBooleanEnum.NONE; private NullableBooleanEnum hasChanges = NullableBooleanEnum.NONE; private PerformerEnum performerType = PerformerEnum.ANY; private String performer; }
3803bc2d8bfe8a2da0fce22bfbbb245cffc1cc0e
4603b544d2711dfd24df7326fc1efb7620714074
/Study/src/com/lzz/strategy/ContextRunStrategy.java
7873595dea224d6f5b19286087f6f43333520485
[]
no_license
SaitoLi/MyStudyJava
eff04b275680afa937da6e4aef7b07394acbbd7e
20de4fdaa6f14d10bf204ac91f6b22f06e40540c
refs/heads/master
2020-03-28T18:25:25.759591
2018-11-26T07:11:42
2018-11-26T07:11:42
148,880,276
0
0
null
null
null
null
GB18030
Java
false
false
452
java
package com.lzz.strategy; /** * 上下文,持有IRunStrategy的引用 * @author CunsiALIEN * */ public class ContextRunStrategy { private IRunStrategy iRunStrategy; public ContextRunStrategy(IRunStrategy iRunStrategy) { this.iRunStrategy = iRunStrategy; } /** * 选择道路 * 通过实例化的iRunStrategy对象去调用所选择的逃跑路线 */ public void choiceRoad() { iRunStrategy.escapeRoad(); } }
c2ac8c66508a84196de768534e2591009c7255f0
8eece51d61e1b365f3447c80a54a1b6d52cf095a
/src/main/java/io/link4pay/model/transaction/TransactionResponse.java
e665685d3a40f252bc9b8e296615c7910158a87a
[ "MIT" ]
permissive
neoliteconsultant/link4pay_java
b27ceb6a764597e3e69b4c23419f481e3f1f0b08
8b9248e3ee80ae0336a6aa2a4884d42f1f146404
refs/heads/main
2023-08-29T03:36:30.344137
2021-10-05T16:10:19
2021-10-05T16:10:19
399,447,980
1
0
null
null
null
null
UTF-8
Java
false
false
216
java
package io.link4pay.model.transaction; public class TransactionResponse { public Response response; public static class Response{ public String description; public int responseCode; } }
1f72c0337b2df49f69c2fe8d32e460543aa1c705
f0c025942c53485b338bc43207ffff9f8353d8da
/app/src/main/java/cn/com/jinzhong/shandonggrain/android/listener/AnimationListener.java
8281b112f92cbde8cd6a0cf64fc8d38fe6ee305d
[]
no_license
wuxinlingluan/ShandongGrain
c528ecc617a99e6ed2ff949ce00194b854ea0fed
10cb3f03e92c1504ad8e8a631bc0ec84fbc29fde
refs/heads/master
2020-06-24T23:13:13.723064
2017-07-12T00:21:24
2017-07-12T00:21:24
96,947,968
0
0
null
null
null
null
UTF-8
Java
false
false
521
java
package cn.com.jinzhong.shandonggrain.android.listener; import android.animation.Animator; /** * Created by ${sheldon} on 2017/7/11. */ public class AnimationListener implements Animator.AnimatorListener { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }
22902b9172462d017388290b399512b20642806f
04528e587474ecb44ac60a3e2008d7baaa235b22
/app/src/main/java/com/example/administrator/rainmusic/ui/fragment/MusicPlayFragment.java
3a3fb1dfcbfc746f9d224b514b3b34f94b7ad8c5
[]
no_license
DHnature/Mr.music
a2c7f9e8962124525971c4b16278c3cdc6d1e33d
cdac66a2bfa00daf84295d9711ed914a02d55e8a
refs/heads/master
2021-01-19T17:34:04.734891
2017-08-22T14:13:16
2017-08-22T14:13:16
101,070,355
0
0
null
null
null
null
UTF-8
Java
false
false
15,025
java
package com.example.administrator.rainmusic.ui.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import com.example.administrator.rainmusic.MainActivity; import com.example.administrator.rainmusic.R; import com.example.administrator.rainmusic.config.MyApplication; import com.example.administrator.rainmusic.constant.Constants; import com.example.administrator.rainmusic.httpservice.HttpUtil; import com.example.administrator.rainmusic.httpservice.PictureUtil; import com.example.administrator.rainmusic.interfaces.LyricHttpCallBackListener; import com.example.administrator.rainmusic.interfaces.PicHttpCallBackListener; import com.example.administrator.rainmusic.model.Music; import com.example.administrator.rainmusic.service.PlayerService; import com.example.administrator.rainmusic.weiget.MusicPlayView; import java.io.Serializable; import java.net.URLEncoder; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.List; public class MusicPlayFragment extends Fragment implements OnClickListener { private static String picpool[]; private static MusicPlayView mPlayView; private static int mResource; private static Button mPrevious; private static int flag = 0; private static int finish=0; private Button mPlayPause; private Button mNext; private SeekBar mSeekBar; private TextView mTextViewDuration; private TextView mTextViewCurrentTime; private TextView title; private int count; private List<Music> musiclist; private MusicBroadcast musicBroadcast; private MainActivity mainActivity = new MainActivity(); private MusicName musicName; public static Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case Constants.VAGUE: break; case Constants.ROTATE_OPEN: mResource = R.drawable.bg_default1; mPlayView.previous(mResource); mPlayView.play(); break; case Constants.ROTATE_CLOSE: mPlayView.pause(); break; case Constants.SEARCH_PICURL: String s = (String) msg.obj; String ss[] = s.split("\"picUrl\"" + ":"); int endindex = 0, i = 0, k; String temp; picpool = new String[ss.length]; for (int j = 0; j < ss.length - 1; j++) { temp = (String) ss[j].subSequence(Constants.defaultbeign, Constants.defaultend); if (temp.equals("null") == false) { endindex = ss[j].indexOf("\"", 1); picpool[i] = ss[j].substring(Constants.defaultbeign + 1, endindex); picpool[i] = picpool[i].replace("\\", ""); i++; Log.d("图片信息", picpool[i - 1]); } } flag = 0; for (k = 0; k < i - 1 && flag == 0; k++) { //finish为了同步插入图片和循环 finish=0; String path = picpool[k]; PictureUtil.loadImageFromNetwork(path, new PicHttpCallBackListener() { @Override public void onFinish(Drawable drawable) { if (drawable != null) { mPlayView.switchImage(drawable); flag = 1; } finish = 1; } @Override public void onError(Exception e) { Log.d("错误", e.getMessage()); finish = 1; } }); while (finish == 0) { } } if (flag == 0) { mResource = R.drawable.bg_default2; mPlayView.previous(mResource); if (MainActivity.mediaplayer.isPlaying()) mPlayView.play(); } } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View viewroot = inflater.inflate(R.layout.fragment_music_play_surface, container, false); title = (TextView) viewroot.findViewById(R.id.title); mPlayPause = (Button) viewroot.findViewById(R.id.btn_play_pause); mNext = (Button) viewroot.findViewById(R.id.btn_next); mPrevious = (Button) viewroot.findViewById(R.id.btn_previous); mPlayView = (MusicPlayView) viewroot.findViewById(R.id.layout_media_play_view); mSeekBar = (SeekBar) viewroot.findViewById(R.id.seekbar); mTextViewDuration = (TextView) viewroot.findViewById(R.id.duration_time); mTextViewCurrentTime = (TextView) viewroot.findViewById(R.id.current_time); //设置播放状态图标以及旋转动画 if (MainActivity.mediaplayer.isPlaying()) { mPlayView.play(); mPlayPause.setBackgroundResource(R.drawable.btn_ctrl_play); } else { mPlayView.pause(); mPlayPause.setBackgroundResource(R.drawable.fm_btn_pause); } /*旋转盘内设置专辑图片,若搜索错误,则使用默认图片*/ HttpUtil.SearchMusic(MyApplication.getContext(), URLEncoder.encode(MainActivity.currentMusic.getTitle()), 10, 1, 0, Constants.SEARCH_PICURL, new LyricHttpCallBackListener() { @Override public void onFinish(String response) { } @Override public void onError(Exception e) { mResource = R.drawable.bg_default1; mPlayView.previous(mResource); } }); Intent intent = getActivity().getIntent(); musiclist = (List<Music>) intent.getSerializableExtra("MusicList"); count = intent.getIntExtra("count", 0); title.setText(MainActivity.currentMusic.getTitle()); //歌曲时长 Date dateDuration = new Date(MainActivity.currentMusic.getDuration()); SimpleDateFormat formatDuration = new SimpleDateFormat("mm:ss"); mTextViewDuration.setText(formatDuration.format(dateDuration)); //设置进度条长度 mSeekBar.setMax(MainActivity.currentMusic.getDuration()); //歌曲播放时长监听广播注册 musicBroadcast = new MusicBroadcast(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.example.mediaplayer.musictime"); getActivity().registerReceiver(musicBroadcast, intentFilter); //自动更新歌曲名广播注册 musicName = new MusicName(); IntentFilter intentFilter2 = new IntentFilter(); intentFilter2.addAction("com.example.mediaplayer.changeNameOfMusicInCircle"); getActivity().registerReceiver(musicName, intentFilter2); mPlayPause.setOnClickListener(this); mNext.setOnClickListener(this); mPrevious.setOnClickListener(this); mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { Intent intent = new Intent(getActivity(), PlayerService.class); intent.putExtra("start_type", Constants.START_TYPE_SEEK_TO); intent.putExtra("progress", seekBar.getProgress()); getActivity().startService(intent); } }); return viewroot; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_play_pause: Intent intent = new Intent(getActivity(), PlayerService.class); if (MainActivity.mediaplayer.isPlaying()) { mPlayView.pause(); mPlayPause.setBackgroundResource(R.drawable.fm_btn_pause); } else { mPlayView.play(); mPlayPause.setBackgroundResource(R.drawable.btn_ctrl_play); } intent.putExtra("start_type", Constants.START_TYPE_OPERATION); intent.putExtra("operation", Constants.OPEARTION_PLAY); intent.putExtra("currentPosition", mainActivity.currentPosition); intent.putExtra("musicList", (Serializable) musiclist); getActivity().startService(intent); break; case R.id.btn_previous: mPlayPause.setBackgroundResource(R.drawable.btn_ctrl_play); Intent intent2 = new Intent(getActivity(), PlayerService.class); intent2.putExtra("start_type", Constants.START_TYPE_OPERATION); intent2.putExtra("operation", Constants.OPEARTION_PREVIOUS_MUSIC); intent2.putExtra("currentPosition", mainActivity.currentPosition); intent2.putExtra("count", count); intent2.putExtra("musicList", (Serializable) musiclist); getActivity().startService(intent2); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { title.setText(MainActivity.currentMusic.getTitle()); HttpUtil.SearchMusic(MyApplication.getContext(), URLEncoder. encode(MainActivity.currentMusic.getTitle()), 10, 1, 0, Constants.SEARCH_PICURL, new LyricHttpCallBackListener() { @Override public void onFinish(String response) { HttpUtil.Cloud_Muisc_getLrcAPI(getActivity(), "pc", LyricFragment.lyricId); } @Override public void onError(Exception e) { mResource = R.drawable.bg_default1; mPlayView.previous(mResource); } }); } }, 200); break; case R.id.btn_next: mPlayPause.setBackgroundResource(R.drawable.btn_ctrl_play); Intent intent3 = new Intent(getActivity(), PlayerService.class); intent3.putExtra("start_type", Constants.START_TYPE_OPERATION); intent3.putExtra("operation", Constants.OPEARTION_NEXT_MUSIC); intent3.putExtra("currentPosition", mainActivity.currentPosition); intent3.putExtra("musicList", (Serializable) musiclist); intent3.putExtra("count", count); getActivity().startService(intent3); Handler handler2 = new Handler(); handler2.postDelayed(new Runnable() { @Override public void run() { title.setText(MainActivity.currentMusic.getTitle()); HttpUtil.SearchMusic(MyApplication.getContext(), URLEncoder. encode(MainActivity.currentMusic.getTitle()), 10, 1, 0, Constants.SEARCH_PICURL, new LyricHttpCallBackListener() { @Override public void onFinish(String response) { HttpUtil.Cloud_Muisc_getLrcAPI(getActivity(), "pc", LyricFragment.lyricId); } @Override public void onError(Exception e) { mResource = R.drawable.bg_default1; mPlayView.previous(mResource); } }); } }, 200); break; default: break; } } @Override public void onDestroy() { Log.d("销毁情况", "已被销毁"); getActivity().unregisterReceiver(musicName); super.onDestroy(); } //歌曲当前播放进度及歌曲总时长监听广播 public class MusicBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra("type", 0); switch (type) { case PlayerService.DURATION_TYPE: int time = intent.getIntExtra("Mtime", 50); Date dateDuration = new Date(time); SimpleDateFormat formatDuration = new SimpleDateFormat("mm:ss"); mSeekBar.setMax(time); mTextViewDuration.setText(formatDuration.format(dateDuration)); break; case PlayerService.CURRENT_TIME_TYPE: int currenttime = intent.getIntExtra("time", 50); Date dateCurrentTime = new Date(currenttime); SimpleDateFormat formatCurrent = new SimpleDateFormat("mm:ss"); mSeekBar.setProgress(currenttime); mTextViewCurrentTime.setText(formatCurrent.format(dateCurrentTime)); break; default: break; } } } //歌曲播放完毕后自动更换标题 public class MusicName extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MainActivity.currentMusic = musiclist.get(MainActivity.currentPosition); title.setText(MainActivity.currentMusic.getTitle()); } } }
6f02e866b2ef570fc9d4f04ff1fdbe0342424fff
212298a1a39f63546f35fd3ac70f63c030345de9
/src/main/java/com/snug/util/SnugUtil.java
d361dbfb7e701b7afd139901ff7a153d155f23c8
[]
no_license
AbnerHuang2/snug
88e53455881cac7a24bf0c4176c7c65b60ef4ea7
aa6a1efc06ea0e7f8f6311d963d80a5253614227
refs/heads/master
2022-07-01T14:08:52.440442
2019-12-04T08:46:59
2019-12-04T08:46:59
225,794,732
1
0
null
2022-06-17T02:44:39
2019-12-04T06:22:43
Java
UTF-8
Java
false
false
2,031
java
package com.snug.util; import com.sun.javadoc.Type; import java.util.ArrayList; import java.util.List; public class SnugUtil { /** * 包括基本类型的数组和实体数组 * @param type * @return */ public static boolean isArray(Type type){ return !type.dimension().equals(""); } public static boolean isCollection(Type type){ return type.qualifiedTypeName().endsWith("List") || type.qualifiedTypeName().endsWith("Set"); } public static boolean isMap(Type type){ return type.qualifiedTypeName().endsWith("Map"); } /** * 判断类型是否为库类型。默认基本类型,java包,javax包,spring包为库类型。 * * @param ptype * @return */ public static boolean isBasic(Type ptype) { String qualifiedTypeName; return ptype.isPrimitive() || (qualifiedTypeName = ptype.qualifiedTypeName()).startsWith("java.") || qualifiedTypeName.startsWith("javax.") || qualifiedTypeName.startsWith("org.springframework."); } public static boolean isEntity(Type type){ return !isBasic(type); } /** * 字符串拼接 * @param list * @param split * @return */ public static String join(List<String> list,String split){ if(list==null || list.size()<1){ return null; } StringBuilder sb = new StringBuilder(); for(int i=0;i<list.size();i++){ if(i==list.size()-1){ sb.append(list.get(i)); }else{ sb.append(list.get(i)+split); } } return sb.toString(); } /** * 如果一个对象为null,把它替换为"" * @param obj * @return */ public String replaceNull(Object obj){ return obj == null ? "" : obj.toString(); } public static void main(String[] args) { System.out.println(System.getProperty("java.class.path")); } }
cfb996967a7d1a5b0df6d574951c3d7eb04a6658
6846636a68ee346e381fe0ca30065999f66b0d1f
/src/main/java/org/xlet/upgrader/web/controller/ChangeLogController.java
7c7d5c70435cbea93342e4dc35babe5bc0bee2aa
[]
no_license
hackerlank/upgrader
f6d16ef0106d97d155398882387cb27fb037d175
fdb2b68ac5159507f877f0dee256b512eee78eed
refs/heads/master
2021-01-13T14:47:42.236014
2014-12-10T09:16:48
2014-12-10T09:16:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,666
java
package org.xlet.upgrader.web.controller; import org.xlet.upgrader.service.ChangeLogService; import org.xlet.upgrader.vo.PaginationRequest; import org.xlet.upgrader.vo.dashboard.ChangeLogDTO; import org.xlet.upgrader.vo.dashboard.form.ChangeLogForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.util.List; /** * Creator: JimmyLin * DateTime: 14-9-16 上午10:40 * Summary: */ @RestController @RequestMapping("/api/v1/changelog") public class ChangeLogController { @Autowired private ChangeLogService logService; @RequestMapping(method = RequestMethod.GET) public List<ChangeLogDTO> getByVersion(@RequestParam(value = "versionId", required = false) Long versionId, UriComponentsBuilder builder) { return logService.getByVersion(builder.build().toUriString(), versionId); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> createChangeLog(ChangeLogForm changelog, UriComponentsBuilder builder) { ChangeLogDTO dto = logService.save(changelog); Long id = dto.getId(); URI uri = builder.path("/api/v1/changelog/" + id).build().toUri(); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uri); return new ResponseEntity(headers, HttpStatus.CREATED); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) public void updateChangeLog(ChangeLogForm changelog, @PathVariable("id") Long id) { logService.update(changelog, id); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteChangeLog(@PathVariable("id") Long id) { logService.delete(id); } @RequestMapping(value = "/list", method = RequestMethod.GET) public Page<ChangeLogDTO> listChangeLog(PaginationRequest request, UriComponentsBuilder builder) { return logService.list(builder.build().toUriString(), new PageRequest(request.getPage(), request.getSize())); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ChangeLogDTO getChangeLog(@PathVariable("id") Long id, UriComponentsBuilder builder) { return logService.getChangeLog(builder.build().toUriString(), id); } }
b785cf95e421e40a9dbbe14b80a131975aa49a2d
7f23eee736dd5eec6f7d130d2427ba359437c7eb
/src/Model/SqlLiteImplementor.java
5e54a4232e36b1b090e288c67b99646bf1cb39d8
[]
no_license
gokkush/Exam-Creator-java
483d6d394ab2682aaf8a6d06e618ff6a6c39f82e
d03dc324a1728151b85bc823e708a0cfd165e2a9
refs/heads/master
2020-08-01T19:37:02.586329
2019-09-27T05:38:49
2019-09-27T05:38:49
211,093,907
0
0
null
null
null
null
UTF-8
Java
false
false
1,265
java
package Model; /* * 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. */ import java.sql.Connection; import java.sql.DriverManager; import javax.swing.JOptionPane; /** * * @author User */ public class SqlLiteImplementor extends DbImplementor { private static Connection baglan=null; private static String yol = "jdbc:sqlite";//veritabanının adresi ve portu private static String dbAdi = ":db/SoruHazirlama.db"; //veritabanının dosya yolu private static String surucu = "org.sqlite.JDBC"; @Override public void Execute(String Sql) { System.out.println("SqlLİte Çalıştı" + Sql); } public void dene(){ } public Connection OpenCon(String SqlCon) { try { Class.forName(surucu).newInstance(); baglan=DriverManager.getConnection(yol+dbAdi); // JOptionPane.showMessageDialog(null, "Başarıyla Bağlandı"); System.out.println("SqlLİte Çalıştı" + SqlCon); return baglan; } catch (Exception e) { JOptionPane.showMessageDialog(null, e); return null; } } }
[ "gokkush.hotmail.com" ]
gokkush.hotmail.com
9e88b03c48aa614f600ee7c0f7b8691557947866
b20267c04f9c38ae0fab08a57a2b60391082323f
/ta4j/src/main/java/org/investphere/ta4j/indicators/trackers/HMAIndicator.java
29a0cdcab3a81acfa8f674de5932bac5efc1c9ff
[ "MIT" ]
permissive
sumit140588/ta4j
64b9258f7f60a076cab50ace0c118c272fbf73c3
15afc298b49cc907cab485458413f7f8050c582a
refs/heads/master
2021-12-08T02:53:52.962702
2015-11-28T14:23:37
2015-11-28T14:23:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,142
java
/** * The MIT License (MIT) * * Copyright (c) 2014-2015 Marc de Verdelhan & respective authors (see AUTHORS) * * 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.investphere.ta4j.indicators.trackers; import eu.verdelhan.ta4j.Decimal; import eu.verdelhan.ta4j.Indicator; import eu.verdelhan.ta4j.indicators.CachedIndicator; /** * HMA indicator. (Hull) * <p> */ public class HMAIndicator extends CachedIndicator<Decimal> { private int timeFrame; private Indicator<Decimal> indicator; public HMAIndicator(Indicator<Decimal> indicator, int timeFrame) { super(indicator); this.indicator = indicator; this.timeFrame = timeFrame; } @Override protected Decimal calculate(int index) { if (index == 0) { return indicator.getValue(0); } return calculateWMA(Decimal.valueOf(2).multipliedBy(calculateWMA(index/2)).minus(calculateWMA(index)), Math.sqrt(index)); } protected Decimal calculateWMA(Decimal value, double index) { return calculateWMA(value, (int)index); } protected Decimal calculateWMA(int index) { if (index == 0) { return indicator.getValue(0); } Decimal value = Decimal.ZERO; return calculateWMA(value, index); } protected Decimal calculateWMA(Decimal value, int index) { if(index - timeFrame < 0) { for(int i = index + 1; i > 0; i--) { value = value.plus(Decimal.valueOf(i).multipliedBy(indicator.getValue(i-1))); } return value.dividedBy(Decimal.valueOf(((index + 1) * (index + 2)) / 2)); } int actualIndex = index; for(int i = timeFrame; i > 0; i--) { value = value.plus(Decimal.valueOf(i).multipliedBy(indicator.getValue(actualIndex))); actualIndex--; } return value.dividedBy(Decimal.valueOf((timeFrame * (timeFrame + 1)) / 2)); } @Override public String toString() { return String.format(getClass().getSimpleName() + " timeFrame: %s", timeFrame); } }
515b30f2a6498aee1a33d559297107503e0e9967
834fcf48d224b07d06d272244a5f7526b9930735
/Android/app/src/main/java/be/tomberndjesse/picaloc/BaseActivity.java
7632939a44b3ab40f6c49481feb54fe45d453e09
[]
no_license
jhoobergs/Picaloc
c56d2aa2802e0ef70e8f63937799c1abb9e6b10d
35e99a295abb48593d6998dafeb1f8b622bc1b84
refs/heads/master
2021-01-12T13:40:31.992476
2016-09-18T14:40:01
2016-09-18T14:40:01
68,431,372
0
0
null
null
null
null
UTF-8
Java
false
false
6,131
java
package be.tomberndjesse.picaloc; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.ProgressBar; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import java.text.DateFormat; import java.util.Date; import be.tomberndjesse.picaloc.utils.SettingsUtil; import be.tomberndjesse.picaloc.utils.SharedPreferencesKeys; /** * Created by jesse on 17/09/2016. */ public class BaseActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private boolean mRequestingLocationUpdates = true; private Location mCurrentLocation; private String mLastUpdateTime; private GoogleApiClient mGoogleApiClient; LocationRequest mLocationRequest; SensorDataInterface sensorDataInterface; private FrameLayout frameLayout; private ProgressBar progressBar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getToken() instead. String uid = user.getUid(); user.getToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { new SettingsUtil(getApplicationContext()).setString(SharedPreferencesKeys.TokenString, task.getResult().getToken()); } }); } else { startActivity(new Intent(this, SignInActivity.class)); finish(); } super.setContentView(R.layout.activity_base); frameLayout = (FrameLayout) findViewById(R.id.frame); progressBar = (ProgressBar) findViewById(R.id.progressBar); } @Override public void setContentView(@LayoutRes int layoutResID) { getLayoutInflater().inflate(layoutResID, frameLayout); } public void enableLocationUpdates(int interval, int fastestInterval) { createLocationRequest(interval, fastestInterval); buildGoogleApiClient(); if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) { startLocationUpdates(); } } public Location getLocation() { return mCurrentLocation; } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } protected void createLocationRequest(int interval, int fastestInterval) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(interval); mLocationRequest.setFastestInterval(fastestInterval); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } @Override public void onConnected(@Nullable Bundle bundle) { if (mRequestingLocationUpdates) { startLocationUpdates(); } } @Override public void onConnectionSuspended(int i) { } protected void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //TODO: return; } LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } public void setSensorDataInterface(SensorDataInterface listener){ sensorDataInterface = listener; } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); if(sensorDataInterface != null) sensorDataInterface.locationChanged(location); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } protected void stopLocationUpdates() { if(mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this); } } @Override protected void onDestroy() { super.onDestroy(); stopLocationUpdates(); } public void showProgressBar(){ progressBar.setVisibility(View.VISIBLE); } public void hideProgressBar(){ progressBar.setVisibility(View.GONE); } }
673388fb3d892020d927e90ee0d7b332d003a542
0c359e241cce729ce777db41d3a4feefa48c30c0
/src/main/java/com/controllerface/cmdr_j/classes/modules/optional/shields/shieldcells/size6/ShieldCellBank_6D.java
14033aa4124f4cfc495d6227a860a6507c3420aa
[]
no_license
controllerface/CMDR-J
760cafe4b89fc86715ee7941d66eaaf7978cf067
9fc70e1ae2f2119e3dc93bbc9a26544526beb56a
refs/heads/main
2022-09-29T02:43:58.308231
2022-09-12T02:09:01
2022-09-12T02:09:01
128,938,494
1
1
null
2021-11-21T01:42:20
2018-04-10T13:37:30
Java
UTF-8
Java
false
false
1,542
java
package com.controllerface.cmdr_j.classes.modules.optional.shields.shieldcells.size6; import com.controllerface.cmdr_j.classes.data.ItemEffects; import com.controllerface.cmdr_j.classes.data.ItemEffectData; import com.controllerface.cmdr_j.classes.modules.optional.shields.shieldcells.AbstractShieldCellBank; import com.controllerface.cmdr_j.enums.equipment.modules.stats.ItemEffect; public class ShieldCellBank_6D extends AbstractShieldCellBank { public ShieldCellBank_6D() { super("6D Shield Cell Bank", new ItemEffects( new ItemEffectData(ItemEffect.Size, 6.0), new ItemEffectData(ItemEffect.Class, "D"), new ItemEffectData(ItemEffect.Mass, 16.0), new ItemEffectData(ItemEffect.Integrity, 68.0), new ItemEffectData(ItemEffect.PowerDraw, 1.42), new ItemEffectData(ItemEffect.BootTime, 25.0), new ItemEffectData(ItemEffect.ShieldBankSpinUp, 5.0), new ItemEffectData(ItemEffect.ShieldBankReinforcement, 26.0), new ItemEffectData(ItemEffect.ShieldBankHeat, 640.0), new ItemEffectData(ItemEffect.AmmoClipSize, 1.0), new ItemEffectData(ItemEffect.AmmoMaximum, 3.0), new ItemEffectData(ItemEffect.ShieldBankDuration, 7.6) )); } @Override public long price() { return 222_444; } }
d5dd94382eb6e0273783d755ef66fcd3725620a7
28552d7aeffe70c38960738da05ebea4a0ddff0c
/google-ads/src/main/java/com/google/ads/googleads/v6/resources/Video.java
361eb5f82a7b8b8f3175a102da77beca2129d94a
[ "Apache-2.0" ]
permissive
PierrickVoulet/google-ads-java
6f84a3c542133b892832be8e3520fb26bfdde364
f0a9017f184cad6a979c3048397a944849228277
refs/heads/master
2021-08-22T08:13:52.146440
2020-12-09T17:10:48
2020-12-09T17:10:48
250,642,529
0
0
Apache-2.0
2020-03-27T20:41:26
2020-03-27T20:41:25
null
UTF-8
Java
false
true
41,363
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v6/resources/video.proto package com.google.ads.googleads.v6.resources; /** * <pre> * A video. * </pre> * * Protobuf type {@code google.ads.googleads.v6.resources.Video} */ public final class Video extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v6.resources.Video) VideoOrBuilder { private static final long serialVersionUID = 0L; // Use Video.newBuilder() to construct. private Video(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Video() { resourceName_ = ""; id_ = ""; channelId_ = ""; title_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Video(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Video( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); resourceName_ = s; break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; id_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; channelId_ = s; break; } case 64: { bitField0_ |= 0x00000004; durationMillis_ = input.readInt64(); break; } case 74: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; title_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v6.resources.VideoProto.internal_static_google_ads_googleads_v6_resources_Video_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v6.resources.VideoProto.internal_static_google_ads_googleads_v6_resources_Video_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v6.resources.Video.class, com.google.ads.googleads.v6.resources.Video.Builder.class); } private int bitField0_; public static final int RESOURCE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object resourceName_; /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } } /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ID_FIELD_NUMBER = 6; private volatile java.lang.Object id_; /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the id field is set. */ @java.lang.Override public boolean hasId() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CHANNEL_ID_FIELD_NUMBER = 7; private volatile java.lang.Object channelId_; /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the channelId field is set. */ @java.lang.Override public boolean hasChannelId() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channelId. */ @java.lang.Override public java.lang.String getChannelId() { java.lang.Object ref = channelId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); channelId_ = s; return s; } } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for channelId. */ @java.lang.Override public com.google.protobuf.ByteString getChannelIdBytes() { java.lang.Object ref = channelId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); channelId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DURATION_MILLIS_FIELD_NUMBER = 8; private long durationMillis_; /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the durationMillis field is set. */ @java.lang.Override public boolean hasDurationMillis() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The durationMillis. */ @java.lang.Override public long getDurationMillis() { return durationMillis_; } public static final int TITLE_FIELD_NUMBER = 9; private volatile java.lang.Object title_; /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the title field is set. */ @java.lang.Override public boolean hasTitle() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The title. */ @java.lang.Override public java.lang.String getTitle() { java.lang.Object ref = title_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); title_ = s; return s; } } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for title. */ @java.lang.Override public com.google.protobuf.ByteString getTitleBytes() { java.lang.Object ref = title_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); title_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getResourceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, id_); } if (((bitField0_ & 0x00000002) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, channelId_); } if (((bitField0_ & 0x00000004) != 0)) { output.writeInt64(8, durationMillis_); } if (((bitField0_ & 0x00000008) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 9, title_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getResourceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, id_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, channelId_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(8, durationMillis_); } if (((bitField0_ & 0x00000008) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, title_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v6.resources.Video)) { return super.equals(obj); } com.google.ads.googleads.v6.resources.Video other = (com.google.ads.googleads.v6.resources.Video) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (hasId() != other.hasId()) return false; if (hasId()) { if (!getId() .equals(other.getId())) return false; } if (hasChannelId() != other.hasChannelId()) return false; if (hasChannelId()) { if (!getChannelId() .equals(other.getChannelId())) return false; } if (hasDurationMillis() != other.hasDurationMillis()) return false; if (hasDurationMillis()) { if (getDurationMillis() != other.getDurationMillis()) return false; } if (hasTitle() != other.hasTitle()) return false; if (hasTitle()) { if (!getTitle() .equals(other.getTitle())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + RESOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); if (hasId()) { hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); } if (hasChannelId()) { hash = (37 * hash) + CHANNEL_ID_FIELD_NUMBER; hash = (53 * hash) + getChannelId().hashCode(); } if (hasDurationMillis()) { hash = (37 * hash) + DURATION_MILLIS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getDurationMillis()); } if (hasTitle()) { hash = (37 * hash) + TITLE_FIELD_NUMBER; hash = (53 * hash) + getTitle().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v6.resources.Video parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v6.resources.Video parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v6.resources.Video parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v6.resources.Video parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v6.resources.Video parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v6.resources.Video parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v6.resources.Video parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v6.resources.Video parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v6.resources.Video parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v6.resources.Video parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v6.resources.Video parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v6.resources.Video parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v6.resources.Video prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * A video. * </pre> * * Protobuf type {@code google.ads.googleads.v6.resources.Video} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v6.resources.Video) com.google.ads.googleads.v6.resources.VideoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v6.resources.VideoProto.internal_static_google_ads_googleads_v6_resources_Video_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v6.resources.VideoProto.internal_static_google_ads_googleads_v6_resources_Video_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v6.resources.Video.class, com.google.ads.googleads.v6.resources.Video.Builder.class); } // Construct using com.google.ads.googleads.v6.resources.Video.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); resourceName_ = ""; id_ = ""; bitField0_ = (bitField0_ & ~0x00000001); channelId_ = ""; bitField0_ = (bitField0_ & ~0x00000002); durationMillis_ = 0L; bitField0_ = (bitField0_ & ~0x00000004); title_ = ""; bitField0_ = (bitField0_ & ~0x00000008); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v6.resources.VideoProto.internal_static_google_ads_googleads_v6_resources_Video_descriptor; } @java.lang.Override public com.google.ads.googleads.v6.resources.Video getDefaultInstanceForType() { return com.google.ads.googleads.v6.resources.Video.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v6.resources.Video build() { com.google.ads.googleads.v6.resources.Video result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v6.resources.Video buildPartial() { com.google.ads.googleads.v6.resources.Video result = new com.google.ads.googleads.v6.resources.Video(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.resourceName_ = resourceName_; if (((from_bitField0_ & 0x00000001) != 0)) { to_bitField0_ |= 0x00000001; } result.id_ = id_; if (((from_bitField0_ & 0x00000002) != 0)) { to_bitField0_ |= 0x00000002; } result.channelId_ = channelId_; if (((from_bitField0_ & 0x00000004) != 0)) { result.durationMillis_ = durationMillis_; to_bitField0_ |= 0x00000004; } if (((from_bitField0_ & 0x00000008) != 0)) { to_bitField0_ |= 0x00000008; } result.title_ = title_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v6.resources.Video) { return mergeFrom((com.google.ads.googleads.v6.resources.Video)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v6.resources.Video other) { if (other == com.google.ads.googleads.v6.resources.Video.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; onChanged(); } if (other.hasId()) { bitField0_ |= 0x00000001; id_ = other.id_; onChanged(); } if (other.hasChannelId()) { bitField0_ |= 0x00000002; channelId_ = other.channelId_; onChanged(); } if (other.hasDurationMillis()) { setDurationMillis(other.getDurationMillis()); } if (other.hasTitle()) { bitField0_ |= 0x00000008; title_ = other.title_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v6.resources.Video parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v6.resources.Video) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object resourceName_ = ""; /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; onChanged(); return this; } /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); onChanged(); return this; } /** * <pre> * Output only. The resource name of the video. * Video resource names have the form: * `customers/{customer_id}/videos/{video_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; onChanged(); return this; } private java.lang.Object id_ = ""; /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the id field is set. */ public boolean hasId() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The id to set. * @return This builder for chaining. */ public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearId() { bitField0_ = (bitField0_ & ~0x00000001); id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * <pre> * Output only. The ID of the video. * </pre> * * <code>string id = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } private java.lang.Object channelId_ = ""; /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the channelId field is set. */ public boolean hasChannelId() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The channelId. */ public java.lang.String getChannelId() { java.lang.Object ref = channelId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); channelId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for channelId. */ public com.google.protobuf.ByteString getChannelIdBytes() { java.lang.Object ref = channelId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); channelId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The channelId to set. * @return This builder for chaining. */ public Builder setChannelId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; channelId_ = value; onChanged(); return this; } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearChannelId() { bitField0_ = (bitField0_ & ~0x00000002); channelId_ = getDefaultInstance().getChannelId(); onChanged(); return this; } /** * <pre> * Output only. The owner channel id of the video. * </pre> * * <code>string channel_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The bytes for channelId to set. * @return This builder for chaining. */ public Builder setChannelIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000002; channelId_ = value; onChanged(); return this; } private long durationMillis_ ; /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the durationMillis field is set. */ @java.lang.Override public boolean hasDurationMillis() { return ((bitField0_ & 0x00000004) != 0); } /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The durationMillis. */ @java.lang.Override public long getDurationMillis() { return durationMillis_; } /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The durationMillis to set. * @return This builder for chaining. */ public Builder setDurationMillis(long value) { bitField0_ |= 0x00000004; durationMillis_ = value; onChanged(); return this; } /** * <pre> * Output only. The duration of the video in milliseconds. * </pre> * * <code>int64 duration_millis = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearDurationMillis() { bitField0_ = (bitField0_ & ~0x00000004); durationMillis_ = 0L; onChanged(); return this; } private java.lang.Object title_ = ""; /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return Whether the title field is set. */ public boolean hasTitle() { return ((bitField0_ & 0x00000008) != 0); } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The title. */ public java.lang.String getTitle() { java.lang.Object ref = title_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); title_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for title. */ public com.google.protobuf.ByteString getTitleBytes() { java.lang.Object ref = title_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); title_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The title to set. * @return This builder for chaining. */ public Builder setTitle( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; title_ = value; onChanged(); return this; } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearTitle() { bitField0_ = (bitField0_ & ~0x00000008); title_ = getDefaultInstance().getTitle(); onChanged(); return this; } /** * <pre> * Output only. The title of the video. * </pre> * * <code>string title = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The bytes for title to set. * @return This builder for chaining. */ public Builder setTitleBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000008; title_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v6.resources.Video) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v6.resources.Video) private static final com.google.ads.googleads.v6.resources.Video DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v6.resources.Video(); } public static com.google.ads.googleads.v6.resources.Video getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Video> PARSER = new com.google.protobuf.AbstractParser<Video>() { @java.lang.Override public Video parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Video(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Video> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Video> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v6.resources.Video getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
00f5033fce2b3927e20a8c905af085f444dcb978
417aad87d96ef5557d974526ac44babe480f86dd
/Metodología de la programación/test/org/mp/sesion03/ResidenciaTestA.java
41efc2e5484e3ba922ca9caff43a5fd68dc43d4d
[]
no_license
dsubires/UAL
a4b2d06535c7f0ed70745b9678ab22f4136b72d3
01ea833989421016424dc70a2956d104c77e6679
refs/heads/master
2021-08-15T01:41:28.464825
2017-11-17T05:02:19
2017-11-17T05:02:19
103,769,604
0
0
null
null
null
null
ISO-8859-1
Java
false
false
6,155
java
package org.mp.sesion03; import static org.junit.Assert.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.Before; import org.junit.Test; public class ResidenciaTestA { Residencia residencia; Habitacion habitacion1; Habitacion habitacion2; Habitacion habitacion3; Habitacion habitacion4; Habitacion habitacion5; Habitacion habitacion6; Habitacion habitacion7; Habitacion habitacion8; Habitacion habitacion9; Residente residente1; Residente residente2; Residente residente3; Residente residente4; SimpleDateFormat dateFormat; @Before public void setUp() throws Exception { habitacion1 = new Habitacion("101"); habitacion2 = new Habitacion("102"); habitacion3 = new Habitacion("103"); habitacion4 = new Habitacion("201"); habitacion5 = new Habitacion("202"); habitacion6 = new Habitacion("203"); habitacion7 = new Habitacion("301"); habitacion8 = new Habitacion("302"); habitacion9 = new Habitacion("303"); dateFormat = new SimpleDateFormat ("dd-MM-yyyy"); residente1 = new Residente("Martinez Gomez, Adrian","27272727",'V', dateFormat.parse("12-02-1940")); residente2 = new Residente("Lopez Lopez, Luisa","27272728",'M', dateFormat.parse("12-03-1940")); residente3 = new Residente("Roquero Sanchez, Luis","27272729",'V', dateFormat.parse("12-04-1940")); residente4 = new Residente("Del Aguila Imperial, Ana Maria","27272730",'M', dateFormat.parse("12-02-1950")); Habitacion[] habitaciones = {habitacion1,habitacion2,habitacion3,habitacion4, habitacion5}; residencia = new Residencia("La Mar Salá",habitaciones); } @Test public void testSetsGets() throws ParseException { // Probar que estan los sets gets de Residente assertTrue(residente1.getNombre().equals("Martinez Gomez, Adrian")); assertTrue(residente1.getDni().equals("27272727")); assertTrue(residente1.getSexo() == 'V'); Date date = dateFormat.parse("12-02-1940"); assertTrue(residente1.getFechaNacimiento().equals(date)); residente1.setNombre("Martinez Cano, Adrian"); residente1.setDni("26272727"); residente1.setSexo('M'); residente1.setFechaNacimiento(dateFormat.parse("13-02-1980")); assertTrue(residente1.getNombre().equals("Martinez Cano, Adrian")); assertTrue(residente1.getDni().equals("26272727")); assertTrue(residente1.getSexo() == 'M'); assertTrue(residente1.getFechaNacimiento().equals(dateFormat.parse("13-02-1980"))); // Probar que estan los sets gets de Habitación assertTrue(habitacion1.getNumero().equals("101")); habitacion1.setNumero("110"); assertTrue(habitacion1.getNumero().equals("110")); } @Test public void testInsertarHabitacion() { Habitacion habitacion = new Habitacion("501"); assertTrue(residencia.getNHabitaciones() == 5); residencia.insertarHabitacion(habitacion); assertTrue(residencia.getNHabitaciones() == 6); for (int i = 0; i < 100; i++) { Habitacion habitacionA = new Habitacion("80"+i); residencia.insertarHabitacion(habitacionA); } assertTrue(residencia.getNHabitaciones() == 106); } @Test public void testBuscarHabitacionPorNumero() { assertTrue(residencia.getNHabitaciones() == 5); Habitacion habitacion = residencia.buscarHabitacion("101"); assertTrue(habitacion.equals(habitacion1)); assertFalse(habitacion.equals(habitacion2)); Habitacion habitacionA = residencia.buscarHabitacion("701"); assertTrue(habitacionA == null); assertTrue(residencia.getNHabitaciones() == 5); } @Test public void testEliminarHabitacion() { assertTrue(residencia.getNHabitaciones() == 5); residencia.eliminarHabitacion(habitacion1); assertTrue(residencia.getNHabitaciones() == 4); } @Test public void testEdadResidente() throws ParseException { Date date = dateFormat.parse("12-03-2007"); assertTrue(residente1.getEdad(date)==67); assertTrue(residente2.getEdad(date)==67); assertTrue(residente3.getEdad(date)==66); assertTrue(residente4.getEdad(date)==57); } @Test public void testIngresoSalida() throws ParseException { residencia.ingreso(residente1, habitacion1, dateFormat.parse("12-01-2007"), dateFormat.parse("12-06-2007")); residencia.ingreso(residente2, habitacion2, dateFormat.parse("12-02-2007"), dateFormat.parse("12-06-2007")); assertTrue(residencia.getNReservas() == 2); assertTrue(residencia.getNResidentes() == 2); residencia.ingreso(residente3, habitacion3, dateFormat.parse("12-02-2007"), dateFormat.parse("12-03-2007")); assertTrue(residencia.getNReservas() == 3); assertTrue(residencia.getNResidentes() == 3); residencia.salida(residente1, dateFormat.parse("12-05-2007")); assertTrue(residencia.getNReservas() == 3); assertTrue(residencia.getNResidentes() == 2); } @Test public void testIngresoCienResidentes() throws ParseException { assertTrue(residencia.getNReservas() == 0); for (int i = 0; i < 100; i++) { Residente residente = new Residente("nombre"+i,"272727"+i,'V',dateFormat.parse("12-02-1950") ); Habitacion habitacion = new Habitacion("100"+i); residencia.ingreso(residente,habitacion,dateFormat.parse("12-02-2007"),dateFormat.parse("12-02-2008")); } assertTrue(residencia.getNReservas() == 100); } @Test public void testCambioHabitacion() throws ParseException { residencia.ingreso(residente1, habitacion1, dateFormat.parse("12-01-2007"), dateFormat.parse("12-03-2007")); residencia.ingreso(residente2, habitacion2, dateFormat.parse("12-02-2007"), dateFormat.parse("12-03-2007")); assertTrue(residencia.getNReservas() == 2); assertTrue(residencia.getNResidentes() == 2); residencia.ingreso(residente3, habitacion3, dateFormat.parse("12-02-2007"), dateFormat.parse("12-03-2007")); assertTrue(residencia.getNReservas() == 3); assertTrue(residencia.getNResidentes() == 3); residencia.cambiarHabitacion(residente1, habitacion4, dateFormat.parse("12-02-2007"), dateFormat.parse("12-03-2007")); assertTrue(residencia.getNReservas() == 4); assertTrue(residencia.getNResidentes() == 3); } }
15c170481cb5c7f245cbe0e8af2682b245494e14
dc54461554ccb453c3b5237f612ecfc4586bc5db
/app/src/main/java/com/kagwisoftwares/nhms/Facility/DeptStaff.java
acd1da99ba2d501d2d9e63f7495ad30ea35a45ce
[]
no_license
kagwicharles/NHMs
7c6cfcad72d9da5ab7542252c2c837a3d33891a7
723b3bf6af18157d725d25e5879f90cde1695ffc
refs/heads/master
2023-04-24T12:10:51.133596
2021-04-22T07:06:26
2021-04-22T07:06:26
344,372,821
0
0
null
null
null
null
UTF-8
Java
false
false
743
java
package com.kagwisoftwares.nhms.Facility; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.Image; import android.widget.ImageView; public class DeptStaff { public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public int getDeptIcon() { return deptIcon; } public void setDeptIcon(int deptIcon) { this.deptIcon = deptIcon; } private String deptName; private int deptIcon; public DeptStaff(String deptName,int deptIcon) { this.deptName = deptName; this.deptIcon = deptIcon; } }
b11018b65c4c91ace5f65dac7868e1355f6372ac
9dea7c8b3b8d01cbf220873f9fa4b94f8aaf41dd
/base/src/main/java/com/codvision/base/rxjava/RxSchedulers.java
ec7abc7da54da96e686c1f297c97642da512566d
[]
no_license
HongDongwei/Modulestext
e559a9f3af2eea881de22276732b7658ca83ebe9
36fe8761e65c7f47901133afacd66da328b5ef2b
refs/heads/master
2023-01-31T17:06:22.239897
2020-12-17T02:53:27
2020-12-17T02:53:27
322,162,165
0
0
null
null
null
null
UTF-8
Java
false
false
839
java
package com.codvision.base.rxjava; import io.reactivex.FlowableTransformer; import io.reactivex.ObservableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * Project: Modules * Des:封装线程调度 * * @author xujichang * created by 2018/7/26 - 5:01 PM */ public class RxSchedulers { public static <T> ObservableTransformer<T, T> observableTransformer_io_main() { return upstream -> upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } public static <T> FlowableTransformer<T, T> flowableTransformer_io_main() { return upstream -> upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }
2dbe3835e55209e83db2ad82de4f07b0c999eb4a
e1938b85ba2f6f15bd925e916727f48d9db5490d
/src/main/java/com/qunjie/ocean/servcie/TokenCache.java
a7c3cf952413b731136157174ae3e51027a41b59
[]
no_license
weizhuxiao/integration
5a6daea250f4becf7f6286d1818e2fab754289cd
56765a97bbeb804004cfbb5841386c6f0185ea37
refs/heads/main
2023-08-19T04:26:48.267906
2021-05-19T08:35:20
2021-05-19T08:35:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,067
java
package com.qunjie.ocean.servcie; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Maps; import com.qunjie.common.email.DefaultEmailAddress; import com.qunjie.common.email.event.SendEmailEvent; import com.qunjie.ocean.model.TokenModel; import com.qunjie.ocean.utils.HttpHelper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * Copyright (C),2020-2021,群杰印章物联网 * FileName: com.qunjie.ocean.servcie.TokenCache * * @author whs * Date: 2021/3/1 10:51 * Description: * History: * &lt;author&gt; &lt;time&gt; &lt;version&gt; &lt;desc&gt; * 修改人姓名 修改时间 版本号 描述 */ @Slf4j @Component public class TokenCache { @Autowired HttpHelper httpHelper; @Autowired ApplicationContext applicationContext; private static Map<String, TokenModel> accessTokenMap = Maps.newConcurrentMap(); public static final String APP_ID = "1692668295491611"; public static final String SECRET = "915a689fe0b4c496f061ff1c83264ac1ec80b1f6"; public static final String ADVERTISER_ID = "1690201024478285"; public static final String key = APP_ID + SECRET; public synchronized void setToken(TokenModel token){ accessTokenMap.put(key,token); } public synchronized TokenModel getToken(){ TokenModel tokenModel = accessTokenMap.computeIfAbsent(key,k->new TokenModel()); return tokenModel; } public void refreshToken(){ TokenModel tokenModel = accessTokenMap.computeIfAbsent(key,k->new TokenModel()); if (tokenModel != null){ String refresh_token = tokenModel.getRefresh_token(); TokenModel newTokenModel = refreshAccessToken(refresh_token); setToken(newTokenModel); }else { } } public TokenModel getAccessToken(String code) { // 请求地址 String open_api_url_prefix = "https://ad.oceanengine.com/open_api/"; String uri = "oauth2/access_token/"; // 请求参数 Map<String, String> data = new HashMap() { { put("app_id", TokenCache.APP_ID); put("secret", TokenCache.SECRET); put("grant_type", "auth_code"); put("auth_code", code); } }; JSONObject jsonObject = httpHelper.doPost(open_api_url_prefix + uri, data); if (jsonObject != null){ JSONObject data1 = jsonObject.getJSONObject("data"); TokenModel tokenModel = new TokenModel(data1.getString("access_token"),data1.getLong("expires_in"), data1.getString("refresh_token"),data1.getLong("refresh_token_expires_in")); setToken(tokenModel); return tokenModel; } return null; } public TokenModel refreshAccessToken(String refresh_token) { // 请求地址 String open_api_url_prefix = "https://ad.oceanengine.com/open_api/"; String uri = "oauth2/refresh_token/"; // 请求参数1 Map < String,String> data = new HashMap() { { put("appid", TokenCache.APP_ID); put("secret", TokenCache.SECRET); put("grant_type", "refresh_token"); put("refresh_token", refresh_token); } }; // 构造请求 JSONObject jsonObject = httpHelper.doPost(open_api_url_prefix + uri, data); if (jsonObject != null) { JSONObject data1 = jsonObject.getJSONObject("data"); TokenModel tokenModel = new TokenModel(data1.getString("access_token"), data1.getLong("expires_in"), data1.getString("refresh_token"), data1.getLong("refresh_token_expires_in")); return tokenModel; } return null; } @Scheduled(cron = "0 0 0/12 * * ?") public void refreshToke(){ log.info("==============refresh缓存的token!================================"); TokenModel tokenModel = accessTokenMap.get(key); if (tokenModel != null){ TokenModel tokenModel1 = refreshAccessToken(tokenModel.getRefresh_token()); setToken(tokenModel1); }else { applicationContext.publishEvent(new SendEmailEvent(this,"飞鱼销售线索未授权,到如下地址:\nhttps://ad.oceanengine.com/openapi/appid/list.html?rid=7ag3hu8nekn#/external/\n" + "登录后点APPID管理--->点击test那个猫--->点击下方的'点击跳转'-->完成授权\n账户:[email protected]\n" + "密码:Gd123456!", DefaultEmailAddress.SENDTODev,"飞鱼销售线索未授权!")); log.info("==================缓存的token失效=====需重新授权!================"); } } }
531e5cdd734d39cb798eed98817ec7c0d6d16e39
f15889af407de46a94fd05f6226c66182c6085d0
/callosumemr/src/main/java/com/nas/recovery/web/action/appointment/AppointmentAction.java
eed03dbf5497f5ce08f1b547fbc527d57620fd72
[]
no_license
oreon/sfcode-full
231149f07c5b0b9b77982d26096fc88116759e5b
bea6dba23b7824de871d2b45d2a51036b88d4720
refs/heads/master
2021-01-10T06:03:27.674236
2015-04-27T10:23:10
2015-04-27T10:23:10
55,370,912
0
0
null
null
null
null
UTF-8
Java
false
false
1,228
java
package com.nas.recovery.web.action.appointment; import java.util.ArrayList; import java.util.List; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import javax.persistence.EntityManager; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.apache.commons.lang.StringUtils; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Begin; import org.jboss.seam.annotations.End; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Out; import org.jboss.seam.Component; import org.jboss.seam.security.Identity; import org.jboss.seam.annotations.datamodel.DataModel; import org.jboss.seam.annotations.datamodel.DataModelSelection; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.log.Log; import org.jboss.seam.annotations.Observer; //@Scope(ScopeType.CONVERSATION) @Name("appointmentAction") public class AppointmentAction extends AppointmentActionBase implements java.io.Serializable{ }
[ "singhj@38423737-2f20-0410-893e-9c0ab9ae497d" ]
singhj@38423737-2f20-0410-893e-9c0ab9ae497d
fdb48558e34ebf0b11d207245a3ca978c733fc8a
32b6d118554d0323e7dae414de066eecc99c03a6
/src/main/java/com/mx/bookstore/service/Book.java
6e7f257417ab9de4eb2fec6f14b6293e9eba11c1
[]
no_license
ojuarass/BookStoreClient
f8bb9777c3d967ce5a554e8b298defb9836d928b
8ff3b97437a822fe086e7a4556ecc7a983a121d9
refs/heads/master
2021-02-16T15:56:04.647818
2020-03-04T22:53:48
2020-03-04T22:53:48
245,021,477
0
0
null
2020-10-13T20:04:53
2020-03-04T22:57:38
Java
UTF-8
Java
false
false
3,803
java
package com.mx.bookstore.service; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para book complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="book"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="author" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="editorial" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="isbn" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="type" type="{http://service.bookstore.mx.com/}bookTypeEnum" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "book", propOrder = { "author", "editorial", "isbn", "name", "type" }) public class Book { protected String author; protected String editorial; protected String isbn; protected String name; @XmlSchemaType(name = "string") protected BookTypeEnum type; /** * Obtiene el valor de la propiedad author. * * @return * possible object is * {@link String } * */ public String getAuthor() { return author; } /** * Define el valor de la propiedad author. * * @param value * allowed object is * {@link String } * */ public void setAuthor(String value) { this.author = value; } /** * Obtiene el valor de la propiedad editorial. * * @return * possible object is * {@link String } * */ public String getEditorial() { return editorial; } /** * Define el valor de la propiedad editorial. * * @param value * allowed object is * {@link String } * */ public void setEditorial(String value) { this.editorial = value; } /** * Obtiene el valor de la propiedad isbn. * * @return * possible object is * {@link String } * */ public String getIsbn() { return isbn; } /** * Define el valor de la propiedad isbn. * * @param value * allowed object is * {@link String } * */ public void setIsbn(String value) { this.isbn = value; } /** * Obtiene el valor de la propiedad name. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Define el valor de la propiedad name. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Obtiene el valor de la propiedad type. * * @return * possible object is * {@link BookTypeEnum } * */ public BookTypeEnum getType() { return type; } /** * Define el valor de la propiedad type. * * @param value * allowed object is * {@link BookTypeEnum } * */ public void setType(BookTypeEnum value) { this.type = value; } }
b777bf443ebd803081f2e607dfd7938777b29c2c
3857b52280f5e893140c3ce048ed86ed0c959ab4
/spring/ArtGallery/src/main/java/service/api/ProductService.java
2e2e0fb3f5153aa6785bfb8a91c53ca982bc7087
[]
no_license
madhuriSo/ArtGallery
ffdc17bc52f336b2216b8ba0019340e8c9e6ec26
2f844b516aa912e200f9fc3c2368f74772c72908
refs/heads/master
2021-08-28T04:22:00.807102
2017-12-11T07:07:03
2017-12-11T07:07:03
113,820,378
0
0
null
null
null
null
UTF-8
Java
false
false
160
java
package service.api; import service.data.ProductData; import java.util.List; public interface ProductService { public List<ProductData> getProducts(); }
399cda9e6802c4770686950b726e6fd6f3494999
b5a6450a4283bc604b5bbb6da266bfa8ee298de2
/src/test/java/com/mmxb/CarRentalMgrApplicationTests.java
25522d04cd0745869f6ab5ba3cdf7288a4a420c2
[]
no_license
MuhammadAmmad/rental-car-manager
70fb31f28e5c09e4511b7f7dc5f0907da62ed135
7e418f67925bb9ca2912bea980d2f53f3c913434
refs/heads/master
2021-05-30T01:34:37.638884
2015-12-05T17:03:59
2015-12-05T17:03:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
504
java
package com.mmxb; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = CarRentalMgrApplication.class) @WebAppConfiguration public class CarRentalMgrApplicationTests { @Test public void contextLoads() { } }
811cafc1d7e7ccaf39a3f9d615915998ba4e2e90
793458d39b0767814ecb805bb6f298191a74bd93
/rst-ws-cli/src/test/java/com/forkexec/rst/ws/it/ctrlClearIT.java
a61a58bd6eb4ce8ef2c535f1a333893a2a016392
[]
no_license
CubeSkyy/ist-sdis
883306c49d63122f7b5904adb898d6e7f98def75
6dc097fd143bed29d27b278d2e2a389a24ea0d69
refs/heads/master
2022-07-20T07:39:52.647109
2022-06-20T20:26:40
2022-06-20T20:26:40
199,046,555
0
0
null
null
null
null
UTF-8
Java
false
false
908
java
package com.forkexec.rst.ws.it; import com.forkexec.rst.ws.*; import org.junit.Test; import java.util.List; public class ctrlClearIT extends BaseIT { final int QUANTITY_TO_ORDER = 10; @Test(expected = BadMenuIdFault_Exception.class) public void successMenu() throws BadMenuIdFault_Exception, BadInitFault_Exception { List<MenuInit> lm = createInitList(); client.ctrlInit(lm); client.ctrlClear(); client.getMenu(createMenuId()); } @Test(expected = BadMenuIdFault_Exception.class) public void successOrder() throws BadMenuIdFault_Exception, BadInitFault_Exception, BadQuantityFault_Exception, InsufficientQuantityFault_Exception { List<MenuInit> lm = createInitList(); client.ctrlInit(lm); client.orderMenu(createMenuId(), QUANTITY_TO_ORDER); client.ctrlClear(); client.getMenu(createMenuId()); } }
5f283a50d4f29d35a805ace8bdacaafad4f08dac
17e1132297512ec937f73f4cdb618ff63be021fa
/src/main/java/com/alexp/repository/UserActivityRepository.java
9af8db7d8d26065de1fa5f852d7ab48a043c9ccf
[]
no_license
plotnik14/activity-log-app
ab376920b47bccc6d8f20df1adc5ef0861529fbd
082d08dae71b59a679966e3dab02b4781d81b0f8
refs/heads/main
2023-01-01T07:31:20.996927
2020-10-24T20:12:57
2020-10-24T20:12:57
306,961,797
0
0
null
null
null
null
UTF-8
Java
false
false
280
java
package com.alexp.repository; import com.alexp.model.UserActivityRecord; import java.util.Date; import java.util.List; public interface UserActivityRepository { List<UserActivityRecord> searchUserActivityRecordsByParams(List<Long> userIds, Date startDate, Date endDate); }
a7d9fb7243e6237724c3e3748176c60d7981fc79
fc98ecdc22882d25424c42f97ff902b22eccd436
/xmsadapter/src/main/java/org/xms/g/location/GeofencingEvent.java
d93485f11fc47687307d84013183b8176557a932
[]
no_license
Jos9eM/MapsHuawei
2e6614111b6cbcc0561958fc54494f660018fba1
13c4c8a29811857254d6743e634d3cb9cdeee990
refs/heads/master
2021-05-24T14:06:48.723702
2020-04-06T19:38:13
2020-04-06T19:38:13
253,597,995
0
0
null
null
null
null
UTF-8
Java
false
false
5,980
java
package org.xms.g.location; public class GeofencingEvent extends org.xms.g.utils.XObject { private boolean wrapper = true; public GeofencingEvent(com.google.android.gms.location.GeofencingEvent param0, com.huawei.hms.location.GeofenceData param1) { super(param0, null); this.setHInstance(param1); wrapper = true; } public static org.xms.g.location.GeofencingEvent fromIntent(android.content.Intent param0) { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "com.huawei.hms.location.GeofenceData.getDataFromIntent(param0)"); com.huawei.hms.location.GeofenceData hReturn = com.huawei.hms.location.GeofenceData.getDataFromIntent(param0); return ((hReturn) == null ? null : (new org.xms.g.location.GeofencingEvent(null, hReturn))); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "com.google.android.gms.location.GeofencingEvent.fromIntent(param0)"); com.google.android.gms.location.GeofencingEvent gReturn = com.google.android.gms.location.GeofencingEvent.fromIntent(param0); return ((gReturn) == null ? null : (new org.xms.g.location.GeofencingEvent(gReturn, null))); } } public int getErrorCode() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.location.GeofenceData) this.getHInstance()).getErrorCode()"); return ((com.huawei.hms.location.GeofenceData) this.getHInstance()).getErrorCode(); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getErrorCode()"); return ((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getErrorCode(); } } public int getGeofenceTransition() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConversion()"); return ((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConversion(); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getGeofenceTransition()"); return ((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getGeofenceTransition(); } } public java.util.List<org.xms.g.location.Geofence> getTriggeringGeofences() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConvertingGeofenceList()"); java.util.List hReturn = ((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConvertingGeofenceList(); return ((java.util.List) org.xms.g.utils.Utils.mapCollection(hReturn, new org.xms.g.utils.Function<com.huawei.hms.location.Geofence, org.xms.g.location.Geofence>() { public org.xms.g.location.Geofence apply(com.huawei.hms.location.Geofence param0) { return new org.xms.g.location.Geofence.XImpl(null, param0); } })); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getTriggeringGeofences()"); java.util.List gReturn = ((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getTriggeringGeofences(); return ((java.util.List) org.xms.g.utils.Utils.mapCollection(gReturn, new org.xms.g.utils.Function<com.google.android.gms.location.Geofence, org.xms.g.location.Geofence>() { public org.xms.g.location.Geofence apply(com.google.android.gms.location.Geofence param0) { return new org.xms.g.location.Geofence.XImpl(param0, null); } })); } } public android.location.Location getTriggeringLocation() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConvertingLocation()"); return ((com.huawei.hms.location.GeofenceData) this.getHInstance()).getConvertingLocation(); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getTriggeringLocation()"); return ((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).getTriggeringLocation(); } } public boolean hasError() { if (org.xms.g.utils.GlobalEnvSetting.isHms()) { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.huawei.hms.location.GeofenceData) this.getHInstance()).isFailure()"); return ((com.huawei.hms.location.GeofenceData) this.getHInstance()).isFailure(); } else { org.xms.g.utils.XmsLog.d("XMSRouter", "((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).hasError()"); return ((com.google.android.gms.location.GeofencingEvent) this.getGInstance()).hasError(); } } public static org.xms.g.location.GeofencingEvent dynamicCast(java.lang.Object param0) { return ((org.xms.g.location.GeofencingEvent) param0); } public static boolean isInstance(java.lang.Object param0) { if (!(param0 instanceof org.xms.g.utils.XGettable)) { return false; } if (org.xms.g.utils.GlobalEnvSetting.isHms()) { return ((org.xms.g.utils.XGettable) param0).getHInstance() instanceof com.huawei.hms.location.GeofenceData; } else { return ((org.xms.g.utils.XGettable) param0).getGInstance() instanceof com.google.android.gms.location.GeofencingEvent; } } }
56d47296d1b4fb4fd273056e5b97d5c0f8e63eb0
45801185e808b4da9bf641866e67f501ec13966f
/app2/src/main/java/com/example/wincber/recyclerdialogfragment/MyRecyclerHolder.java
71783b536abc5b6182274ed7e33f10f6f824eebf
[]
no_license
NIUNIUN/InjectStudy
79211e8f34d7ba297967f6805d1dfb8657923244
c3ab2333f37cbcde21e76167751427da69ef9245
refs/heads/master
2023-01-14T04:30:01.642577
2020-11-30T08:10:23
2020-11-30T08:10:23
317,152,008
0
0
null
null
null
null
UTF-8
Java
false
false
493
java
package com.example.wincber.recyclerdialogfragment; import android.support.v4.view.ViewPager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; /** * Created by wincber on 9/21/2016. */ public class MyRecyclerHolder extends RecyclerView.ViewHolder{ ViewPager mViewPager; public MyRecyclerHolder(View itemView) { super(itemView); this.mViewPager = (ViewPager)itemView.findViewById(R.id.pager); } }
989209f870e66dd71fd93abbfc52c9c2c9dd41bc
dd9fdb0016be5242d50e08ded1cec16aeb2048ea
/src/main/java/com/nordfors/springboot/backend/apirest/models/dao/IClienteDao.java
0e107a7645ebe1968c798121c9976d19200b1663
[]
no_license
ChristianNordfors/spring-apirest-clientes
112cf86a2a7358be82df702378f432bce888bc52
32d0c73c04d65d810e7e533123ce398b5bd5b8c3
refs/heads/master
2022-12-01T10:02:58.940191
2020-08-22T00:05:18
2020-08-22T00:05:18
289,145,732
0
0
null
null
null
null
UTF-8
Java
false
false
659
java
package com.nordfors.springboot.backend.apirest.models.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.nordfors.springboot.backend.apirest.models.entity.Cliente; import com.nordfors.springboot.backend.apirest.models.entity.Region; public interface IClienteDao extends JpaRepository<Cliente, Long>{ // Este método podría estar en una interface IRegionDao con su propio Crud o JpaRepository // En el Query se trabaja con objetos y no con tablas. Region es el nombre de la clase @Query("from Region") public List<Region> findAllRegiones(); }
eff4d919dcfd59c919a73fe5accf17cd5a2aa2a9
02d1e71d946456b7f619e3cb0350ddff54eef6e0
/app/src/main/java/com/appropel/xplanegps/view/util/LocationUtilImpl.java
c90d7f5955f1909d2ba2d371358b9f95cc7db7a1
[]
no_license
aworldnervelink/xplane-to-gps
a5b908f086db66651cefdc5849628297bfadb0f9
3b798ffa77c0339d1e5b0508fa152be74cba8445
refs/heads/master
2021-02-10T17:58:31.983366
2018-04-14T20:21:55
2018-04-14T20:21:55
244,405,795
0
0
null
null
null
null
UTF-8
Java
false
false
3,225
java
package com.appropel.xplanegps.view.util; import android.location.Location; import android.location.LocationManager; import com.appropel.xplane.udp.Data; import com.appropel.xplanegps.common.util.LocationUtil; import com.appropel.xplanegps.common.util.XPlaneVersion; import com.appropel.xplanegps.common.util.XPlaneVersionUtil; import com.appropel.xplanegps.model.Preferences; import java.lang.reflect.Method; import de.greenrobot.event.EventBus; /** * Utility for converting raw data into Android Location format. */ public final class LocationUtilImpl implements LocationUtil { /** Conversion factor from knots to m/s. */ public static final float KNOTS_TO_M_S = 0.514444444f; /** Conversion factor from feet to meters. */ public static final float FEET_TO_METERS = 0.3048f; /** EasyVFR magic number. */ private static final float EASY_VFR = 1234.0f; /** Preferences. */ private final Preferences preferences; /** Event bus. */ private final EventBus eventBus; /** * Constructs a new {@code LocationUtilImpl}. * @param preferences preferences. * @param eventBus event bus. */ public LocationUtilImpl(final Preferences preferences, final EventBus eventBus) { this.preferences = preferences; this.eventBus = eventBus; } @Override public void broadcastLocation(final Data data) { final XPlaneVersion version = XPlaneVersionUtil.getXPlaneVersion(preferences.getXplaneVersion()); // Transfer data values into a Location object. Location location = new Location(LocationManager.GPS_PROVIDER); for (Data.Chunk chunk : data.getChunks()) { switch (chunk.getIndex()) { case 3: // speeds location.setSpeed(chunk.getData()[3] * KNOTS_TO_M_S); break; case 17: // pitch, roll, headings (X-Plane 10, 11) case 18: // pitch, roll, headings (X-Plane 9) if (chunk.getIndex() == version.getHeadingIndex()) { location.setBearing(chunk.getData()[2]); } break; case 20: // lat, lon, altitude location.setLatitude(chunk.getData()[0]); location.setLongitude(chunk.getData()[1]); location.setAltitude(chunk.getData()[2] * FEET_TO_METERS); break; default: break; } } // Set the time in the location. location.setTime(System.currentTimeMillis()); // Set accuracy. location.setAccuracy(preferences.isEasyVfr() ? EASY_VFR : 1.0f); try { Method locationJellyBeanFixMethod = Location.class.getMethod("makeComplete"); if (locationJellyBeanFixMethod != null) { locationJellyBeanFixMethod.invoke(location); } } catch (final Exception ex) // NOPMD - we want to ignore this. { // Do nothing if method doesn't exist. } eventBus.post(location); } }
286fcec882dd84c8d4924210315d4362a565aa2d
c008f811103f4dd87f07d1b870fb7a2d75b76efe
/src/main/java/com/actividad06/service/DeporteServiceImpl.java
2d59273a47022dc3e8240a552bac63103392a4ba
[]
no_license
jeremychaflocgit/Actividad06
9ec919b1752bd0096a6926ead8a2ae5f1f2e42aa
3d45d6c873a363695fd0f4d486aa387e552ad91a
refs/heads/master
2023-08-22T07:48:43.104100
2021-10-18T03:07:30
2021-10-18T03:07:30
418,325,562
0
0
null
null
null
null
UTF-8
Java
false
false
477
java
package com.actividad06.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.actividad06.entity.Deporte; import com.actividad06.repository.DeporteRepository; @Service public class DeporteServiceImpl implements DeporteService { @Autowired private DeporteRepository repositorio; @Override public List<Deporte> listaDeporte() { return repositorio.findAll(); } }
[ "cchaf@ANTRYX" ]
cchaf@ANTRYX
eb380fd75b5063b774cc79bd869a2a5e5425d5a0
61ee320062727efd4cee4bf320f3025f6bacaef2
/src/io/github/norbipeti/chat/server/io/Cookies.java
a7fdefef87d1880053fade5ad790c66332a7b42f
[]
no_license
NorbiPeti/ChatServer
2900a83d09564b5369909f85020c865347e203c3
dfcd2c7effcc6c9066f63773e4860c937695102f
refs/heads/master
2020-12-25T14:58:07.820343
2018-06-22T09:54:35
2018-06-22T09:54:35
66,225,977
0
0
null
null
null
null
UTF-8
Java
false
false
1,779
java
package io.github.norbipeti.chat.server.io; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import com.sun.net.httpserver.HttpExchange; public class Cookies extends HashMap<String, Cookie> { private static final long serialVersionUID = -328053564170765287L; private String expiretime; public Cookies(int addyears) { super(); this.expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(addyears, 0, 0)) .format(DateTimeFormatter.RFC_1123_DATE_TIME); } public Cookies(String expiretime) { super(); this.expiretime = expiretime; } public Cookies() { super(); this.expiretime = ZonedDateTime.now(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME); } public void SendHeaders(HttpExchange exchange) { for (Entry<String, Cookie> item : entrySet()) exchange.getResponseHeaders().add("Set-Cookie", item.getKey() + "=" + item.getValue().getValue() + "; expires=" + expiretime); exchange.getResponseHeaders().add("Set-Cookie", "expiretime=" + expiretime + "; expires=" + expiretime); } public Cookies add(Cookie cookie) { this.put(cookie.getName(), cookie); return this; } public String getExpireTime() { return expiretime; } public ZonedDateTime getExpireTimeParsed() { return ZonedDateTime.parse(expiretime, DateTimeFormatter.RFC_1123_DATE_TIME); } public void setExpireTime(LocalDateTime expiretime) { this.expiretime = expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME); } @Override public String toString() { return "Cookies [expiretime=" + expiretime + ", " + super.toString() + "]"; } }
42a87627cc182340054619d32f15982a6a88445f
08a528e03695d6603d0e29b1b6391faa5cc3aefa
/src/main/java/org/seckill/entity/Seckill.java
c6363a80a7d9b2a68673364a655650c7be7471b3
[]
no_license
zihua-chen/seckillSystem
71be7e4fc0f4085260efefb660a2e3cc1275f3cc
9a913c741bcba502c852bace6c2461785775f66c
refs/heads/master
2023-01-13T11:07:14.889687
2020-11-19T06:40:56
2020-11-19T06:40:56
314,145,494
0
0
null
null
null
null
UTF-8
Java
false
false
1,510
java
package org.seckill.entity; import java.util.Date; /** * @author=zhch */ public class Seckill { private long seckillId; private String name; private int number; private Date startTime; private Date endTime; private Date createTime; public long getSeckillId() { return seckillId; } public void setSeckillId(long seckillId) { this.seckillId = seckillId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Seckill{" + "seckillId=" + seckillId + ", name='" + name + '\'' + ", number=" + number + ", startTime=" + startTime + ", endTime=" + endTime + ", createTime=" + createTime + '}'; } }
184180de9ee676c49f039b40d335916f581e0898
fe61c93162aa987a193f86c5f587b5cf8fe0dbc6
/src/com/javarush/JavaSyntax/task/task07/task0712/Solution.java
44a2c8576649340a34111632072a543ba955656a
[]
no_license
DenisLaptev/MyJavaRushProject
aa7edf1da9c98fdf2954b76c5f632f4c0d981869
ff5cc2d8a6640a59b84f50bc4fa609ef67bc0dfa
refs/heads/master
2020-06-29T08:11:13.786260
2019-08-04T11:07:09
2019-08-04T11:07:09
200,482,273
0
0
null
null
null
null
UTF-8
Java
false
false
1,380
java
package com.javarush.JavaSyntax.task.task07.task0712; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /* Самые-самые */ public class Solution { public static void main(String[] args) throws Exception { //напишите тут ваш код ArrayList<String> stringList = new ArrayList<>(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); for (int i = 0; i < 10; i++) { String string = bufferedReader.readLine(); stringList.add(string); } int minLength = stringList.get(0).length(); int maxLength = stringList.get(0).length(); for (int i = 0; i < 10; i++) { if (minLength > stringList.get(i).length()) { minLength = stringList.get(i).length(); } if (maxLength < stringList.get(i).length()) { maxLength = stringList.get(i).length(); } } for (int i = 0; i < 10; i++) { if (stringList.get(i).length() == minLength) { System.out.println(stringList.get(i)); break; } if (stringList.get(i).length() == maxLength) { System.out.println(stringList.get(i)); break; } } } }
bdc951717aae4aef617d589838f2f04bfd75691e
45d58ad7e0af7cf0ec69ee218b0ba46da81c2abd
/src/java/org/apache/fop/datatypes/ValidationPercentBaseContext.java
6349fc4d16757f9ddb20f9cc6079514b0cbf82a0
[ "Apache-2.0" ]
permissive
balabit-deps/balabit-os-7-fop
48cc73bfb90a83329d4e8041bf1c622884df8a08
3ff623f6752a0550998528362469857048ccb324
refs/heads/master
2020-04-07T09:11:06.972556
2018-11-07T15:43:56
2018-11-07T15:43:56
158,243,262
0
0
null
null
null
null
UTF-8
Java
false
false
2,169
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. */ /* $Id: ValidationPercentBaseContext.java 1617052 2014-08-10 06:55:01Z gadams $ */ package org.apache.fop.datatypes; import org.apache.fop.fo.FObj; /** * This base context is used during validation when the actual base values are still unknown * but should still already be checked. The actual value returned is not so important in this * case. But it's important that zero and non-zero values can be distinguished. * <p> * Example: A table with collapsing border model has no padding. The Table FO should be able * to check if non-zero values (even percentages) have been specified. */ public final class ValidationPercentBaseContext implements PercentBaseContext { /** * Main constructor. */ private ValidationPercentBaseContext() { } /** * Returns the value for the given lengthBase. * {@inheritDoc} */ public int getBaseLength(int lengthBase, FObj fobj) { //Simply return a dummy value which produces a non-zero value when a non-zero percentage //was specified. return 100000; } private static PercentBaseContext pseudoContextForValidation = new ValidationPercentBaseContext(); /** @return a base context for validation purposes. See class description. */ public static PercentBaseContext getPseudoContext() { return pseudoContextForValidation; } }
b74c2109d8ddfbcef3787abb409d231dfe3bb07f
c49fa7c0f679da9b05ad7dd8d3c98df42b059970
/EasyGandhinagar/src/com/nplussolutions/easygandhinagar/PublicFacilities.java
58741a82d1e2cdb66025821da4160252761240a8
[]
no_license
05bca054/gnadhinagar_android
d6c0eee81675dcf1607c6df62a8c1e457f92d6a2
7535c6dcd22617032e232ac9602ae786ab84d3d6
refs/heads/master
2021-01-23T02:59:19.245146
2014-09-24T05:11:05
2014-09-24T05:11:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,109
java
package com.nplussolutions.easygandhinagar; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import com.nplussolutions.easygandhinagar.Utils.Config; import com.nplussolutions.easygandhinagar.Utils.CustomProgressDialog; import com.nplussolutions.easygandhinagar.Utils.Utility; public class PublicFacilities extends Activity { Context ctx; String[] id,_name,sectorname; Button btn_exit_no_dialog; Button btn_exit_yes_dialog ; Button btn_home,btn_quit,btn_footersearch; Button btn_pub_postoffice,btn_pub_hospital,btn_pub_petrolpump,btn_pub_school,btn_pub_policestation,btn_pub_firestation, btn_pub_religious,btn_pub_garden,btn_pub_bank,btn_pub_theartre,btn_pub_communityhall,btn_pub_hotels,btn_pub_shoppingcenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.public_facilities); ctx = this; btn_home = (Button) findViewById(R.id.btn_home); btn_quit = (Button) findViewById(R.id.btn_quit); btn_footersearch = (Button) findViewById(R.id.btn_footersearch); btn_footersearch.setVisibility(View.INVISIBLE); btn_pub_postoffice = (Button) findViewById(R.id.btn_pub_postoffice); btn_pub_hospital = (Button) findViewById(R.id.btn_pub_hospital); btn_pub_petrolpump = (Button) findViewById(R.id.btn_pub_petrolpump); btn_pub_school = (Button) findViewById(R.id.btn_pub_school); btn_pub_policestation = (Button) findViewById(R.id.btn_pub_policestation); btn_pub_firestation = (Button) findViewById(R.id.btn_pub_firestation); btn_pub_religious = (Button) findViewById(R.id.btn_pub_religious); btn_pub_garden = (Button) findViewById(R.id.btn_pub_garden); btn_pub_bank = (Button) findViewById(R.id.btn_pub_bank); btn_pub_theartre = (Button) findViewById(R.id.btn_pub_theartre); btn_pub_communityhall = (Button) findViewById(R.id.btn_pub_communityhall); btn_pub_hotels = (Button) findViewById(R.id.btn_pub_hotels); btn_pub_shoppingcenter = (Button) findViewById(R.id.btn_pub_shoppingcenter); btn_home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ctx, Home.class)); overridePendingTransition(R.anim.slide_out_right, R.anim.slide_in_right); finish(); } }); btn_quit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { exitApp(); } }); btn_pub_postoffice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_postoffice.getText().toString(),btn_pub_postoffice.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_hospital.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_hospital.getText().toString(),btn_pub_hospital.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_petrolpump.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_petrolpump.getText().toString(),btn_pub_petrolpump.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_school.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_school.getText().toString(),btn_pub_school.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_policestation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_policestation.getText().toString(),btn_pub_policestation.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_firestation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_firestation.getText().toString(),btn_pub_firestation.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_religious.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_religious.getText().toString(),btn_pub_religious.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_garden.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_garden.getText().toString(),btn_pub_garden.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_bank.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_bank.getText().toString(),btn_pub_bank.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_theartre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_theartre.getText().toString(),btn_pub_theartre.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_communityhall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_communityhall.getText().toString(),btn_pub_communityhall.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_hotels.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_hotels.getText().toString(),btn_pub_hotels.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); btn_pub_shoppingcenter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Utility.isInternetAvailable(ctx)) new AsyncPublicServices(btn_pub_shoppingcenter.getText().toString(),btn_pub_shoppingcenter.getTag().toString()).execute(); else Utility.showDialog(PublicFacilities.this, "Easy Gandhinagar", "Something Going Wrong with your Internet Connection!!", R.drawable.ic_launcher); } }); } //Exit App public void exitApp(){ final Dialog exitapp = new Dialog(PublicFacilities.this); exitapp.requestWindowFeature(Window.FEATURE_NO_TITLE); exitapp.setContentView(R.layout.popup_logout); exitapp.setCancelable(false); btn_exit_no_dialog = (Button) exitapp.findViewById(R.id.btn_exit_no_dialog); btn_exit_yes_dialog = (Button) exitapp.findViewById(R.id.btn_exit_yes_dialog); btn_exit_yes_dialog.setOnClickListener(new OnClickListener() { public void onClick(View v) { stopService(new Intent(PublicFacilities.this, LocationService.class)); PublicFacilities.this.finish(); exitapp.dismiss(); } }); btn_exit_no_dialog.setOnClickListener(new OnClickListener() { public void onClick(View v) { exitapp.dismiss(); } }); exitapp.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); exitapp.show(); } public class AsyncPublicServices extends AsyncTask<Object, Object, Object> { String publicname,bui_id; CustomProgressDialog dialog; HttpClient httpclient; HttpGet httpget; HttpResponse response; public AsyncPublicServices(String publicname,String bui_id) { this.bui_id=bui_id; this.publicname = publicname; dialog = new CustomProgressDialog(ctx, "Loading..."); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setCancelable(false); dialog.show(); } @Override public Object doInBackground(Object... params) { try { httpclient = new DefaultHttpClient(); String query=""; query += (bui_id !=null) ? ("bui_id="+URLEncoder.encode(bui_id,"UTF-8")) : ""; httpget = new HttpGet(Config.URL + "button_pubserv.php?"+query); //http://nplussolutions.com/Webservices_Gujgov_finaldata/button_pubserv.php?bui_id=5 response = httpclient.execute(httpget); return EntityUtils.toString(response.getEntity()); } catch (Exception e) { return null; } } @Override public void onPreExecute() { super.onPreExecute(); dialog.show(); } @Override public void onPostExecute(Object result) { super.onPostExecute(result); try { if(result != null) { JSONArray service = new JSONArray(result.toString()); id = new String[service.length()]; _name = new String[service.length()]; sectorname = new String[service.length()]; for (int i=0; i<service.length(); i++) { JSONObject items = service.getJSONObject(i); try{ if(items.getString("gid").toString() != null || !items.getString("gid").toString().equals("")) id[i] = items.getString("gid"); } catch (Exception e) {Log.e("Exception", e.toString());} try{ if(items.getString("plot_no").toString() != null || !items.getString("plot_no").toString().equals("")) _name[i] = items.getString("plot_no"); } catch (Exception e) {Log.e("Exception", e.toString());} } Intent intent = new Intent(PublicFacilities.this,PublicFacilitiesList.class); intent.putExtra("listname", publicname); intent.putExtra("gid", id); intent.putExtra("name", _name); startActivity(intent); finish(); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } }catch(Exception e) { Utility.showPopupDialog(PublicFacilities.this,"Public Services not availble."); } dialog.dismiss(); } @Override public void onProgressUpdate(Object... values) { super.onProgressUpdate(values); } } @Override public void onBackPressed() { // TODO Auto-generated method stub startActivity(new Intent(ctx, Home.class)); overridePendingTransition(R.anim.slide_out_right, R.anim.slide_in_right); finish(); } // Menu Option @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_aboutus: // AboutUs final Dialog popup = new Dialog(PublicFacilities.this); popup.requestWindowFeature(Window.FEATURE_NO_TITLE); popup.setContentView(R.layout.popup_aboutus); popup.setCancelable(true); ImageView img_about_close = (ImageView) popup.findViewById(R.id.img_about_close); img_about_close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { popup.dismiss(); } }); popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); popup.show(); return true; case R.id.menu_feedback: // Feedback Feedback f = new Feedback(); f.feedback(ctx, PublicFacilities.this); return true; case R.id.menu_suggestion: // Suggestion Suggestion s = new Suggestion(); s.suggestion(ctx, PublicFacilities.this); return true; default: return super.onOptionsItemSelected(item); } } }
34b26ec2c2c7ac72aae0eebce3c5e565c7f06550
09308f131534645a55a6ebdea1e6200d2f172f91
/Tetris/Tetris_19June/game/src/devan/input/conditionalInput/ConditionalTouchUp.java
398547e8edb89d312418828065d6793d3b5801ba
[]
no_license
misterdustinface/prototypes
db937527bade4e5e151b32690d229deab2d8e6bf
b80e017317a329b63dfc609f2ac5d4b7d196d742
refs/heads/master
2021-01-25T12:24:01.090439
2015-08-02T19:54:53
2015-08-02T19:54:53
18,827,082
0
0
null
null
null
null
UTF-8
Java
false
false
539
java
package devan.input.conditionalInput; import devan.input.VGesture.TouchUpListener; public class ConditionalTouchUp implements TouchUpListener{ Conditional condition; TouchUpListener listener; public ConditionalTouchUp(Conditional condition, TouchUpListener listener) { this.condition = condition; this.listener = listener; } @Override public boolean touchUp(int x, int y, int pointer, int button) { if(condition.isConditionMet()) { listener.touchUp(x, y, pointer, button); } return false; } }
bb7af0d2fca4fa1c885568fcbd2527af693b1670
e49ddf6e23535806c59ea175b2f7aa4f1fb7b585
/tags/release-5.2.1/mipav/src/plugins/PlugInAlgorithmDrosophilaRetinalRegistration.java
0e1798e4e0219ca05694209450d2338c8956d3a6
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
svn2github/mipav
ebf07acb6096dff8c7eb4714cdfb7ba1dcace76f
eb76cf7dc633d10f92a62a595e4ba12a5023d922
refs/heads/master
2023-09-03T12:21:28.568695
2019-01-18T23:13:53
2019-01-18T23:13:53
130,295,718
1
0
null
null
null
null
UTF-8
Java
false
false
61,751
java
import gov.nih.mipav.util.MipavMath; import gov.nih.mipav.model.algorithms.*; import gov.nih.mipav.model.algorithms.utilities.AlgorithmFlip; import gov.nih.mipav.model.file.*; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import gov.nih.mipav.view.dialogs.JDialogVOIStatistics; import gov.nih.mipav.view.dialogs.JPanelPixelExclusionSelector.ExclusionRangeType; import java.io.IOException; import javax.swing.*; import WildMagic.LibFoundation.Curves.BSplineBasisDiscretef; import WildMagic.LibFoundation.Mathematics.Vector3f; /** * This plugin was done for Dr Chi-hon Lee of NICHD * * The main research problem Dr Lee had was that the z-resolution is poor compared to x and y when acquiring datsets * using confocal microscopy * * The solution was to acquire 2 orthogonal datsets and combine them into a result image * * In order to achieve this, one dataset needs to be registered to the other datset to obtain transformation files. This * part is done prior to the plugin by a user * * This plugin builds a result image by transforming back to both images using the transformation files and applying a * certain combination of the pixels to put in the result image * * The result image is of 512x512x512 size * * @author pandyan */ public class PlugInAlgorithmDrosophilaRetinalRegistration extends AlgorithmBase { /** images * */ private ModelImage imageX, imageXRegistered, imageY, resultImage, redChannelsImage, greenChannelsImage, imageXRegisteredTransformed, imageYTransformed; /** alg * */ private AlgorithmVOIProps algoVOIProps; /** min and maxes of vois * */ private float minR_X, minG_X, minB_X, minR_Y, minG_Y, minB_Y, maxR_X, maxG_X, maxB_X, maxR_Y, maxG_Y, maxB_Y; /** vjf to draw vois on * */ private final ViewJFrameImage vjfX, vjfY; private final JTextArea outputTextArea; /** slope of transfer function * */ private float slopeR, slopeG, slopeB; /** b-intercept of transfer function * */ private float bR, bG, bB; /** transform matrices * */ private final TransMatrix matrixGreen, matrixAffine; /** 2D and 3D B-Spline basis definitions. */ private BSplineBasisDiscretef m_kBSplineBasisX; /** b spline */ private BSplineBasisDiscretef m_kBSplineBasisY; /** b spline */ private BSplineBasisDiscretef m_kBSplineBasisZ; /** b slpine */ private BSplineLattice3Df m_kBSpline3D; /** alg * */ private AlgorithmTransform algoTrans; /** image y res * */ private final float[] imageYRes; /** image Y end * */ private final boolean imageYEnd; /** dir * */ private final String dir; /** image x orig * */ private final float[] imageXOrig; /** extents */ private final int[] imageYExtents; /** radio buttons * */ private final JRadioButton doTrilinearRadio, doAverageRadio, doRescaleRadio, ignoreBGRadio, doSqRtRadio; /** textfield * */ private final JTextField transform3FilePathTextField; /** num control points * */ private final int numControlPoints; /** spline degree * */ private final int splineDegree; /** control mat * */ private final float[][] controlMat; private boolean createMirroredImg; /** * constructr * * @param imageX * @param imageXRegistered * @param imageY * @param vjfX * @param vjfY * @param outputTextArea * @param matrixGreen * @param matrixAffine * @param doTrilinearRadio * @param doAverageRadio * @param doRescaleRadio * @param ignoreBGRadio * @param doSqRtRadio * @param transform3FilePathTextField * @param numControlPoints * @param splineDegree * @param controlMat */ public PlugInAlgorithmDrosophilaRetinalRegistration(final ModelImage imageX, final ModelImage imageXRegistered, final ModelImage imageY, final ViewJFrameImage vjfX, final ViewJFrameImage vjfY, final JTextArea outputTextArea, final TransMatrix matrixGreen, final TransMatrix matrixAffine, final JRadioButton doTrilinearRadio, final JRadioButton doAverageRadio, final JRadioButton doRescaleRadio, final JRadioButton ignoreBGRadio, final JRadioButton doSqRtRadio, final JTextField transform3FilePathTextField, final int numControlPoints, final int splineDegree, final float[][] controlMat, boolean createMirroredImg) { this.imageX = imageX; this.imageXRegistered = imageXRegistered; this.imageY = imageY; this.vjfX = vjfX; this.vjfY = vjfY; this.outputTextArea = outputTextArea; this.matrixGreen = matrixGreen; this.matrixAffine = matrixAffine; this.doTrilinearRadio = doTrilinearRadio; this.doAverageRadio = doAverageRadio; this.doRescaleRadio = doRescaleRadio; this.ignoreBGRadio = ignoreBGRadio; this.doSqRtRadio = doSqRtRadio; this.transform3FilePathTextField = transform3FilePathTextField; this.numControlPoints = numControlPoints; this.splineDegree = splineDegree; this.controlMat = controlMat; this.createMirroredImg = createMirroredImg; imageYRes = imageY.getResolutions(0); imageYEnd = imageY.getFileInfo()[0].getEndianess(); dir = imageY.getFileInfo()[0].getFileDirectory(); imageXOrig = imageX.getFileInfo()[0].getOrigin(); imageYExtents = imageY.getExtents(); } /** * run algorithm */ public void runAlgorithm() { outputTextArea.append("Running Algorithm v2.9" + "\n"); final long begTime = System.currentTimeMillis(); // rescale imageX intensity to imageY based on VOI if (doRescaleRadio.isSelected()) { outputTextArea.append("Rescaling image... \n"); final VOIVector VOIsX = imageX.getVOIs(); final int nVOIX = VOIsX.size(); if (nVOIX != 1) { MipavUtil.displayError("Both images must contain one VOI"); return; } final VOIVector VOIsY = imageY.getVOIs(); final int nVOIY = VOIsY.size(); if (nVOIY != 1) { MipavUtil.displayError("Both images must contain one VOI"); return; } final VOI VOIX = VOIsX.VOIAt(0); VOIX.setAllActive(true); algoVOIProps = new AlgorithmVOIProps(imageX, AlgorithmVOIProps.PROCESS_PER_VOI, ExclusionRangeType.NO_RANGE, getActiveVOIs(imageX)); algoVOIProps.run(); minR_X = algoVOIProps.getMinIntensityRed(); maxR_X = algoVOIProps.getMaxIntensityRed(); minG_X = algoVOIProps.getMinIntensityGreen(); maxG_X = algoVOIProps.getMaxIntensityGreen(); minB_X = algoVOIProps.getMinIntensityBlue(); maxB_X = algoVOIProps.getMaxIntensityBlue(); algoVOIProps.finalize(); algoVOIProps = null; final VOI VOIY = VOIsY.VOIAt(0); VOIY.setAllActive(true); algoVOIProps = new AlgorithmVOIProps(imageY, AlgorithmVOIProps.PROCESS_PER_VOI, ExclusionRangeType.NO_RANGE, getActiveVOIs(imageY)); algoVOIProps.run(); minR_Y = algoVOIProps.getMinIntensityRed(); maxR_Y = algoVOIProps.getMaxIntensityRed(); minG_Y = algoVOIProps.getMinIntensityGreen(); maxG_Y = algoVOIProps.getMaxIntensityGreen(); minB_Y = algoVOIProps.getMinIntensityBlue(); maxB_Y = algoVOIProps.getMaxIntensityBlue(); algoVOIProps.finalize(); algoVOIProps = null; vjfX.setVisible(false); vjfY.setVisible(false); VOIsX.clear(); VOIsY.clear(); slopeG = calculateSlope(minG_Y, minG_X, maxG_Y, maxG_X); bG = calculateB(minG_Y, minG_X, slopeG); // now we go through imageX and rescale final int length = imageX.getExtents()[0] * imageX.getExtents()[1] * imageX.getExtents()[2] * 4; final float[] buffer = new float[length]; try { imageX.exportData(0, length, buffer); } catch (final IOException error) { System.out.println("IO exception"); return; } float green; float newGreen; for (int i = 0; i < buffer.length; i = i + 4) { /* * red = buffer[i+1]; if(slopeR == 0 && bR == 0) { newRed = red; }else { newRed = * getNewValue(red,slopeR,bR); if(newRed < 0) { newRed = 0; }else if(newRed > 255) { newRed = 255; } } * buffer[i+1] = newRed; */ green = buffer[i + 2]; if (slopeG == 0 && bG == 0) { newGreen = green; } else { newGreen = getNewValue(green, slopeG, bG); if (newGreen < 0) { newGreen = 0; } else if (newGreen > 255) { newGreen = 255; } } buffer[i + 2] = newGreen; /* * blue = buffer[i+3]; if(slopeB == 0 && bB == 0) { newBlue = blue; }else { newBlue = * getNewValue(blue,slopeB,bB); if(newBlue < 0) { newBlue = 0; }else if(newBlue > 255) { newBlue = * 255; } } buffer[i+3] = newBlue; */ } try { imageX.importData(0, buffer, true); } catch (final IOException error) { System.out.println("IO exception"); return; } imageX.calcMinMax(); }// done rescaling TransMatrix intermMatrix1; if(matrixGreen == null) { intermMatrix1 = matrixAffine; intermMatrix1.Inverse(); }else { intermMatrix1 = new TransMatrix(4); intermMatrix1.Mult(matrixAffine, matrixGreen); // pretty sure this is correct intermMatrix1.Inverse(); } final int[] extents = {512, 512, 512}; resultImage = new ModelImage(ModelStorageBase.ARGB, extents, "resultImage"); final float[] resultImageResols = new float[3]; resultImageResols[0] = imageY.getResolutions(0)[0]; resultImageResols[1] = imageY.getResolutions(0)[1]; resultImageResols[2] = imageY.getResolutions(0)[2] * imageY.getExtents()[2] / 512; for (int i = 0; i < resultImage.getExtents()[2]; i++) { resultImage.setResolutions(i, resultImageResols); } final byte[] resultBuffer = new byte[512 * 512 * 512 * 4]; int index = 0; // index into resultBuffer final double[] tPt1 = new double[3]; final double[] tPt2 = new double[3]; byte[] imageXBuffer; final int length1 = imageX.getExtents()[0] * imageX.getExtents()[1] * imageX.getExtents()[2] * 4; imageXBuffer = new byte[length1]; try { imageX.exportData(0, length1, imageXBuffer); } catch (final IOException error) { System.out.println("IO exception"); return; } AlgorithmBSpline bSplineX = new AlgorithmBSpline(); float[] imageXFloatBuffer = new float[length1]; for (int c = 0; c < 4; c++) { for (int z = 0; z < imageX.getExtents()[2]; z++) { for (int y = 0; y < imageX.getExtents()[1]; y++) { for (int x = 0; x < imageX.getExtents()[0]; x++) { int tempIndex = 4 * (z * imageX.getExtents()[1] * imageX.getExtents()[0] + y * imageX.getExtents()[0] + x) + c; imageXFloatBuffer[tempIndex] = (imageXBuffer[tempIndex] & 0xff); } } } } bSplineX.setup3DBSplineC(imageXFloatBuffer, imageX.getExtents(), 3); byte[] imageYBuffer; final int length2 = imageY.getExtents()[0] * imageY.getExtents()[1] * imageY.getExtents()[2] * 4; imageYBuffer = new byte[length2]; try { imageY.exportData(0, length2, imageYBuffer); } catch (final IOException error) { System.out.println("IO exception"); return; } AlgorithmBSpline bSplineY = new AlgorithmBSpline(); float[] imageYFloatBuffer = new float[length2]; for (int c = 0; c < 4; c++) { for (int z = 0; z < imageY.getExtents()[2]; z++) { for (int y = 0; y < imageY.getExtents()[1]; y++) { for (int x = 0; x < imageY.getExtents()[0]; x++) { int tempIndex = 4 * (z * imageY.getExtents()[1] * imageY.getExtents()[0] + y * imageY.getExtents()[0] + x) + c; imageYFloatBuffer[tempIndex] = (imageYBuffer[tempIndex] & 0xff); } } } } bSplineY.setup3DBSplineC(imageYFloatBuffer, imageY.getExtents(), 3); // following is if nlt file is inputted also ModelSimpleImage[] akSimpleImageSourceMap = null; if ( !transform3FilePathTextField.getText().trim().equals("")) { // create the non-linear image-maps m_kBSplineBasisX = new BSplineBasisDiscretef(numControlPoints, splineDegree, imageYExtents[0]); m_kBSplineBasisY = new BSplineBasisDiscretef(numControlPoints, splineDegree, imageYExtents[1]); m_kBSplineBasisZ = new BSplineBasisDiscretef(numControlPoints, splineDegree, imageYExtents[2]); m_kBSpline3D = new BSplineLattice3Df(m_kBSplineBasisX, m_kBSplineBasisY, m_kBSplineBasisZ); final Vector3f kPoint = new Vector3f(); int ind = 0; for (int iControlX = 0; iControlX < numControlPoints; iControlX++) { // System.out.println("iControlX = " + iControlX); for (int iControlY = 0; iControlY < numControlPoints; iControlY++) { for (int iControlZ = 0; iControlZ < numControlPoints; iControlZ++) { kPoint.X = controlMat[ind][0]; kPoint.Y = controlMat[ind][1]; kPoint.Z = controlMat[ind++][2]; m_kBSpline3D.setControlPoint(iControlX, iControlY, iControlZ, kPoint); } } } akSimpleImageSourceMap = m_kBSpline3D.createImageMap(imageYExtents[0], imageYExtents[1], imageYExtents[2]); } // okay....now.... float xmm, ymm, zmm; byte[] rgb1 = new byte[3]; byte[] rgb2 = new byte[3]; final short[] rgb1_short = new short[3]; final short[] rgb2_short = new short[3]; // loop through each point in result image outputTextArea.append("Combining images into result image... \n"); for (int z = 0; z < 512; z++) { outputTextArea.append("z is " + z + "\n"); for (int y = 0; y < 512; y++) { for (int x = 0; x < 512; x++) { // first transform the point back to both spaces...results in tPt1 and tPt2 if ( !transform3FilePathTextField.getText().trim().equals("")) { // if nlt file is inputted xmm = x * resultImage.getResolutions(0)[0]; ymm = y * resultImage.getResolutions(0)[1]; zmm = z * resultImage.getResolutions(0)[2]; tPt1[0] = MipavMath.round(xmm / imageY.getResolutions(0)[0]); tPt1[1] = MipavMath.round(ymm / imageY.getResolutions(0)[1]); tPt1[2] = MipavMath.round(zmm / imageY.getResolutions(0)[2]); tPt2[0] = xmm / imageY.getResolutions(0)[0]; tPt2[1] = ymm / imageY.getResolutions(0)[1]; tPt2[2] = zmm / imageY.getResolutions(0)[2]; final int iIndexTrg = (int) tPt1[0] + ((int) tPt1[1] * imageYExtents[0]) + ((int) tPt1[2] * imageYExtents[0] * imageYExtents[1]); float xMapPt = 0.0f; float yMapPt = 0.0f; float zMapPt = 0.0f; if (iIndexTrg < akSimpleImageSourceMap[0].data.length) { xMapPt = (imageYExtents[0] - 1) * akSimpleImageSourceMap[0].data[iIndexTrg]; yMapPt = (imageYExtents[1] - 1) * akSimpleImageSourceMap[1].data[iIndexTrg]; zMapPt = (imageYExtents[2] - 1) * akSimpleImageSourceMap[2].data[iIndexTrg]; } xmm = xMapPt * imageY.getResolutions(0)[0]; ymm = yMapPt * imageY.getResolutions(0)[1]; zmm = zMapPt * imageY.getResolutions(0)[2]; intermMatrix1.transform(xmm, ymm, zmm, tPt1); tPt1[0] = tPt1[0] / imageX.getResolutions(0)[0]; tPt1[1] = tPt1[1] / imageX.getResolutions(0)[1]; tPt1[2] = tPt1[2] / imageX.getResolutions(0)[2]; } else { // if nlt file is NOT inputted xmm = x * resultImage.getResolutions(0)[0]; ymm = y * resultImage.getResolutions(0)[1]; zmm = z * resultImage.getResolutions(0)[2]; //6/4/2010 /*intermMatrix1.transform(xmm, ymm, zmm, tPt1); tPt1[0] = tPt1[0] / imageY.getResolutions(0)[0]; tPt1[1] = tPt1[1] / imageY.getResolutions(0)[1]; tPt1[2] = tPt1[2] / imageY.getResolutions(0)[2];*/ //6/4/2010 tPt1[0] = MipavMath.round(xmm / imageY.getResolutions(0)[0]); tPt1[1] = MipavMath.round(ymm / imageY.getResolutions(0)[1]); tPt1[2] = MipavMath.round(zmm / imageY.getResolutions(0)[2]); intermMatrix1.transform(xmm, ymm, zmm, tPt1); tPt1[0] = tPt1[0] / imageX.getResolutions(0)[0]; tPt1[1] = tPt1[1] / imageX.getResolutions(0)[1]; tPt1[2] = tPt1[2] / imageX.getResolutions(0)[2]; xmm = x * resultImage.getResolutions(0)[0]; ymm = y * resultImage.getResolutions(0)[1]; zmm = z * resultImage.getResolutions(0)[2]; tPt2[0] = xmm / imageY.getResolutions(0)[0]; tPt2[1] = ymm / imageY.getResolutions(0)[1]; tPt2[2] = zmm / imageY.getResolutions(0)[2]; } // Now either do averaging or closest-Z int floorPointIndex1 = 0, floorPointIndex2 = 0; if (doAverageRadio.isSelected() || doSqRtRadio.isSelected()) { // get linear interpolated values from both transformed points if (tPt1[0] < 0 || tPt1[1] < 0 || tPt1[2] < 0 || tPt1[0] > imageX.getExtents()[0] - 1 || tPt1[1] > imageX.getExtents()[1] - 1 || tPt1[2] > imageX.getExtents()[2] - 1) { rgb1_short[0] = 0; rgb1_short[1] = 0; rgb1_short[2] = 0; } else { final double tX1_floor = Math.floor(tPt1[0]); final double tY1_floor = Math.floor(tPt1[1]); final double tZ1_floor = Math.floor(tPt1[2]); final float dx1 = (float) (tPt1[0] - tX1_floor); final float dy1 = (float) (tPt1[1] - tY1_floor); final float dz1 = (float) (tPt1[2] - tZ1_floor); final int[] extents1 = imageX.getExtents(); floorPointIndex1 = (int) ( ( (tZ1_floor * (extents1[0] * extents1[1])) + (tY1_floor * extents1[0]) + tX1_floor) * 4); if (floorPointIndex1 < imageXBuffer.length) { if (doTrilinearRadio.isSelected()) { rgb1 = AlgorithmConvolver.getTrilinearC(floorPointIndex1, dx1, dy1, dz1, extents1, imageXBuffer); rgb1_short[0] = (short) (rgb1[0] & 0xff); rgb1_short[1] = (short) (rgb1[1] & 0xff); rgb1_short[2] = (short) (rgb1[2] & 0xff); } else { float[] tempValues = bSplineX.bSpline3DC(0, 0, 0, (float)tX1_floor, (float)tY1_floor, (float)tZ1_floor); for ( int c = 0; c < 4; c++ ) { if (tempValues[c] > 255) { tempValues[c] = 255; } else if (tempValues[c] < 0) { tempValues[c] = 0; } } rgb1_short[0] = (short) (tempValues[1]); rgb1_short[1] = (short) (tempValues[2]); rgb1_short[2] = (short) (tempValues[3]); /* r1_float = splineAlgX_R.interpolatedValue(imageX_R_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (r1_float > 255) { r1_float = 255; } else if (r1_float < 0) { r1_float = 0; } g1_float = splineAlgX_G.interpolatedValue(imageX_G_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (g1_float > 255) { g1_float = 255; } else if (g1_float < 0) { g1_float = 0; } b1_float = splineAlgX_B.interpolatedValue(imageX_B_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (b1_float > 255) { b1_float = 255; } else if (b1_float < 0) { b1_float = 0; } rgb1_short[0] = (short) (r1_float); rgb1_short[1] = (short) (g1_float); rgb1_short[2] = (short) (b1_float); */ } } else { rgb1_short[0] = 0; rgb1_short[1] = 0; rgb1_short[2] = 0; } } if (tPt2[0] < 0 || tPt2[1] < 0 || tPt2[2] < 0 || tPt2[0] > imageY.getExtents()[0] - 1 || tPt2[1] > imageY.getExtents()[1] - 1 || tPt2[2] > imageY.getExtents()[2] - 1) { rgb2_short[0] = 0; rgb2_short[1] = 0; rgb2_short[2] = 0; } else { final double tX2_floor = Math.floor(tPt2[0]); final double tY2_floor = Math.floor(tPt2[1]); final double tZ2_floor = Math.floor(tPt2[2]); final float dx2 = (float) (tPt2[0] - tX2_floor); final float dy2 = (float) (tPt2[1] - tY2_floor); final float dz2 = (float) (tPt2[2] - tZ2_floor); final int[] extents2 = imageY.getExtents(); floorPointIndex2 = (int) ( ( (tZ2_floor * (extents2[0] * extents2[1])) + (tY2_floor * extents2[0]) + tX2_floor) * 4); if (floorPointIndex2 < imageYBuffer.length) { if (doTrilinearRadio.isSelected()) { rgb2 = AlgorithmConvolver.getTrilinearC(floorPointIndex2, dx2, dy2, dz2, extents2, imageYBuffer); rgb2_short[0] = (short) (rgb2[0] & 0xff); rgb2_short[1] = (short) (rgb2[1] & 0xff); rgb2_short[2] = (short) (rgb2[2] & 0xff); } else { float[] tempValues = bSplineY.bSpline3DC(0, 0, 0, (float)tX2_floor, (float)tY2_floor, (float)tZ2_floor); for ( int c = 0; c < 4; c++ ) { if (tempValues[c] > 255) { tempValues[c] = 255; } else if (tempValues[c] < 0) { tempValues[c] = 0; } } rgb2_short[0] = (short) (tempValues[1]); rgb2_short[1] = (short) (tempValues[2]); rgb2_short[2] = (short) (tempValues[3]); /* r2_float = splineAlgY_R.interpolatedValue(imageY_R_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (r2_float > 255) { r2_float = 255; } else if (r2_float < 0) { r2_float = 0; } g2_float = splineAlgY_G.interpolatedValue(imageY_G_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (g2_float > 255) { g2_float = 255; } else if (g2_float < 0) { g2_float = 0; } b2_float = splineAlgY_B.interpolatedValue(imageY_B_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (b2_float > 255) { b2_float = 255; } else if (b2_float < 0) { b2_float = 0; } rgb2_short[0] = (short) (r2_float); rgb2_short[1] = (short) (g2_float); rgb2_short[2] = (short) (b2_float); */ } } else { rgb2_short[0] = 0; rgb2_short[1] = 0; rgb2_short[2] = 0; } } byte avgR, avgG, avgB; if (doAverageRadio.isSelected()) { // dont do combining if other point is all background if (ignoreBGRadio.isSelected()) { if (rgb1_short[0] == 0 && rgb1_short[1] == 0 && rgb1_short[2] == 0) { avgR = (byte) rgb2_short[0]; avgG = (byte) rgb2_short[1]; avgB = (byte) rgb2_short[2]; } else if (rgb2_short[0] == 0 && rgb2_short[1] == 0 && rgb2_short[2] == 0) { avgR = (byte) rgb1_short[0]; avgG = (byte) rgb1_short[1]; avgB = (byte) rgb1_short[2]; } else { // averaging avgR = (byte) Math.round( ( (rgb1_short[0] + rgb2_short[0]) / 2.0f)); avgG = (byte) Math.round( ( (rgb1_short[1] + rgb2_short[1]) / 2.0f)); avgB = (byte) Math.round( ( (rgb1_short[2] + rgb2_short[2]) / 2.0f)); } } else { // averaging avgR = (byte) Math.round( ( (rgb1_short[0] + rgb2_short[0]) / 2.0f)); avgG = (byte) Math.round( ( (rgb1_short[1] + rgb2_short[1]) / 2.0f)); avgB = (byte) Math.round( ( (rgb1_short[2] + rgb2_short[2]) / 2.0f)); } } else { // dont do combining if other point is all background if (ignoreBGRadio.isSelected()) { if (rgb1_short[0] == 0 && rgb1_short[1] == 0 && rgb1_short[2] == 0) { avgR = (byte) rgb2_short[0]; avgG = (byte) rgb2_short[1]; avgB = (byte) rgb2_short[2]; } else if (rgb2_short[0] == 0 && rgb2_short[1] == 0 && rgb2_short[2] == 0) { avgR = (byte) rgb1_short[0]; avgG = (byte) rgb1_short[1]; avgB = (byte) rgb1_short[2]; } else { // doing Sqrt (Intensity X * Intensity Y) avgR = (byte) Math.sqrt(rgb1_short[0] * rgb2_short[0]); avgG = (byte) Math.sqrt(rgb1_short[1] * rgb2_short[1]); avgB = (byte) Math.sqrt(rgb1_short[2] * rgb2_short[2]); } } else { // doing Sqrt (Intensity X * Intensity Y) avgR = (byte) Math.sqrt(rgb1_short[0] * rgb2_short[0]); avgG = (byte) Math.sqrt(rgb1_short[1] * rgb2_short[1]); avgB = (byte) Math.sqrt(rgb1_short[2] * rgb2_short[2]); } } // alpha resultBuffer[index] = (byte) 1; // r index = index + 1; resultBuffer[index] = avgR; // g index = index + 1; resultBuffer[index] = avgG; // b index = index + 1; resultBuffer[index] = avgB; index = index + 1; } else { // CLOSEST Z // look at z transformed points double diff1, diff2; if (tPt1[2] - Math.floor(tPt1[2]) <= .5) { diff1 = tPt1[2] - Math.floor(tPt1[2]); } else { diff1 = Math.ceil(tPt1[2]) - tPt1[2]; } if (tPt2[2] - Math.floor(tPt2[2]) <= .5) { diff2 = tPt2[2] - Math.floor(tPt2[2]); } else { diff2 = Math.ceil(tPt2[2]) - tPt2[2]; } diff1 = diff1 * imageX.getResolutions(0)[2]; diff2 = diff2 * imageY.getResolutions(0)[2]; // get linear interpolated values from both transformed points if (tPt1[0] < 0 || tPt1[1] < 0 || tPt1[2] < 0 || tPt1[0] > imageX.getExtents()[0] - 1 || tPt1[1] > imageX.getExtents()[1] - 1 || tPt1[2] > imageX.getExtents()[2] - 1) { rgb1_short[0] = 0; rgb1_short[1] = 0; rgb1_short[2] = 0; } else { final double tX1_floor = Math.floor(tPt1[0]); final double tY1_floor = Math.floor(tPt1[1]); final double tZ1_floor = Math.floor(tPt1[2]); final float dx1 = (float) (tPt1[0] - tX1_floor); final float dy1 = (float) (tPt1[1] - tY1_floor); final float dz1 = (float) (tPt1[2] - tZ1_floor); final int[] extents1 = imageX.getExtents(); floorPointIndex1 = (int) ( ( (tZ1_floor * (extents1[0] * extents1[1])) + (tY1_floor * extents1[0]) + tX1_floor) * 4); if (doTrilinearRadio.isSelected()) { rgb1 = AlgorithmConvolver.getTrilinearC(floorPointIndex1, dx1, dy1, dz1, extents1, imageXBuffer); rgb1_short[0] = (short) (rgb1[0] & 0xff); rgb1_short[1] = (short) (rgb1[1] & 0xff); rgb1_short[2] = (short) (rgb1[2] & 0xff); } else { float[] tempValues = bSplineY.bSpline3DC(0, 0, 0, (float)tX1_floor, (float)tY1_floor, (float)tZ1_floor); for ( int c = 0; c < 4; c++ ) { if (tempValues[c] > 255) { tempValues[c] = 255; } else if (tempValues[c] < 0) { tempValues[c] = 0; } } rgb1_short[0] = (short) (tempValues[1]); rgb1_short[1] = (short) (tempValues[2]); rgb1_short[2] = (short) (tempValues[3]); /* r1_float = splineAlgX_R.interpolatedValue(imageX_R_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (r1_float > 255) { r1_float = 255; } else if (r1_float < 0) { r1_float = 0; } g1_float = splineAlgX_G.interpolatedValue(imageX_G_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (g1_float > 255) { g1_float = 255; } else if (g1_float < 0) { g1_float = 0; } b1_float = splineAlgX_B.interpolatedValue(imageX_B_coeff, tX1_floor, tY1_floor, tZ1_floor, extents1[0], extents1[1], extents1[2], 3); if (b1_float > 255) { b1_float = 255; } else if (b1_float < 0) { b1_float = 0; } rgb1_short[0] = (short) (r1_float); rgb1_short[1] = (short) (g1_float); rgb1_short[2] = (short) (b1_float); */ } } if (tPt2[0] < 0 || tPt2[1] < 0 || tPt2[2] < 0 || tPt2[0] > imageY.getExtents()[0] - 1 || tPt2[1] > imageY.getExtents()[1] - 1 || tPt2[2] > imageY.getExtents()[2] - 1) { rgb2_short[0] = 0; rgb2_short[1] = 0; rgb2_short[2] = 0; } else { final double tX2_floor = Math.floor(tPt2[0]); final double tY2_floor = Math.floor(tPt2[1]); final double tZ2_floor = Math.floor(tPt2[2]); final float dx2 = (float) (tPt2[0] - tX2_floor); final float dy2 = (float) (tPt2[1] - tY2_floor); final float dz2 = (float) (tPt2[2] - tZ2_floor); final int[] extents2 = imageY.getExtents(); floorPointIndex2 = (int) ( ( (tZ2_floor * (extents2[0] * extents2[1])) + (tY2_floor * extents2[0]) + tX2_floor) * 4); if (doTrilinearRadio.isSelected()) { rgb2 = AlgorithmConvolver.getTrilinearC(floorPointIndex2, dx2, dy2, dz2, extents2, imageYBuffer); rgb2_short[0] = (short) (rgb2[0] & 0xff); rgb2_short[1] = (short) (rgb2[1] & 0xff); rgb2_short[2] = (short) (rgb2[2] & 0xff); } else { float[] tempValues = bSplineY.bSpline3DC(0, 0, 0, (float)tX2_floor, (float)tY2_floor, (float)tZ2_floor); for ( int c = 0; c < 4; c++ ) { if (tempValues[c] > 255) { tempValues[c] = 255; } else if (tempValues[c] < 0) { tempValues[c] = 0; } } rgb2_short[0] = (short) (tempValues[1]); rgb2_short[1] = (short) (tempValues[2]); rgb2_short[2] = (short) (tempValues[3]); /* r2_float = splineAlgY_R.interpolatedValue(imageY_R_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (r2_float > 255) { r2_float = 255; } else if (r2_float < 0) { r2_float = 0; } g2_float = splineAlgY_G.interpolatedValue(imageY_G_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (g2_float > 255) { g2_float = 255; } else if (g2_float < 0) { g2_float = 0; } b2_float = splineAlgY_B.interpolatedValue(imageY_B_coeff, tX2_floor, tY2_floor, tZ2_floor, extents2[0], extents2[1], extents2[2], 3); if (b2_float > 255) { b2_float = 255; } else if (b2_float < 0) { b2_float = 0; } rgb2_short[0] = (short) (r2_float); rgb2_short[1] = (short) (g2_float); rgb2_short[2] = (short) (b2_float); */ } } byte r, g, b; if (diff1 < diff2) { r = (byte) rgb1_short[0]; g = (byte) rgb1_short[1]; b = (byte) rgb1_short[2]; } else { r = (byte) rgb2_short[0]; g = (byte) rgb2_short[1]; b = (byte) rgb2_short[2]; } // alpha resultBuffer[index] = (byte) 255; // r index = index + 1; resultBuffer[index] = r; // g index = index + 1; resultBuffer[index] = g; // b index = index + 1; resultBuffer[index] = b; index = index + 1; } } } } outputTextArea.append("\n"); try { resultImage.importData(0, resultBuffer, true); } catch (final IOException error) { System.out.println("IO exception"); error.printStackTrace(); return; } final FileInfoImageXML[] fileInfoBases = new FileInfoImageXML[resultImage.getExtents()[2]]; for (int i = 0; i < fileInfoBases.length; i++) { fileInfoBases[i] = new FileInfoImageXML(resultImage.getImageName(), null, FileUtility.XML); fileInfoBases[i].setEndianess(imageY.getFileInfo()[0].getEndianess()); fileInfoBases[i].setUnitsOfMeasure(imageY.getFileInfo()[0].getUnitsOfMeasure()); fileInfoBases[i].setResolutions(resultImageResols); fileInfoBases[i].setExtents(resultImage.getExtents()); fileInfoBases[i].setImageOrientation(imageY.getFileInfo()[0].getImageOrientation()); fileInfoBases[i].setAxisOrientation(imageY.getFileInfo()[0].getAxisOrientation()); fileInfoBases[i].setOrigin(imageY.getFileInfo()[0].getOrigin()); fileInfoBases[i].setPixelPadValue(imageY.getFileInfo()[0].getPixelPadValue()); fileInfoBases[i].setPhotometric(imageY.getFileInfo()[0].getPhotometric()); fileInfoBases[i].setDataType(ModelStorageBase.ARGB); fileInfoBases[i].setFileDirectory(imageY.getFileInfo()[0].getFileDirectory()); } resultImage.setFileInfo(fileInfoBases); resultImage.calcMinMax(); if (imageX != null) { imageX.disposeLocal(); imageX = null; } if (vjfX != null) { vjfX.close(); } // create red and green channels image createRedAndGreenChannelsImages(); if (imageY != null) { imageY.disposeLocal(); imageY = null; } if (vjfY != null) { vjfY.close(); } final long endTime = System.currentTimeMillis(); final long diffTime = endTime - begTime; final float seconds = ((float) diffTime) / 1000; outputTextArea.append("** Algorithm took " + seconds + " seconds \n"); setCompleted(true); } /** * creates additional red channels and green channels images */ private void createRedAndGreenChannelsImages() { outputTextArea.append("creating red and green channel images..." + "\n"); outputTextArea.append("\n"); TransMatrix xfrm = new TransMatrix(4); xfrm.MakeIdentity(); int interp = 0; // trilinear interp float oXres = imageXRegistered.getResolutions(0)[0]; float oYres = imageXRegistered.getResolutions(0)[1]; float oZres = imageXRegistered.getResolutions(0)[2] * (imageXRegistered.getExtents()[2] / 512f); int oXdim = 512; int oYdim = 512; int oZdim = 512; int[] units = new int[imageXRegistered.getUnitsOfMeasure().length]; for (int i = 0; i < units.length; i++) { units[i] = imageXRegistered.getUnitsOfMeasure(i); } boolean doVOI = false; boolean doClip = true; boolean doPad = false; boolean doRotateCenter = true; Vector3f center = imageXRegistered.getImageCentermm(false); float fillValue = 0.0f; boolean doUpdateOrigin = true; boolean isSATransform = false; algoTrans = new AlgorithmTransform(imageXRegistered, xfrm, interp, oXres, oYres, oZres, oXdim, oYdim, oZdim, units, doVOI, doClip, doPad, doRotateCenter, center); algoTrans.setFillValue(fillValue); algoTrans.setUpdateOriginFlag(doUpdateOrigin); algoTrans.setUseScannerAnatomical(isSATransform); algoTrans.run(); imageXRegisteredTransformed = algoTrans.getTransformedImage(); imageXRegisteredTransformed.calcMinMax(); // now we can dispose of imageXRegisterd if (imageXRegistered != null) { imageXRegistered.disposeLocal(); imageXRegistered = null; } final int[] extents = {512, 512, 512}; redChannelsImage = new ModelImage(ModelStorageBase.ARGB, extents, "redChannelsImage-Rxreg-Ry-Rcomp"); final float[] redChannelsImageResols = new float[3]; redChannelsImageResols[0] = imageYRes[0]; redChannelsImageResols[1] = imageYRes[1]; redChannelsImageResols[2] = imageYRes[2] * imageY.getExtents()[2] / 512; for (int i = 0; i < redChannelsImage.getExtents()[2]; i++) { redChannelsImage.setResolutions(i, redChannelsImageResols); } final byte[] redChannelsBuffer = new byte[512 * 512 * 512 * 4]; greenChannelsImage = new ModelImage(ModelStorageBase.ARGB, extents, "greenChannelsImage-Gxreg-Gy-Gcomp"); final float[] greenChannelsImageResols = new float[3]; greenChannelsImageResols[0] = imageYRes[0]; greenChannelsImageResols[1] = imageYRes[1]; greenChannelsImageResols[2] = imageYRes[2] * imageY.getExtents()[2] / 512; for (int i = 0; i < greenChannelsImage.getExtents()[2]; i++) { greenChannelsImage.setResolutions(i, greenChannelsImageResols); } final byte[] greenChannelsBuffer = new byte[512 * 512 * 512 * 4]; byte imageXRegisteredTransformedByteR, imageYTransformedByteR, compImageByteR, imageXRegisteredTransformedByteG, imageYTransformedByteG, compImageByteG; int a, r, g, b; for (int i = 0; i < redChannelsBuffer.length; i = i + 4) { a = i; r = i + 1; g = i + 2; b = i + 3; // imageYTransformedByteR = imageYTransformed.getByte(r); compImageByteR = resultImage.getByte(r); imageXRegisteredTransformedByteR = imageXRegisteredTransformed.getByte(r); // imageYTransformedByteG = imageYTransformed.getByte(g); compImageByteG = resultImage.getByte(g); imageXRegisteredTransformedByteG = imageXRegisteredTransformed.getByte(g); // alpha redChannelsBuffer[a] = (byte) 255; // channel 1 redChannelsBuffer[r] = imageXRegisteredTransformedByteR; // channel 2 // redChannelsBuffer[g] = imageYTransformedByteR; // channel 3 redChannelsBuffer[b] = compImageByteR; // alpha greenChannelsBuffer[a] = (byte) 255; // channel 1 greenChannelsBuffer[r] = imageXRegisteredTransformedByteG; // channel 2 // greenChannelsBuffer[g] = imageYTransformedByteG; // channel 3 greenChannelsBuffer[b] = compImageByteG; } // now we can save result image and then dispose it and dispose of imageXRegisteredTransformed if (imageXRegisteredTransformed != null) { imageXRegisteredTransformed.disposeLocal(); imageXRegisteredTransformed = null; } final float[] orig = imageXOrig; // SAVE THE RESULT IMAGE String resultImageFileName = "combinedImage"; String processString, interpString, rescaleString, bgString; if (doSqRtRadio.isSelected()) { processString = "_sqrRt"; } else { processString = "_avg"; } if (doTrilinearRadio.isSelected()) { interpString = "_trilinear"; } else { interpString = "_bspline"; } if (doRescaleRadio.isSelected()) { rescaleString = "_rescale"; } else { rescaleString = "_norescale"; } if (ignoreBGRadio.isSelected()) { bgString = "_ignoreBG"; } else { bgString = "_includeBG"; } FileIO fileIO = new FileIO(); fileIO.setQuiet(true); FileWriteOptions opts = new FileWriteOptions(true); opts.setFileType(FileUtility.ICS); opts.setFileDirectory(dir); resultImageFileName = resultImageFileName + processString + interpString + rescaleString + bgString; opts.setFileName(resultImageFileName + ".ics"); opts.setBeginSlice(0); opts.setEndSlice(511); opts.setOptionsSet(true); fileIO.writeImage(resultImage, opts); outputTextArea.append("saving combined result image as: \n"); outputTextArea.append(dir + resultImageFileName + ".ics" + "\n"); outputTextArea.append("\n"); if(createMirroredImg) { ModelImage clonedResultImage = (ModelImage)resultImage.clone(); AlgorithmFlip flipAlgo = new AlgorithmFlip(clonedResultImage, AlgorithmFlip.Y_AXIS, AlgorithmFlip.IMAGE, false); flipAlgo.run(); opts = new FileWriteOptions(true); opts.setFileType(FileUtility.ICS); opts.setFileDirectory(dir); resultImageFileName = resultImageFileName + processString + interpString + rescaleString + bgString + "_MIRRORED"; opts.setFileName(resultImageFileName + ".ics"); opts.setBeginSlice(0); opts.setEndSlice(511); opts.setOptionsSet(true); fileIO.writeImage(clonedResultImage, opts); outputTextArea.append("saving mirrored result image as: \n"); outputTextArea.append(dir + resultImageFileName + ".ics" + "\n"); outputTextArea.append("\n"); if (clonedResultImage != null) { clonedResultImage.disposeLocal(); clonedResultImage = null; } flipAlgo.finalize(); flipAlgo = null; } if (resultImage != null) { resultImage.disposeLocal(); resultImage = null; } xfrm = new TransMatrix(4); xfrm.MakeIdentity(); interp = 0; // trilinear interp oXres = imageY.getResolutions(0)[0]; oYres = imageY.getResolutions(0)[1]; oZres = imageY.getResolutions(0)[2] * (imageY.getExtents()[2] / 512f); oXdim = 512; oYdim = 512; oZdim = 512; units = new int[imageY.getUnitsOfMeasure().length]; for (int i = 0; i < units.length; i++) { units[i] = imageY.getUnitsOfMeasure(i); } doVOI = false; doClip = true; doPad = false; doRotateCenter = true; center = imageY.getImageCentermm(false); fillValue = 0.0f; doUpdateOrigin = true; isSATransform = false; // imageYTransform algoTrans = new AlgorithmTransform(imageY, xfrm, interp, oXres, oYres, oZres, oXdim, oYdim, oZdim, units, doVOI, doClip, doPad, doRotateCenter, center); algoTrans.setFillValue(fillValue); algoTrans.setUpdateOriginFlag(doUpdateOrigin); algoTrans.setUseScannerAnatomical(isSATransform); algoTrans.run(); imageYTransformed = algoTrans.getTransformedImage(); // new ViewJFrameImage(imageYTransformed); // now we can dispose of imageY if (imageY != null) { imageY.disposeLocal(); imageY = null; } for (int i = 0; i < redChannelsBuffer.length; i = i + 4) { a = i; r = i + 1; g = i + 2; b = i + 3; imageYTransformedByteR = imageYTransformed.getByte(r); imageYTransformedByteG = imageYTransformed.getByte(g); // alpha // redChannelsBuffer[a] = (byte)255; // channel 1 // redChannelsBuffer[r] = imageXRegisteredTransformedByteR; // channel 2 redChannelsBuffer[g] = imageYTransformedByteR; // channel 3 // redChannelsBuffer[b] = compImageByteR; // alpha // greenChannelsBuffer[a] = (byte)255; // channel 1 // greenChannelsBuffer[r] = imageXRegisteredTransformedByteG; // channel 2 greenChannelsBuffer[g] = imageYTransformedByteG; // channel 3 // greenChannelsBuffer[b] = compImageByteG; } // now we can dispose of imageYTransformed if (imageYTransformed != null) { imageYTransformed.disposeLocal(); imageYTransformed = null; } try { redChannelsImage.importData(0, redChannelsBuffer, true); greenChannelsImage.importData(0, greenChannelsBuffer, true); } catch (final IOException error) { System.out.println("IO exception"); error.printStackTrace(); // setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); return; } FileInfoImageXML[] fileInfoBases = new FileInfoImageXML[redChannelsImage.getExtents()[2]]; for (int i = 0; i < fileInfoBases.length; i++) { fileInfoBases[i] = new FileInfoImageXML(redChannelsImage.getImageName(), null, FileUtility.XML); fileInfoBases[i].setEndianess(imageYEnd); fileInfoBases[i].setUnitsOfMeasure(units); fileInfoBases[i].setResolutions(redChannelsImageResols); fileInfoBases[i].setExtents(redChannelsImage.getExtents()); fileInfoBases[i].setOrigin(orig); fileInfoBases[i].setDataType(ModelStorageBase.ARGB); fileInfoBases[i].setFileDirectory(dir); } redChannelsImage.setFileInfo(fileInfoBases); redChannelsImage.calcMinMax(); final String redImageFileName = redChannelsImage.getImageName(); opts = new FileWriteOptions(true); opts.setFileType(FileUtility.ICS); opts.setFileDirectory(dir); opts.setFileName(redChannelsImage.getImageName() + ".ics"); opts.setBeginSlice(0); opts.setEndSlice(511); opts.setOptionsSet(true); fileIO.writeImage(redChannelsImage, opts); outputTextArea.append("saving red channels image as: \n"); outputTextArea.append(dir + redImageFileName + ".ics" + "\n"); outputTextArea.append("\n"); if (redChannelsImage != null) { redChannelsImage.disposeLocal(); redChannelsImage = null; } fileInfoBases = new FileInfoImageXML[greenChannelsImage.getExtents()[2]]; for (int i = 0; i < fileInfoBases.length; i++) { fileInfoBases[i] = new FileInfoImageXML(greenChannelsImage.getImageName(), null, FileUtility.XML); fileInfoBases[i].setEndianess(imageYEnd); fileInfoBases[i].setUnitsOfMeasure(units); fileInfoBases[i].setResolutions(redChannelsImageResols); fileInfoBases[i].setExtents(greenChannelsImage.getExtents()); fileInfoBases[i].setOrigin(orig); fileInfoBases[i].setDataType(ModelStorageBase.ARGB); fileInfoBases[i].setFileDirectory(dir); } greenChannelsImage.setFileInfo(fileInfoBases); greenChannelsImage.calcMinMax(); final String greenImageFileName = greenChannelsImage.getImageName(); opts = new FileWriteOptions(true); opts.setFileType(FileUtility.ICS); opts.setFileDirectory(dir); opts.setFileName(greenChannelsImage.getImageName() + ".ics"); opts.setBeginSlice(0); opts.setEndSlice(511); opts.setOptionsSet(true); fileIO.writeImage(greenChannelsImage, opts); outputTextArea.append("saving green channels image as: \n"); outputTextArea.append(dir + greenImageFileName + ".ics" + "\n"); outputTextArea.append("\n"); if (greenChannelsImage != null) { greenChannelsImage.disposeLocal(); greenChannelsImage = null; } } /** * This legacy code returns all active vois for a given source image. PlugIns should explicitly identify VOIs they * would like to process using AlgorithmVOIProps, because the user may have already added other VOIs to srcImage, or * VOIs may be created by the algorithm in an unexpected way. This plugin relied on <code>AlgorithmVOIProp</code>'s * getActiveVOIs() code, so that code has been moved into this plugin. * * Use of this method is discouraged, as shown by the old documentation for this method: not for use. should be * moved to a better location. does NOT clone the VOIs that it find to be active, and inserts into a new * ViewVOIVector. if no VOIs are active, the ViewVOIVector returned is <code>null</code>. * * @return All the active VOIs for a given srcImage. */ private ViewVOIVector getActiveVOIs(final ModelImage srcImage) { ViewVOIVector voiList; voiList = new ViewVOIVector(); int i; try { for (i = 0; i < srcImage.getVOIs().size(); i++) { if (srcImage.getVOIs().VOIAt(i).isActive()) { // voi at i is the active voi voiList.addElement(srcImage.getVOIs().VOIAt(i)); } } } catch (final ArrayIndexOutOfBoundsException indexException) { // got to the end of list and never found an active VOI. // return an empty VOI list. return new ViewVOIVector(); } return voiList; } /** * calculates slop based on 4 data points * * @param Y1 * @param X1 * @param Y2 * @param X2 * @return */ private float calculateSlope(final float Y1, final float X1, final float Y2, final float X2) { float slope = 0; final float Y = Y2 - Y1; final float X = X2 - X1; if (X == 0) { slope = 0; } else { slope = Y / X; } return slope; } /** * calculates b-intercept * * @param Y1 * @param X1 * @param slope * @return */ private float calculateB(final float Y1, final float X1, final float slope) { float b = 0; final float mx = X1 * slope; b = Y1 - mx; return b; } /** * gets new value based on slope and b-intercept * * @param X * @param slope * @param b * @return */ private float getNewValue(final float X, final float slope, final float b) { float Y = 0; final float mx = slope * X; Y = mx + b; return Y; } }
[ "[email protected]@ba61647d-9d00-f842-95cd-605cb4296b96" ]
[email protected]@ba61647d-9d00-f842-95cd-605cb4296b96
3a7a972e2e2e55a98fb33bf6b3200466f25848af
123fd25b3875893466abd20061cb36a12bdcaccb
/src/grade/GradeService.java
b64ef68872e6a6f4122f21cc723ce4df6eb92bb7
[]
no_license
selss2/test2
95755f8c09329d291c9a2afd16717da3481fb394
2b2efefaf9d9dabcf083300e469b667711ba97d3
refs/heads/master
2021-01-16T20:42:38.000184
2016-07-26T08:38:35
2016-07-26T08:38:35
63,741,676
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
package grade; import java.util.List; public interface GradeService { // 총 7개의 기본 패턴이 존재하더라 // exeU public int insert(GradeBean grade); public void update(GradeBean grade); public String delete(String del); // exeQ public List<GradeBean> list(); public List<GradeBean> findById(String id); public GradeBean findBySeq(String seq); public int count(String examDate); // 점수입력받는 메소드 public void score(String[] strArr); }
4f64a810cc047c208c340ecd910fdbca6ab54f34
a95c979c4b5a446e02f80997442f39c055d629a4
/app/src/main/java/jigneshkt/test/com/testproject/presentation/ui/flightschedule/FlightScheduleView.java
2eb7ba39678667b9165d39af5707c3c21b56290f
[]
no_license
JigneshKT/FlightSchedule
dba4facd034a892adc27373558ab17b9cc905553
13902f834d51b0bef944a5ef48ae35b3b46acd9f
refs/heads/master
2020-05-03T20:45:18.581558
2019-04-03T07:21:33
2019-04-03T07:21:33
178,809,873
0
0
null
null
null
null
UTF-8
Java
false
false
660
java
package jigneshkt.test.com.testproject.presentation.ui.flightschedule; import java.util.ArrayList; import jigneshkt.test.com.testproject.base.BaseActivityView; import jigneshkt.test.com.testproject.domain.model.FlightSchedule; public interface FlightScheduleView extends BaseActivityView { void setArrivalAirportName(String name); void setDepartureAirportName(String name); void updateFlightSchedule(); void onFlightScheduleSuccess(ArrayList<FlightSchedule> flightScheduleArrayList); void onFlightScheduleFailure(); void onFlightNotFound(); void onFlightNoMoreFound(); void showLoading(); void removeLoading(); }
136bd8428d0aaaa2e96308f464506476537f94a2
cc79942d4d23a88d60a25ca15de553cccbfe505d
/src/gui/AccueilChefController.java
3105470a13e3fec4ebe8db3804205085fd64e090
[]
no_license
khalilVer/ProjetJava
9b520329d87a5134834384d4b344e3a598a1faad
791a2eff65a9c5af112b1d7005f17fc4ae24270f
refs/heads/master
2020-05-24T18:52:59.254881
2019-05-19T00:57:37
2019-05-19T00:57:37
187,419,046
0
0
null
null
null
null
UTF-8
Java
false
false
5,311
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 gui; import Controller.ChauffeurController; import Controller.TacheController; import Controller.VoyageController; import entities.Chauffeur; import entities.Tache; import entities.Voyage; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * FXML Controller class * * @author Khalil */ public class AccueilChefController implements Initializable { @FXML private Label username; @FXML private Button btnOverview; @FXML private Button btnSettings; @FXML private Button btnTarif; @FXML private Button btnSignout; @FXML private Pane pnlCustomer; @FXML private Pane pnlOrders; @FXML private Pane pnlMenus; @FXML private Pane pnlOverview; @FXML private VBox pnItems; ObservableList<String> AllTache = FXCollections.observableArrayList(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { pnItems.getChildren().clear(); AllTache.clear(); List<Tache> listTache = null; TacheController ac = new TacheController(); VoyageController vc = new VoyageController(); ChauffeurController cc = new ChauffeurController(); listTache = ac.getAllTaches(); int i = 1; for (Tache tache : listTache) { Voyage v= vc.getVoyageById(tache.getId_voyage()); Chauffeur ch = cc.getChauffeurById(tache.getId_chauffeur()); HBox h1 = new HBox(); Label espace = new Label(" "); Label label3 = new Label(String.valueOf(i)); i++; label3.setPrefWidth(70); Label label = new Label(v.getDestination_depart()); label.setPrefWidth(120); Label label2 = new Label(v.getDestination_arrive()); label2.setPrefWidth(80); Label label4 = new Label(String.valueOf(v.getHeure_depart())); label4.setPrefWidth(150); Label label5 = new Label(String.valueOf(v.getHeure_arrive())); label5.setPrefWidth(150); Button delete = new Button("Supprimer"); delete.setOnAction((event) -> { ac.deleteTache(tache); pnItems.getChildren().remove(h1); }); Button update = new Button("Modifier"); update.setOnAction((event) -> { try { FXMLLoader Loder = new FXMLLoader(); Loder.setLocation(getClass().getResource("UpdateTache.fxml")); Loder.load(); UpdateTacheController display = Loder.getController(); System.out.println(tache.getId_voyage()); System.out.println(tache.getId_chauffeur()); display.getVoyageAndChauffeur(tache.getId_voyage(), tache.getId_chauffeur()); Parent AnchorPane = Loder.getRoot(); Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Scene scene = new Scene(AnchorPane); stage.setScene(scene); stage.showAndWait(); } catch (IOException ex) { } }); h1.getChildren().addAll(label3,label2,label,label4,label5,delete,update); pnItems.getChildren().add(h1); } } @FXML private void retour(ActionEvent event) throws IOException { FXMLLoader Loder = new FXMLLoader(); Loder.setLocation(getClass().getResource("AccueilAdmin.fxml")); Loder.load(); Parent AnchorPane = Loder.getRoot(); Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); Scene scene = new Scene(AnchorPane); stage.setScene(scene); stage.showAndWait(); } }
d2af8ac7dc0f690dc6a8225b7a55815752c03e3f
31aa8c70feec18e13be80329428e826a4854ca92
/src/main/java/org/example/web/dto/Book.java
750a005ce379cb04522060ea2e235398c2c5e6b2
[]
no_license
DmParshin/simple_mvc
3abc5be8128b4ed679f29b6b0ac9ddfaa2abfa4b
58d99d313dc9a2faeeaa241bc0ff7c499d25b300
refs/heads/master
2023-06-21T08:44:27.140463
2021-07-21T09:26:10
2021-07-21T09:26:10
387,329,163
0
0
null
null
null
null
UTF-8
Java
false
false
936
java
package org.example.web.dto; public class Book { private String id; private String author; private String title; private Integer size; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } @Override public String toString() { return "Book{" + "id=" + id + ", author='" + author + '\'' + ", title='" + title + '\'' + ", size=" + size + '}'; } }
818859ed8d098c10f568ef2374203c441da0b775
643f4173f934049ce825d9e3f097abb70587e4f2
/Assignment_2/src/main/java/com/cs499/a2/web/rest/UserResource.java
bc4d75535cd32187dbd5a480481d754db8706603
[]
no_license
chunhho/CS499-Cloud
22557536490a308021725b9d954ce0bcd6e3296d
c345d3170532dbe53f7507844e980c37e126cda5
refs/heads/master
2021-01-01T20:05:31.580524
2017-03-22T23:13:41
2017-03-22T23:13:41
78,381,515
0
0
null
null
null
null
UTF-8
Java
false
false
8,297
java
package com.cs499.a2.web.rest; import com.cs499.a2.config.Constants; import com.codahale.metrics.annotation.Timed; import com.cs499.a2.domain.User; import com.cs499.a2.repository.UserRepository; import com.cs499.a2.security.AuthoritiesConstants; import com.cs499.a2.service.MailService; import com.cs499.a2.service.UserService; import com.cs499.a2.service.dto.UserDTO; import com.cs499.a2.web.rest.vm.ManagedUserVM; import com.cs499.a2.web.rest.util.HeaderUtil; import com.cs499.a2.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; import io.swagger.annotations.ApiParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * REST controller for managing users. * * <p>This class accesses the User entity, and needs to fetch its collection of authorities.</p> * <p> * For a normal use-case, it would be better to have an eager relationship between User and Authority, * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join * which would be good for performance. * </p> * <p> * We use a View Model and a DTO for 3 reasons: * <ul> * <li>We want to keep a lazy association between the user and the authorities, because people will * quite often do relationships with the user, and we don't want them to get the authorities all * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users' * application because of this use-case.</li> * <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests, * but then all authorities come from the cache, so in fact it's much better than doing an outer join * (which will get lots of data from the database, for each HTTP call).</li> * <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li> * </ul> * <p>Another option would be to have a specific JPA entity graph to handle this case.</p> */ @RestController @RequestMapping("/api") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); private static final String ENTITY_NAME = "userManagement"; private final UserRepository userRepository; private final MailService mailService; private final UserService userService; public UserResource(UserRepository userRepository, MailService mailService, UserService userService) { this.userRepository = userRepository; this.mailService = mailService; this.userService = userService; } /** * POST /users : Creates a new user. * <p> * Creates a new user if the login and email are not already used, and sends an * mail with an activation link. * The user needs to be activated on creation. * </p> * * @param managedUserVM the user to create * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity createUser(@RequestBody ManagedUserVM managedUserVM) throws URISyntaxException { log.debug("REST request to save User : {}", managedUserVM); //Lowercase the user login before comparing with database if (userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()).isPresent()) { return ResponseEntity.badRequest() .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "userexists", "Login already in use")) .body(null); } else if (userRepository.findOneByEmail(managedUserVM.getEmail()).isPresent()) { return ResponseEntity.badRequest() .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "emailexists", "Email already in use")) .body(null); } else { User newUser = userService.createUser(managedUserVM); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) .headers(HeaderUtil.createAlert( "userManagement.created", newUser.getLogin())) .body(newUser); } } /** * PUT /users : Updates an existing User. * * @param managedUserVM the user to update * @return the ResponseEntity with status 200 (OK) and with body the updated user, * or with status 400 (Bad Request) if the login or email is already in use, * or with status 500 (Internal Server Error) if the user couldn't be updated */ @PutMapping("/users") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<UserDTO> updateUser(@RequestBody ManagedUserVM managedUserVM) { log.debug("REST request to update User : {}", managedUserVM); Optional<User> existingUser = userRepository.findOneByEmail(managedUserVM.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "emailexists", "E-mail already in use")).body(null); } existingUser = userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserVM.getId()))) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "userexists", "Login already in use")).body(null); } Optional<UserDTO> updatedUser = userService.updateUser(managedUserVM); return ResponseUtil.wrapOrNotFound(updatedUser, HeaderUtil.createAlert("userManagement.updated", managedUserVM.getLogin())); } /** * GET /users : get all users. * * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and with body all users * @throws URISyntaxException if the pagination headers couldn't be generated */ @GetMapping("/users") @Timed public ResponseEntity<List<UserDTO>> getAllUsers(@ApiParam Pageable pageable) throws URISyntaxException { final Page<UserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** * GET /users/:login : get the "login" user. * * @param login the login of the user to find * @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found) */ @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") @Timed public ResponseEntity<UserDTO> getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return ResponseUtil.wrapOrNotFound( userService.getUserWithAuthoritiesByLogin(login) .map(UserDTO::new)); } /** * DELETE /users/:login : delete the "login" User. * * @param login the login of the user to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<Void> deleteUser(@PathVariable String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); return ResponseEntity.ok().headers(HeaderUtil.createAlert( "userManagement.deleted", login)).build(); } }
[ "Gary Ho" ]
Gary Ho
1ab1c3234c91736e24381684c2cee3fc184455ac
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project38/src/test/java/org/gradle/test/performance38_4/Test38_385.java
20dc32a99c4dc57cc8ae372b3179059568e5c342
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
292
java
package org.gradle.test.performance38_4; import static org.junit.Assert.*; public class Test38_385 { private final Production38_385 production = new Production38_385("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
6b3ac37ed840a197e4ddaffe7ac2dc242e49ffef
793a6274ee39ac04114b12b92e46940454d1ffbd
/kouyudao/src/main/java/com/ludashen/dao/OrderDao.java
6a2195b346a0d0cfb7d2fef007191a4ea1565ac6
[]
no_license
ludagewudi/EnKouyu
6d76fad96ba2808a7930d2cd910abd1292b14c86
9f731bb194322a4ba44284a94915475ec576db51
refs/heads/master
2022-12-21T19:34:01.154467
2020-01-04T17:23:06
2020-01-04T17:23:06
231,801,531
0
0
null
2022-12-16T04:25:40
2020-01-04T17:24:55
Java
UTF-8
Java
false
false
1,055
java
package com.ludashen.dao; import com.ludashen.kouyumain.A; import com.ludashen.kouyumain.B; import com.ludashen.kouyumain.Order; import com.ludashen.kouyumain.Title; import org.apache.ibatis.annotations.One; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @description: * @author: 陆均琪 * @Data: 2019-12-25 23:41 */ public interface OrderDao { @Select("SELECT *FROM `order`;") @Results({ @Result(id = true, property = "id", column = "id"), //设置主键 @Result(property = "a", column = "a", javaType = A.class, one = @One(select = "com.ludashen.dao.ADao.findAid")), @Result(property = "b", column = "b", javaType = B.class, one = @One(select = "com.ludashen.dao.BDao.findBid")), @Result(property = "title", column = "title", javaType = Title.class, one = @One(select = "com.ludashen.dao.TitleDao.findTid")), }) public List<Order> findAll() throws Exception; }
c99bcb17e6b8a15a8d47d3770679f6440a32dbda
888ada06f371ebf09b845dcfa9e36e5dce9b50ba
/user-service-demo/src/main/java/com/laoxu/userservice/UserServiceDemoApplication.java
6b9093971e7d43fd99f19c8d2913f88b8e9ab923
[]
no_license
1051513344/spring-cloud-basic
6628c8378ebd4264117330ed4d345d1fa58740cb
effe07c3e8af57dab711350b0d40485333c2dc68
refs/heads/master
2022-12-04T04:30:10.167661
2020-08-18T09:40:25
2020-08-18T09:40:25
288,413,313
0
0
null
null
null
null
UTF-8
Java
false
false
460
java
package com.laoxu.userservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient // 开启EurekaClient功能 public class UserServiceDemoApplication { public static void main(String[] args) { SpringApplication.run(UserServiceDemoApplication.class, args); } }
98154cebfcee2764572f793b9957d5369ed88ddf
6a6d325ec45ddb249d484808f7014e8d438de549
/src/main/java/com/technobel2021/exercicehotel/model/ErrorDTO.java
3a938bf5e26b7c8b8f0f4e9612dd708e716891e8
[]
no_license
Shimshaker/ExerciceHotel-master
281c49c093c189dfb6230cfadf936a0f230cd230
7cfdf2e9497a5cb5e8845d861a0944710fbd45d4
refs/heads/master
2023-08-19T08:03:42.887456
2021-10-18T19:49:42
2021-10-18T19:49:42
418,435,527
0
0
null
null
null
null
UTF-8
Java
false
false
255
java
package com.technobel2021.exercicehotel.model; import java.time.Instant; public class ErrorDTO { private String message; private Instant timestamp = Instant.now(); public ErrorDTO(String message){ this.message = message; } }
d726d63345f9b9c3c9a65bfbfd54d8d8ec5b31a3
70c709f05c4c1acc92f8cb0cdfc701878859096a
/src/java/controller/themdmcontroller.java
f28dd51a2509d750f6df71f727b1698c2c0f8c2f
[]
no_license
tringuyenvn94/shop-quan-ao
0313c7e790889bd8922c1edc4dd509fed5ee1258
0c2322d6c1c0afe87693ffac34148f0316fb9cad
refs/heads/master
2020-05-18T16:40:55.106917
2013-06-28T06:06:43
2013-06-28T06:06:43
37,208,500
0
0
null
null
null
null
UTF-8
Java
false
false
3,026
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.SPDao; import dao.danhmucdao; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pojo.DanhMucPojo; import pojo.SPPojo; /** * * @author luctanbinh */ @WebServlet(name = "themdmcontroller", urlPatterns = {"/themdmcontroller"}) public class themdmcontroller extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String ten = request.getParameter("txtTen"); String xuatXu = request.getParameter("txtXuatXu"); danhmucdao.themDanhMuc(ten, xuatXu); RequestDispatcher view = request.getRequestDispatcher("themdm.jsp"); view.forward(request, response); } finally { } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
5ba9c6dfb191e831fb54706e3eb525c711e00cfc
f39a53e8c015be238c11d0cb3e6bc266a1b87929
/src/main/java/rs/ac/ftn/uns/sep/bank/model/Card.java
10213ea490b7809acb0a010afdad12494146d724
[]
no_license
vujasinovic/SEP-Bank
00751082ce4b1bd91ad014a4ec23ed7e9059995d
103ebb41d5e97fdc43e29a6f1ee8a15e701727f7
refs/heads/master
2022-01-30T12:16:01.808319
2020-01-31T13:07:39
2020-01-31T13:07:39
226,938,922
0
0
null
2022-01-07T00:19:18
2019-12-09T18:23:20
Java
UTF-8
Java
false
false
520
java
package rs.ac.ftn.uns.sep.bank.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.ToString; import javax.persistence.*; import java.sql.Date; @Entity @Data public class Card { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String pan; private Integer securityCode; private String holderName; private Date validTo; @ManyToOne @JoinColumn(name = "account", nullable = false) private Account account; }
457ce99a5e561993f4055bf679efd38d3e9b3386
45261cf94bc061c6c8025e47dec37c741789bbd7
/src/test/java/br/com/supero/books/BooksApplicationTests.java
3269da41612909e7ca77bbdbd6dee1d7c8a4dd4f
[]
no_license
YouFool/books-api
249b23a1783a71136690c6ea5dfdfea66d0eb8e9
f78a933761526a0c4ae78adf8c2a7948effb28d1
refs/heads/master
2021-01-08T16:17:29.910336
2020-02-23T02:11:46
2020-02-23T02:11:46
242,077,501
0
0
null
null
null
null
UTF-8
Java
false
false
221
java
package br.com.supero.books; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class BooksApplicationTests { @Test public void contextLoads() { } }
3cf2ef4f2adcd6c62473514b35f71c973663c4d7
9aeb261d951d7efd9511184ed38c9caa0a3cd59f
/src/main/java/com/android/tools/r8/naming/identifiernamestring/ClassForNameIdentifierNameStringLookupResult.java
5785d0a64b92ec3a845e61df207a0c10f9903c5c
[ "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
veryriskyrisk/r8
70bbac0692fcdd7106721015d82d898654ba404a
c4e4ae59b83f3d913c34c55e90000a4756cfe65f
refs/heads/master
2023-03-22T03:51:56.548646
2021-03-17T16:53:58
2021-03-18T09:00:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
795
java
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.naming.identifiernamestring; import com.android.tools.r8.graph.DexType; import com.android.tools.r8.utils.InternalOptions; public class ClassForNameIdentifierNameStringLookupResult extends IdentifierNameStringTypeLookupResult { ClassForNameIdentifierNameStringLookupResult(DexType type) { super(type); } @Override public boolean isTypeInitializedFromUse() { return true; } @Override public boolean isTypeCompatInstantiatedFromUse(InternalOptions options) { return options.isForceProguardCompatibilityEnabled(); } }
ed3d1ad8d40c8d4b0be835ae969ef1db5dff7db2
8393c0ca0974beba03c455110b04e4accce239bd
/src/main/java/com/example/spring/demospring/dependency/lookup/TypeSafetyDependencyLookupDemo.java
959fc6ff5f56cdaf22cb25eb8a1993751c6eb66e
[]
no_license
zll1020/demo-spring
4c414f9c069b06d64345159e0ec7c1788df07824
235f93321017cf22857e616c49d2664d16f0eefd
refs/heads/master
2022-11-18T11:57:41.354408
2020-07-17T10:19:20
2020-07-17T10:19:20
276,797,271
0
0
null
null
null
null
UTF-8
Java
false
false
3,499
java
package com.example.spring.demospring.dependency.lookup; import com.example.spring.demospring.domain.User; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * 类型安全 依赖查找示例 * * @author Lillian * @since */ public class TypeSafetyDependencyLookupDemo { public static void main(String[] args) { // 创建 BeanFactory 容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); // 将当前类 TypeSafetyDependencyLookupDemo 作为配置类(Configuration Class) applicationContext.register(TypeSafetyDependencyLookupDemo.class); // 启动应用上下文 applicationContext.refresh(); // 演示 BeanFactory#getBean 方法的安全性 displayBeanFactoryGetBean(applicationContext); // 演示 ObjectFactory#getObject 方法的安全性 displayObjectFactoryGetObject(applicationContext); // 演示 ObjectProvider#getIfAvaiable 方法的安全性 displayObjectProviderIfAvailable(applicationContext); // 演示 ListableBeanFactory#getBeansOfType 方法的安全性 displayListableBeanFactoryGetBeansOfType(applicationContext); // 演示 ObjectProvider Stream 操作的安全性 displayObjectProviderStreamOps(applicationContext); // 关闭应用上下文 applicationContext.close(); } private static void displayObjectProviderStreamOps(AnnotationConfigApplicationContext applicationContext) { ObjectProvider<User> userObjectProvider = applicationContext.getBeanProvider(User.class); printBeansException("displayObjectProviderStreamOps", () -> userObjectProvider.forEach(System.out::println)); } private static void displayListableBeanFactoryGetBeansOfType(ListableBeanFactory beanFactory) { printBeansException("displayListableBeanFactoryGetBeansOfType", () -> beanFactory.getBeansOfType(User.class)); } private static void displayObjectProviderIfAvailable(AnnotationConfigApplicationContext applicationContext) { ObjectProvider<User> userObjectProvider = applicationContext.getBeanProvider(User.class); printBeansException("displayObjectProviderIfAvailable", () -> userObjectProvider.getIfAvailable()); } private static void displayObjectFactoryGetObject(AnnotationConfigApplicationContext applicationContext) { // ObjectProvider is ObjectFactory ObjectFactory<User> userObjectFactory = applicationContext.getBeanProvider(User.class); printBeansException("displayObjectFactoryGetObject", () -> userObjectFactory.getObject()); } public static void displayBeanFactoryGetBean(BeanFactory beanFactory) { printBeansException("displayBeanFactoryGetBean", () -> beanFactory.getBean(User.class)); } private static void printBeansException(String source, Runnable runnable) { System.err.println("=========================================="); System.err.println("Source from :" + source); try { runnable.run(); } catch (BeansException exception) { exception.printStackTrace(); } } }
c634b82daa1f87d1545001dc84593d7a8a835b40
120e613549a40dcc610f4a688a05291e32c3d424
/src/test/java/generator/ImprovedRecursionFifonacciGeneratorTest.java
d35f93b7c341e704ebb2fc6cf4995b8fc98f55a9
[]
no_license
vmelnychuk/java-fibonacci
5c89a7d4c1ae8944cf0269de34c1993a67bd52fc
b040a364ced7cb15f635e3f64ec4c6f005a94dd6
refs/heads/master
2021-01-09T21:53:45.209697
2015-10-06T13:11:26
2015-10-06T13:11:26
43,687,321
0
0
null
null
null
null
UTF-8
Java
false
false
1,739
java
package generator; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.math.BigInteger; import static org.junit.Assert.*; // http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html public class ImprovedRecursionFifonacciGeneratorTest { private FibonacciGenerator generator; @Before public void setUp() throws Exception { generator = new ImprovedRecursionFifonacciGenerator(); } @After public void tearDown() throws Exception { generator = null; } @Test public void testGeneratorWithInitialValues() throws Exception { BigInteger zero = generator.getNumber(0); assertEquals(BigInteger.ZERO, zero); BigInteger one = generator.getNumber(1); assertEquals(BigInteger.ONE, one); } @Test public void testGeneratorWithConfiguration() throws Exception { FibonacciGenerator generatorWithConfiguration = new ImprovedRecursionFifonacciGenerator( FibonacciConfiguration.ONE_BASE); assertEquals(1L, generatorWithConfiguration.getNumber(0)); assertEquals(1L, generatorWithConfiguration.getNumber(1)); } @Test public void testGetNumberWithFive() throws Exception { assertEquals(5L, generator.getNumber(5)); } @Test public void testGetNumberWithTwenty() throws Exception { assertEquals(6765L, generator.getNumber(20)); } @Test public void testGetNumberWithThirtyEight() throws Exception { assertEquals(39088169L, generator.getNumber(38)); } @Test public void testGetNumberWithMaxLongSize() throws Exception { assertEquals(7540113804746346429L, generator.getNumber(92)); } }
fb5c938490a281eda632f990ceeec3923f8dcda7
5cde8e269e98f5d348056e1b8e3d4cfedb33afc5
/src/main/java/com/sinovatech/search/orm/hibernate/SimpleHibernateDao.java
c52e9e8d6686bb88b47cfbe3ad9805dcbdcc29ea
[]
no_license
gyygit/searchH
82a075c1bd9925cf92fea5a7a865ec234501787c
0222000f79647402d5a01bb0dba361e6c3b2c9ec
refs/heads/master
2020-04-09T22:19:13.596057
2018-12-06T06:05:54
2018-12-06T06:05:54
160,625,271
0
0
null
null
null
null
UTF-8
Java
false
false
13,085
java
/** * Copyright (c) 2005-2010 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: SimpleHibernateDao.java 1205 2010-09-09 15:12:17Z calvinxiu $ */ package com.sinovatech.search.orm.hibernate; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.metadata.ClassMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import com.sinovatech.search.utils.reflection.ReflectionUtils; /** * 封装Hibernate原生API的DAO泛型基类. * * 可在Service层直接使用, 也可以扩展泛型DAO子类使用, 见两个构造函数的注释. 参考Spring2.5自带的Petlinc例子, * 取消了HibernateTemplate, 直接使用Hibernate原生API. * * @param <T> * DAO操作的对象类型 * @param <PK> * 主键类型 * * @author calvin */ @SuppressWarnings("unchecked") public class SimpleHibernateDao<T, PK extends Serializable> { protected Logger logger = LoggerFactory.getLogger(getClass()); protected SessionFactory sessionFactory; protected Class<T> entityClass; /** * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends * SimpleHibernateDao<User, Long> */ public SimpleHibernateDao() { this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass()); } /** * 用于用于省略Dao层, 在Service层直接使用通用SimpleHibernateDao的构造函数. 在构造函数中定义对象类型Class. * eg. SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User, * Long>(sessionFactory, User.class); */ public SimpleHibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) { this.sessionFactory = sessionFactory; this.entityClass = entityClass; } /** * 取得sessionFactory. */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * 采用@Autowired按类型注入SessionFactory, 当有多个SesionFactory的时候在子类重载本函数. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * 取得当前Session. */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * 保存新增或修改的对象. */ public void saveOrUpdate(final T entity) { Assert.notNull(entity, "entity不能为空"); getSession().saveOrUpdate(entity); logger.debug("save entity: {}", entity); } public void update(final T entity) { Assert.notNull(entity, "entity不能为空"); Object c = (T) getSession().merge(entity); getSession().update(c); logger.debug("update entity: {}", entity); } public void save(final T entity) { Assert.notNull(entity, "entity不能为空"); getSession().save(entity); logger.debug("saveObj entity: {}", entity); } public void saveAll(final List<T> list) { Assert.notNull(list); getSession().save(list); } /** * 删除对象. * * @param entity * 对象必须是session中的对象或含id属性的transient对象. */ public void delete(final T entity) { // Assert.notNull(entity, "entity不能为空"); if(entity != null){ getSession().delete(entity); logger.debug("delete entity: {}", entity); } } /** * 按id删除对象. */ public void delete(final PK id) { Assert.notNull(id, "id不能为空"); delete(get(id)); logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id); } /** * 按id获取对象. */ public T get(final PK id) { // 在此处做非空校验后,如为空返回NULL,节省service层面代码<br> // 如service之前在参数为空时抛出异常,现在可以在经过本方法后如果为返回值为NULL抛出异常 try { Assert.notNull(id, "id不能为空"); } catch (AssertionError e) { return null; } Object o = getSession().get(entityClass, id); return o == null ? null : (T) o; } /** * 按id列表获取对象列表. */ public List<T> get(final Collection<PK> ids) { return find(Restrictions.in(getIdName(), ids)); } /** * 获取全部对象. */ public List<T> getAll() { return find(); } /** * 获取全部对象, 支持按属性行序. */ public List<T> getAll(String orderByProperty, boolean isAsc) { Criteria c = createCriteria(); if (isAsc) { c.addOrder(Order.asc(orderByProperty)); } else { c.addOrder(Order.desc(orderByProperty)); } return c.list(); } /** * 按属性查找对象列表, 匹配方式为相等. */ public List<T> findBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName不能为空"); Criterion criterion = Restrictions.eq(propertyName, value); return find(criterion); } /** * 按属性查找唯一对象, 匹配方式为相等. */ public T findUniqueBy(final String propertyName, final Object value) { Assert.hasText(propertyName, "propertyName不能为空"); Criterion criterion = Restrictions.eq(propertyName, value); Object object = createCriteria(criterion).uniqueResult(); return object == null ? null : (T) object; } /** * 按HQL查询对象列表. * * @param values * 数量可变的参数,按顺序绑定. */ public <X> List<X> find(final String hql, final Object... values) { return createQuery(hql, values).list(); } /** * 按HQL查询对象列表. * * @param hql * 数量可变的参数,按顺序绑定. */ public List<T> find(final String hql) { Assert.hasText(hql, "queryString不能为空"); Query query = getSession().createQuery(hql); return query.list(); } /** * 按HQL查询对象列表. * * @param values * 命名参数,按名称绑定. */ public <X> List<X> find(final String hql, final Map<String, ?> values) { return createQuery(hql, values).list(); } /** * 按HQL查询唯一对象. * * @param values * 数量可变的参数,按顺序绑定. */ public <X> X findUnique(final String hql, final Object... values) { return (X) createQuery(hql, values).uniqueResult(); } /** * 按HQL查询唯一对象. * * @param values * 数量可变的参数,按顺序绑定. */ public <X> X findUnique(final String hql, final Map<String,?> values) { return (X) createQuery(hql, values).uniqueResult(); } /** * * 按HQL查询唯一对象. * * @param values * 命名参数,按名称绑定. */ public <X> X findUniqueSql(final String sql, final Map<String, ?> values) { return (X) createQuery(sql, values).uniqueResult(); } /** * 执行HQL进行批量修改/删除操作. * * @param values * 数量可变的参数,按顺序绑定. * @return 更新记录数. */ public int batchExecute(final String hql, final Object... values) { return createQuery(hql, values).executeUpdate(); } /** * 执行HQL进行批量修改/删除操作. * * @param values * 命名参数,按名称绑定. * @return 更新记录数. */ public int batchExecute(final String hql, final Map<String, ?> values) { return createQuery(hql, values).executeUpdate(); } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values * 数量可变的参数,按顺序绑定. */ public Query createQuery(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values * 命名参数,按名称绑定. */ public Query createQuery(final String queryString, final Map<String, ?> values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createQuery(queryString); if ((values != null) && (values.size() > 0)) { query.setProperties(values); } return query; } /** * 按Criteria查询对象列表. * * @param criterions * 数量可变的Criterion. */ public List<T> find(final Criterion... criterions) { return createCriteria(criterions).list(); } /** * 按Criteria查询唯一对象. * * @param criterions * 数量可变的Criterion. */ public T findUnique(final Criterion... criterions) { return (T) createCriteria(criterions).uniqueResult(); } /** * 根据Criterion条件创建Criteria. 与find()函数可进行更加灵活的操作. * * @param criterions * 数量可变的Criterion. */ public Criteria createCriteria(final Criterion... criterions) { Criteria criteria = getSession().createCriteria(entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } /** * 初始化对象. 使用load()方法得到的仅是对象Proxy, 在传到View层前需要进行初始化. 如果传入entity, * 则只初始化entity的直接属性,但不会初始化延迟加载的关联集合和属性. 如需初始化关联属性,需执行: * Hibernate.initialize(user.getRoles()),初始化User的直接属性和关联集合. * Hibernate.initialize(user.getDescription()),初始化User的直接属性和延迟加载的Description属性. */ public void initProxyObject(Object proxy) { Hibernate.initialize(proxy); } /** * Flush当前Session. */ public void flush() { getSession().flush(); } /** * 为Query添加distinct transformer. 预加载关联对象的HQL会引起主对象重复, 需要进行distinct处理. */ public Query distinct(Query query) { query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return query; } /** * 为Criteria添加distinct transformer. 预加载关联对象的HQL会引起主对象重复, 需要进行distinct处理. */ public Criteria distinct(Criteria criteria) { criteria .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); return criteria; } /** * 取得对象的主键名. */ public String getIdName() { ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass); return meta.getIdentifierPropertyName(); } /** * 判断对象的属性值在数据库内是否唯一. * * 在修改对象的情景下,如果属性新修改的值(value)等于属性原来的值(orgValue)则不作比较. */ public boolean isPropertyUnique(final String propertyName, final Object newValue, final Object oldValue) { if (newValue == null || newValue.equals(oldValue)) { return true; } Object object = findUniqueBy(propertyName, newValue); return (object == null); } /** * 合并不同Session中的持久对象<br> * * @author dzh * @date 20110106 * @param t 待合并的持久对象 * @return */ public Object merge(T t) { if (t == null) return null; return getSession().merge(t); } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values * 数量可变的参数,按顺序绑定. */ public Query createQueryForSql(final String queryString, final Object... values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createSQLQuery(queryString); if (values != null) { for (int i = 0; i < values.length; i++) { query.setParameter(i, values[i]); } } return query; } /** * 根据查询HQL与参数列表创建Query对象. 与find()函数可进行更加灵活的操作. * * @param values * 数量可变的参数,按顺序绑定. */ public Query createQueryForSql(final String queryString, final Map<String,?> values) { Assert.hasText(queryString, "queryString不能为空"); Query query = getSession().createSQLQuery(queryString); if ((values != null) && (values.size() > 0)) { query.setProperties(values); } return query; } }
e058e89932ee72ed24dab35e9d06797afc2fea28
695908e1b54f985602646e50a8880b47d0a6cc46
/src/main/java/com/enbiso/proj/jproject/domain/Task.java
f1af8fc78fee1f9299d4731c82d7c3e3658c5269
[]
no_license
aarimaz/jproject
d7182e1d48634e9161b03b60c176d7ae71644177
5aff7094ab170db9c5653331ab3abedb686f921f
refs/heads/master
2021-01-18T14:49:46.688980
2015-11-01T15:47:43
2015-11-01T15:47:43
44,820,299
0
1
null
2020-09-18T06:57:10
2015-10-23T15:06:01
Java
UTF-8
Java
false
false
4,160
java
package com.enbiso.proj.jproject.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A Task. */ @Entity @Table(name = "app_task_tab") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Task implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull @Column(name = "title", nullable = false) private String title; @ManyToOne private Iteration iteration; @ManyToOne private Person assignee; @ManyToOne private Person owner; @ManyToOne private TaskType type; @ManyToOne private TaskStatus status; @ManyToOne private TaskPriority priority; @ManyToOne private TaskImportance importance; @OneToMany(mappedBy = "parentTask") @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Task> subTasks = new HashSet<>(); @ManyToOne private Task parentTask; @OneToMany(mappedBy = "task") @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<TaskComment> comments = new HashSet<>(); @OneToMany(mappedBy = "task") @JsonIgnore @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<TaskLog> logs = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Iteration getIteration() { return iteration; } public void setIteration(Iteration iteration) { this.iteration = iteration; } public Person getAssignee() { return assignee; } public void setAssignee(Person person) { this.assignee = person; } public Person getOwner() { return owner; } public void setOwner(Person person) { this.owner = person; } public TaskType getType() { return type; } public void setType(TaskType taskType) { this.type = taskType; } public TaskStatus getStatus() { return status; } public void setStatus(TaskStatus taskStatus) { this.status = taskStatus; } public TaskPriority getPriority() { return priority; } public void setPriority(TaskPriority taskPriority) { this.priority = taskPriority; } public TaskImportance getImportance() { return importance; } public void setImportance(TaskImportance taskImportance) { this.importance = taskImportance; } public Set<Task> getSubTasks() { return subTasks; } public void setSubTasks(Set<Task> tasks) { this.subTasks = tasks; } public Task getParentTask() { return parentTask; } public void setParentTask(Task task) { this.parentTask = task; } public Set<TaskComment> getComments() { return comments; } public void setComments(Set<TaskComment> taskComments) { this.comments = taskComments; } public Set<TaskLog> getLogs() { return logs; } public void setLogs(Set<TaskLog> taskLogs) { this.logs = taskLogs; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Task task = (Task) o; if ( ! Objects.equals(id, task.id)) return false; return true; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "Task{" + "id=" + id + ", title='" + title + "'" + '}'; } }
3870def08925d76fcc946fb9c8993e32bc39da95
53204595f0ce28dfaa939114a7901d7ada033c26
/src/com/xclink/ch04/Arc.java
53985de6b3a77688c51000a5ee1301ad855ac4d8
[]
no_license
hongdk/beginner
0cfe0809f51df0dc6015442fc5ef5ab953d591af
c134bd7570f1c4841314eea49570dce48feceb42
refs/heads/master
2020-03-20T03:27:50.461046
2018-06-13T03:18:26
2018-06-13T03:18:26
137,147,105
0
0
null
null
null
null
ISO-8859-7
Java
false
false
89
java
package com.xclink.ch04; public class Arc { //ΚτΠΤ //·½·¨ }
[ "hongdk@ontheway" ]
hongdk@ontheway
b435677b487324b837e0b578fac9e3b688af39f7
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/transform/DeleteProvisionedConcurrencyConfigRequestMarshaller.java
bb0c2c0fcad080c75cab69cc68c56e2f4fe2275b
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379135
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
2023-09-13T23:35:28
2010-03-22T23:34:58
null
UTF-8
Java
false
false
2,535
java
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.lambda.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.lambda.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteProvisionedConcurrencyConfigRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteProvisionedConcurrencyConfigRequestMarshaller { private static final MarshallingInfo<String> FUNCTIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("FunctionName").build(); private static final MarshallingInfo<String> QUALIFIER_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("Qualifier").build(); private static final DeleteProvisionedConcurrencyConfigRequestMarshaller instance = new DeleteProvisionedConcurrencyConfigRequestMarshaller(); public static DeleteProvisionedConcurrencyConfigRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteProvisionedConcurrencyConfigRequest deleteProvisionedConcurrencyConfigRequest, ProtocolMarshaller protocolMarshaller) { if (deleteProvisionedConcurrencyConfigRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteProvisionedConcurrencyConfigRequest.getFunctionName(), FUNCTIONNAME_BINDING); protocolMarshaller.marshall(deleteProvisionedConcurrencyConfigRequest.getQualifier(), QUALIFIER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
[ "" ]
8e9b2c5457520e67028686f7475cccf8c51416e6
140c5dca031e3b49e47e4aa25d5cd87fdde1fcff
/Sokoban33/app/src/main/java/com/example/sokoban33/LevelItem.java
dedf0a5f4c42882b206d5ecea42ead92533ab20b
[]
no_license
danielhlousek/TAMZ---Sokoban
6620fda26e4a0e38d67e7c8203d2cbbe5eee02eb
9ed6bfd1c6f280305c99b14d5578b195e191a70c
refs/heads/master
2020-09-13T09:13:24.096109
2019-12-18T15:01:38
2019-12-18T15:01:38
222,721,383
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package com.example.sokoban33; public class LevelItem { int id; String name; public LevelItem(int id, String name) { this.id = id; this.name = name; } }
d38d0fe2e104d9cc0efc77ec8b2623907975359a
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/test/android/javatests/src/org/chromium/chrome/test/pagecontroller/controllers/notifications/DownloadNotificationController.java
248bd4504556a7b27893317e94f53521ee3fb393
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
Java
false
false
1,398
java
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.test.pagecontroller.controllers.notifications; import org.chromium.chrome.test.pagecontroller.controllers.PageController; import org.chromium.chrome.test.pagecontroller.utils.IUi2Locator; import org.chromium.chrome.test.pagecontroller.utils.Ui2Locators; /** * Download Permissions Dialog (download for offline viewing) Page Controller. */ public class DownloadNotificationController extends PageController { private static final IUi2Locator LOCATOR_DOWNLOAD_NOTIFICATION = Ui2Locators.withTextContaining("needs storage access to download files"); private static final IUi2Locator LOCATOR_CONTINUE = Ui2Locators.withAnyResEntry(android.R.id.button1); private static final DownloadNotificationController sInstance = new DownloadNotificationController(); private DownloadNotificationController() {} public static DownloadNotificationController getInstance() { return sInstance; } public void clickContinue() { mUtils.click(LOCATOR_CONTINUE); } @Override public DownloadNotificationController verifyActive() { mLocatorHelper.verifyOnScreen(LOCATOR_DOWNLOAD_NOTIFICATION); return this; } }
f113975aa6c40a3fda192e94ada97b8bc60503a4
8bfc0b8ec1646d813fa9908fae384df2b30b5deb
/glink-examples/src/main/java/com/github/tm/glink/examples/query/RangeQueryExample.java
4bbfafb8af2c522bd5168b526485cf3c2b32189e
[]
no_license
liyingben/glink
a001a2b5e6f8fdf1657c0ea6bd66e5f6975a587d
b4a918724ae338b21ef1d3944c25b2c969e4f92f
refs/heads/master
2023-02-22T05:36:45.776626
2021-01-21T04:00:33
2021-01-21T04:00:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,442
java
package com.github.tm.glink.examples.query; import com.github.tm.glink.core.datastream.SpatialDataStream; import com.github.tm.glink.core.enums.GeometryType; import com.github.tm.glink.core.enums.TextFileSplitter; import com.github.tm.glink.core.format.Schema; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.io.WKTReader; import java.util.ArrayList; import java.util.List; /** * @author Yu Liebing */ public class RangeQueryExample { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); SpatialDataStream<Point> pointSpatialDataStream = new SpatialDataStream<>( env, 0, 1, TextFileSplitter.COMMA, GeometryType.POINT, true, Schema.types(Integer.class, String.class), "22.3,33.4,1,hangzhou", "22.4,33.6,2,wuhan"); // pointSpatialDataStream.print(); // create query polygons WKTReader wktReader = new WKTReader(); Polygon queryPolygon1 = (Polygon) wktReader.read("POLYGON ((10 10, 10 20, 20 20, 20 10, 10 10))"); List<Polygon> queryPolygons = new ArrayList<>(); queryPolygons.add(queryPolygon1); SpatialDataStream<Point> s = pointSpatialDataStream.index().rangeQuery(queryPolygons); s.print(); env.execute(); } }
cb1f7665976b30656fb78f3710271cbcae9f9c94
cfc94d0b10315a5dcd87f3df067b864174cc3334
/src/main/java/com/neelima/bookstore/security/UserDetailsImpl.java
91931c8b3a0dc034811dd59c52c6658aac53d35a
[]
no_license
rdongol10/BookRecords
c081e7a42e1b311e9f33b55a75a3dd29148f348c
599c288182a03fe1dfd74f461f4ebbff03545b66
refs/heads/master
2023-03-18T08:01:59.731688
2021-03-05T10:35:39
2021-03-05T10:35:39
339,123,301
0
0
null
null
null
null
UTF-8
Java
false
false
1,399
java
package com.neelima.bookstore.security; import java.util.Collection; import java.util.Collections; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.neelima.bookstore.model.User; public class UserDetailsImpl implements UserDetails { private static final long serialVersionUID = 1L; private User user; public UserDetailsImpl() { } public UserDetailsImpl(User user) { super(); this.user = user; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Collections.singleton(new SimpleGrantedAuthority("USER")); } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getLoginName(); } @Override public boolean isAccountNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isAccountNonLocked() { // TODO Auto-generated method stub return true; } @Override public boolean isCredentialsNonExpired() { // TODO Auto-generated method stub return true; } @Override public boolean isEnabled() { // TODO Auto-generated method stub return true; } }
17870a51ac9e9275aa399824ff83c8ab54ec90c2
f2447870521a478ae750ea545ac339731a2171fa
/src/main/java/com/zdy/aipc/Service/tradestragegy/DefaultTradeStrategy.java
aaacc8291f5a0731b6351c0c0cfaa9d2c6fb506a
[]
no_license
zdyGit/AIPCWithJava
acbaa5ff0872bc942af23d95dadd3086efd89c60
a444180d4f58d5a869fd62821b106370b9b0ec66
refs/heads/master
2022-09-10T08:59:17.857855
2020-04-24T03:22:23
2020-04-24T03:22:23
171,816,383
0
0
null
2022-09-01T23:24:22
2019-02-21T06:48:58
Java
UTF-8
Java
false
false
4,004
java
package com.zdy.aipc.service.tradestragegy; import com.alibaba.fastjson.JSONObject; import com.zdy.aipc.dao.ProductTradeParamDao; import com.zdy.aipc.dao.ProductTradeRecordDao; import com.zdy.aipc.domain.ProductInfo; import com.zdy.aipc.domain.ProductTradeParam; import com.zdy.aipc.domain.ProductTradeRecord; import com.zdy.aipc.service.ProductService; import com.zdy.aipc.utils.DateUtils; import com.zdy.aipc.utils.LogbackUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Date; @Service public class DefaultTradeStrategy implements ITradeStrategy { @Autowired private ProductTradeRecordDao productTradeRecordDao; @Autowired private ProductTradeParamDao productTradeParamDao; @Override public JSONObject getTradeInfo(ProductInfo product) throws Exception{ ProductTradeRecord productTradeRecord = productTradeRecordDao.getLatestProductTradeRecord(product.getProdCode()); ProductTradeParam productTradeParam = productTradeParamDao.getProductTradeParamByProdCode(product.getProdCode()); //最新净值 double latestPrice = product.getLatestPrice(); //上次交易净值 double lastPrice = productTradeRecord == null ? latestPrice:productTradeRecord.getTradeIndex(); //上次交易时间 String lastTradeDate = productTradeRecord == null?"20000101":productTradeRecord.getTradeDate(); // 基础交易金额 double baseTradeAmount = productTradeParam.getBaseTradeAmount(); //最大涨跌幅 double maxChangeRate = productTradeParam.getMaxChangeRate(); //最大交易间隔 int maxPeriodDays = productTradeParam.getMaxPeriodDays(); //基础交易标准 double baseTradePrice = productTradeParam.getBaseTradeIndex(); // 距上次交易涨幅 double priceChangeRate = (latestPrice - lastPrice)/lastPrice; SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); String now = df.format(new Date()); //距上次交易时间间隔 int daysDiff = DateUtils.getDaysDiff(lastTradeDate,now); JSONObject jres = new JSONObject(); double tradeAmount = 0 ; int tradeType; //跌幅超过最大涨跌幅,立即发起交易 if(priceChangeRate <0 && 0-priceChangeRate >= maxChangeRate){ tradeType = 1; tradeAmount = getTradeAmount(baseTradePrice,latestPrice,baseTradeAmount); } else{ //交易时间超过时间间隔,立即发起交易 if(daysDiff >= maxPeriodDays){ tradeType = 2; tradeAmount = getTradeAmount(baseTradePrice,latestPrice,baseTradeAmount); } else{ tradeType = 0; tradeAmount = 0; } } jres.put("prodCode",product.getProdCode()); jres.put("prodName",product.getProdName()); jres.put("changeRate",String.format("%.3f%%[%.3f%%]",priceChangeRate*100.0,(0-maxChangeRate)*100.0)); jres.put("daysDiff",String.format("%d days[%d days]",daysDiff,maxPeriodDays)); jres.put("tradeAmount",tradeAmount); jres.put("tradeType",tradeType); return jres ; } private double getTradeAmount(double baseTradePrice,double latestTradePrice,double baseTradeAmount){ double amount = 0; if(latestTradePrice >= baseTradePrice){ return baseTradeAmount; } double dropRate = (baseTradePrice - latestTradePrice) / baseTradePrice; double rDropRate = (dropRate*6+1); amount = baseTradeAmount * (rDropRate * rDropRate * rDropRate); LogbackUtils.info(String.format("%f,%f,%f,%f",baseTradePrice,baseTradeAmount,latestTradePrice,amount)); return amount; } }
46e2f014b4a6ff4739ac5967f740ccdeb7dfe177
75d42a46699563f5b85261bbd6149fb9b2dbe120
/src/EightHouses.java
2111bffbf108d3674c009718c9149bc312871380
[]
no_license
allaharsha/Leetcode
00c7bbbfe8898225fbc6dbb6140de3b4201297c3
930f03f5f93493e2e95024589d928dd8feb9ec5b
refs/heads/master
2021-07-08T19:51:28.313312
2021-03-10T16:05:33
2021-03-10T16:05:33
230,963,053
0
0
null
null
null
null
UTF-8
Java
false
false
714
java
public class EightHouses { static int[] eightHouses(int[] arr,int num) { int[] dup = new int[arr.length]; for(int i=0;i<num;i++) { for(int j=0;j<arr.length;j++) { if(j==0) { if(arr[j+1]==0) dup[j] = 0; else dup[j] = 1; } else if(j == arr.length -1) { if(arr[j-1]==0) dup[j] = 0; else dup[j] = 1; } else { if(arr[j-1]==arr[j+1]) dup[j] = 0; else dup[j] = 1; } } arr = dup; dup = new int[arr.length]; } return arr; } public static void main(String[] args) { int[] arr= {1,1,1,0,1,1,1,1}; int[] result = eightHouses(arr,2); for(int i=0;i<arr.length;i++) { System.out.print(result[i]+" "); } } }
f65778a6a2d1a7b5ee9db64fe7480d6b34645ff2
61e68bdd73fd516cfb2da36673c856139da2b6c7
/src/FileScanner.java
17b1bfe5ae89080c59abad681fcb42c8c9836301
[]
no_license
wittrura/MovieGuess
c81788013992d35c94b38b673afb0c69aeafb5d3
db749c771c587780d0ec6d72c46a9348ee2ffc7f
refs/heads/master
2021-08-17T00:53:12.435820
2017-11-20T15:53:23
2017-11-20T15:53:23
111,430,330
0
0
null
null
null
null
UTF-8
Java
false
false
1,270
java
import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; import java.io.File; import java.io.BufferedReader; public class FileScanner { public String[] getArrayOfMovies() { int lines = 0; try { File file = new File("/Users/ryanwittrup/Development/BUILD_AND_BURN/MovieGuesser/src/movies.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); while (reader.readLine() != null) lines++; reader.close(); } catch (Exception e) { System.out.println("File missing"); } try { File file = new File("/Users/ryanwittrup/Development/BUILD_AND_BURN/MovieGuesser/src/movies.txt"); Scanner scanner = new Scanner(file); String[] movies = new String[lines]; int i = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); movies[i] = line; i++; } return movies; } catch (Exception e) { System.out.println("File missing"); } String [] errArray = new String[0]; return errArray; } public static void main(String[] args) { } }
a92d9e9f034e6b57ab8f5ae752dd4dae1029917e
00a323257397dd7269842f5eadaec5fa0bf80898
/code/app/src/main/java/com/example/pontes_stefane_esig/myapplication/helpers/LoginHelper.java
11cfe7fb8ca627f3fbd8eb49ee7ad44603a2ae76
[]
no_license
fivaz/tasks
3cf691df3c3dec1c9ebb3419bf3cece424be1488
49f392fa1d84208aa4c77b69e2e0fd3de22b6a4d
refs/heads/master
2022-01-18T11:38:36.467449
2019-04-30T09:19:07
2019-04-30T09:19:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,691
java
package com.example.pontes_stefane_esig.myapplication.helpers; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import com.example.pontes_stefane_esig.myapplication.R; import com.example.pontes_stefane_esig.myapplication.models.User; public class LoginHelper { private final EditText inputEmail; private final EditText inputPassword; private User user; private Context context; public LoginHelper(AppCompatActivity context) { inputEmail = context.findViewById(R.id.et_login_email); inputPassword = context.findViewById(R.id.et_login_password); this.context = context; user = new User(); } public User getUser() { String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); user.setEmail(email); user.setPassword(password); return user; } public void setUser(User user) { inputEmail.setText(user.getEmail()); inputPassword.setText(user.getPassword()); this.user = user; } public boolean isOk() { String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); if (email.isEmpty()) { String message = context.getString(R.string.error_msg_email_required); inputEmail.setError(message); return false; } if (password.isEmpty()) { String message = context.getString(R.string.error_msg_password_required); inputPassword.setError(message); return false; } return true; } }
65a6d87a34d86d2487c532716f95dca8e93d6857
9d9405b973cac9ce688b3c39b278454fe6ea64d5
/sip-servlets-examples/shopping-demo-jsr309/business/src/main/java/org/jboss/mobicents/seam/actions/AfterShippingAction.java
58fc4db998c6e09cdaf7fca9278698174f3f3d1d
[]
no_license
stevesui/sipservlet
56a9115bfe699edc9b664f9e5a3c0172d15dc89e
dcd977dc191334b2b0aa143504836564b53fadcc
refs/heads/master
2021-01-13T01:36:33.185702
2014-07-31T17:43:26
2014-07-31T17:43:26
22,393,134
1
1
null
null
null
null
UTF-8
Java
false
false
7,752
java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.mobicents.seam.actions; import java.io.Serializable; import java.math.BigDecimal; import java.net.URLEncoder; import java.sql.Timestamp; import java.util.Map; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.media.mscontrol.MediaSession; import javax.media.mscontrol.join.Joinable.Direction; import javax.media.mscontrol.mediagroup.MediaGroup; import javax.media.mscontrol.networkconnection.NetworkConnection; import javax.media.mscontrol.networkconnection.SdpPortManager; import javax.servlet.sip.Address; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipURI; import javax.servlet.sip.URI; import org.jboss.mobicents.seam.listeners.DTMFListener; import org.jboss.mobicents.seam.model.Order; import org.jboss.mobicents.seam.util.MMSUtil; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.contexts.Contexts; import org.jboss.seam.log.Log; /** * An example of a Seam component used to handle a jBPM transition event. * * @author Amit Bhayani */ @Stateless @Name("afterShipping") public class AfterShippingAction implements AfterShipping, Serializable { @Logger private Log log; @In String customerfullname; @In String cutomerphone; @In BigDecimal amount; @In Long orderId; @In Order order; //jboss 5, compliant with sip spec 1.1 //@Resource(mappedName="java:comp/env/sip/shopping-demo/SipFactory") SipFactory sipFactory; //jboss 4 @Resource(mappedName="java:/sip/shopping-demo/SipFactory") SipFactory sipFactory; public void orderShipped() { log.info("*************** Fire ORDER_SHIPPED ***************************"); log.info("First Name = " + customerfullname); log.info("Phone = " + cutomerphone); log.info("orderId = " + orderId); log.info("order = " + order); Timestamp orderDate = order.getDeliveryDate(); try { SipApplicationSession sipApplicationSession = sipFactory.createApplicationSession(); String callerAddress = (String)Contexts.getApplicationContext().get("caller.sip"); String callerDomain = (String)Contexts.getApplicationContext().get("caller.domain"); SipURI fromURI = sipFactory.createSipURI(callerAddress, callerDomain); Address fromAddress = sipFactory.createAddress(fromURI); Address toAddress = sipFactory.createAddress(cutomerphone); SipServletRequest sipServletRequest = sipFactory.createRequest(sipApplicationSession, "INVITE", fromAddress, toAddress); // getting the contact address for the registered customer sip address String userContact= ((Map<String, String>)Contexts.getApplicationContext().get("registeredUsersMap")).get(cutomerphone); if(userContact != null && userContact.length() > 0) { // for customers using the registrar URI requestURI = sipFactory.createURI(userContact); sipServletRequest.setRequestURI(requestURI); } else { // for customers not using the registrar and registered directly their contact location URI requestURI = sipFactory.createURI(cutomerphone); sipServletRequest.setRequestURI(requestURI); } //TTS file creation StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("Welcome "); stringBuffer.append(customerfullname); stringBuffer.append(". This is a reminder call for your order number "); stringBuffer.append(orderId); stringBuffer.append(". The shipment will be at your doorstep on ."); stringBuffer.append(orderDate.getDate()); stringBuffer.append(" of "); String month = null; switch (orderDate.getMonth()) { case 0: month = "January"; break; case 1: month = "February"; break; case 2: month = "March"; break; case 3: month = "April"; break; case 4: month = "May"; break; case 5: month = "June"; break; case 6: month = "July"; break; case 7: month = "August"; break; case 8: month = "September"; break; case 9: month = "October"; break; case 10: month = "November"; break; case 11: month = "December"; break; default: break; } stringBuffer.append(month); stringBuffer.append(" "); stringBuffer.append(1900 + orderDate.getYear()); stringBuffer.append(" at "); stringBuffer.append(orderDate.getHours()); stringBuffer.append(" hour and "); stringBuffer.append(orderDate.getMinutes()); stringBuffer.append(" minute. Thank you. Bye."); sipServletRequest.getSession().setAttribute("speechUri", java.net.URI.create("data:" + URLEncoder.encode("ts("+ stringBuffer +")", "UTF-8"))); Thread.sleep(300); //Media Server Control Creation MediaSession mediaSession = MMSUtil.getMsControl().createMediaSession(); NetworkConnection conn = mediaSession .createNetworkConnection(NetworkConnection.BASIC); SdpPortManager sdpManag = conn.getSdpPortManager(); sdpManag.generateSdpOffer(); byte[] sdpOffer = null; int numTimes = 0; while(sdpOffer == null && numTimes<10) { sdpOffer = sdpManag.getMediaServerSessionDescription(); Thread.sleep(500); numTimes++; } sipServletRequest.setContentLength(sdpOffer.length); sipServletRequest.setContent(sdpOffer, "application/sdp"); MediaGroup mg = mediaSession.createMediaGroup(MediaGroup.PLAYER_SIGNALDETECTOR); sipServletRequest.getSession().setAttribute("mediaGroup", mg); sipServletRequest.getSession().setAttribute("mediaSession", mediaSession); sipServletRequest.getSession().setAttribute("customerName", customerfullname); sipServletRequest.getSession().setAttribute("customerPhone", cutomerphone); sipServletRequest.getSession().setAttribute("amountOrder", amount); sipServletRequest.getSession().setAttribute("orderId", orderId); sipServletRequest.getSession().setAttribute("connection", conn); sipServletRequest.getSession().setAttribute("shipping", true); sipServletRequest.send(); mg.getSignalDetector().addListener(new DTMFListener(mg, sipServletRequest.getSession(), MMSUtil.audioFilePath)); conn.join(Direction.DUPLEX, mg); } catch (UnsupportedOperationException uoe) { log.error("An unexpected exception occurred while trying to create the request for shipping call", uoe); } catch (Exception e) { log.error("An unexpected exception occurred while trying to create the request for shipping call", e); } } }