index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/LONGEST_SUBSEQUENCE_DIFFERENCE_ADJACENTS_ONE_SET_2.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LONGEST_SUBSEQUENCE_DIFFERENCE_ADJACENTS_ONE_SET_2{ static int f_gold ( int [ ] arr , int n ) { HashMap < Integer , Integer > um = new HashMap < Integer , Integer > ( ) ; int longLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = 0 ; if ( um . containsKey ( arr [ i ] - 1 ) && len < um . get ( arr [ i ] - 1 ) ) len = um . get ( arr [ i ] - 1 ) ; if ( um . containsKey ( arr [ i ] + 1 ) && len < um . get ( arr [ i ] + 1 ) ) len = um . get ( arr [ i ] + 1 ) ; um . put ( arr [ i ] , len + 1 ) ; if ( longLen < um . get ( arr [ i ] ) ) longLen = um . get ( arr [ i ] ) ; } return longLen ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{20,48,58}); param0.add(new int[]{-36,94,-20,-90,-80,88,46,-8,-36,22,70,-16,-48,-54,-82,38,10,-84,12,10,-14,50,12,-28,-64,-38,-84,-62,-56,32,-78,34,-34,48}); param0.add(new int[]{0,0,0}); param0.add(new int[]{50,28,14,52,92,30,30,27,66,77,39,42,28,84,63,55,18,34,57,45,81,38,23,31,9,35,25,39,30,5,28,7,42,42}); param0.add(new int[]{-96,-70,-64,-60,-56,-44,-40,-32,-30,-22,-10,14,26,28,28,38,58,78,80}); param0.add(new int[]{1,0,0,0,1,0,0,1,0,1}); param0.add(new int[]{8,19,30,37,44,46,49,50,51,57,65,67,70,70,76,83,91,92}); param0.add(new int[]{40,62,-6,88,58,66,-40,46,-32,80,22,-30,32,-74,20,-82,-58,-18,30,68,-2,38,-76,-58,22,-22,74}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1}); param0.add(new int[]{46,6,71,56,21,97,80,67,26,25,79,86,64,84,53,50,29,19,95,58,14,15,63,1,76,64,11,47,9,97,54,27}); List<Integer> param1 = new ArrayList<>(); param1.add(2); param1.add(29); param1.add(1); param1.add(22); param1.add(11); param1.add(8); param1.add(13); param1.add(20); param1.add(12); param1.add(17); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,100
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/MAXIMIZE_VOLUME_CUBOID_GIVEN_SUM_SIDES.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MAXIMIZE_VOLUME_CUBOID_GIVEN_SUM_SIDES{ static int f_gold ( int s ) { int maxvalue = 0 ; for ( int i = 1 ; i <= s - 2 ; i ++ ) { for ( int j = 1 ; j <= s - 1 ; j ++ ) { int k = s - i - j ; maxvalue = Math . max ( maxvalue , i * j * k ) ; } } return maxvalue ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(67); param0.add(48); param0.add(59); param0.add(22); param0.add(14); param0.add(66); param0.add(1); param0.add(75); param0.add(58); param0.add(78); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,101
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/PROGRAM_PRINT_SUM_GIVEN_NTH_TERM_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PROGRAM_PRINT_SUM_GIVEN_NTH_TERM_1{ static int f_gold ( long n ) { return ( int ) Math . pow ( n , 2 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Long> param0 = new ArrayList<>(); param0.add(42L); param0.add(40L); param0.add(67L); param0.add(73L); param0.add(18L); param0.add(16L); param0.add(74L); param0.add(33L); param0.add(92L); param0.add(22L); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,102
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/REARRANGE_POSITIVE_AND_NEGATIVE_NUMBERS_PUBLISH.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; class REARRANGE_POSITIVE_AND_NEGATIVE_NUMBERS_PUBLISH{ static void f_gold ( int arr [ ] , int n ) { int i = - 1 , temp = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] < 0 ) { i ++ ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } int pos = i + 1 , neg = 0 ; while ( pos < n && neg < pos && arr [ neg ] < 0 ) { temp = arr [ neg ] ; arr [ neg ] = arr [ pos ] ; arr [ pos ] = temp ; pos ++ ; neg += 2 ; } } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{5,5,6,7,8,10,13,15,15,27,27,29,29,29,29,31,33,33,36,38,38,39,42,47,47,51,51,51,52,53,55,56,57,64,66,66,67,68,70,72,74,78,86,88,94,97,97}); param0.add(new int[]{73,30,55,-5,15,64,-64,-74,-57,-73,-31,48}); param0.add(new int[]{0,0,0,1,1,1,1,1,1,1}); param0.add(new int[]{62,82,89,97,60,43,76,68,5,37,72,92,31}); param0.add(new int[]{-99,-89,-71,-60,-59,-54,-49,1,51}); param0.add(new int[]{1,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1}); param0.add(new int[]{2,7,17,22,24,25,26,28,29,33,34,38,43,49,51,52,54,59,63,70,71,75,82,88,91,91}); param0.add(new int[]{-51,99,-19,-16,5,77,48,18,-14,-37,89,4,-51,-29,-99,41,79,23,84,-38,-68}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{88,87,59}); List<Integer> param1 = new ArrayList<>(); param1.add(26); param1.add(8); param1.add(6); param1.add(7); param1.add(8); param1.add(21); param1.add(14); param1.add(10); param1.add(44); param1.add(1); List<int [ ]> filled_function_param0 = new ArrayList<>(); filled_function_param0.add(new int[]{5,5,6,7,8,10,13,15,15,27,27,29,29,29,29,31,33,33,36,38,38,39,42,47,47,51,51,51,52,53,55,56,57,64,66,66,67,68,70,72,74,78,86,88,94,97,97}); filled_function_param0.add(new int[]{73,30,55,-5,15,64,-64,-74,-57,-73,-31,48}); filled_function_param0.add(new int[]{0,0,0,1,1,1,1,1,1,1}); filled_function_param0.add(new int[]{62,82,89,97,60,43,76,68,5,37,72,92,31}); filled_function_param0.add(new int[]{-99,-89,-71,-60,-59,-54,-49,1,51}); filled_function_param0.add(new int[]{1,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1}); filled_function_param0.add(new int[]{2,7,17,22,24,25,26,28,29,33,34,38,43,49,51,52,54,59,63,70,71,75,82,88,91,91}); filled_function_param0.add(new int[]{-51,99,-19,-16,5,77,48,18,-14,-37,89,4,-51,-29,-99,41,79,23,84,-38,-68}); filled_function_param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); filled_function_param0.add(new int[]{88,87,59}); List<Integer> filled_function_param1 = new ArrayList<>(); filled_function_param1.add(26); filled_function_param1.add(8); filled_function_param1.add(6); filled_function_param1.add(7); filled_function_param1.add(8); filled_function_param1.add(21); filled_function_param1.add(14); filled_function_param1.add(10); filled_function_param1.add(44); filled_function_param1.add(1); for(int i = 0; i < param0.size(); ++i) { f_filled(filled_function_param0.get(i),filled_function_param1.get(i)); f_gold(param0.get(i),param1.get(i)); if(Arrays.equals(param0.get(i), filled_function_param0.get(i)) && param1.get(i) == filled_function_param1.get(i)) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,103
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/PARTITION_INTO_TWO_SUBARRAYS_OF_LENGTHS_K_AND_N_K_SUCH_THAT_THE_DIFFERENCE_OF_SUMS_IS_MAXIMUM.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PARTITION_INTO_TWO_SUBARRAYS_OF_LENGTHS_K_AND_N_K_SUCH_THAT_THE_DIFFERENCE_OF_SUMS_IS_MAXIMUM{ static int f_gold ( int arr [ ] , int N , int k ) { int M , S = 0 , S1 = 0 , max_difference = 0 ; for ( int i = 0 ; i < N ; i ++ ) S += arr [ i ] ; int temp ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } } M = Math . max ( k , N - k ) ; for ( int i = 0 ; i < M ; i ++ ) S1 += arr [ i ] ; max_difference = S1 - ( S - S1 ) ; return max_difference ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{1,5,5,9,9,19,22,24,27,33,39,39,40,41,42,43,44,45,48,52,52,53,53,55,55,56,57,57,60,60,61,62,65,66,67,70,71,72,73,77,78,79,84,87,89,91,95,98}); param0.add(new int[]{-22,-28}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{63,72,2,94,89,11,95,79,90,9,70,28,25,74,16,36,50,91,38,47,47,13,27,29,31,35}); param0.add(new int[]{-86,-78,-76,-76,-66,-62,-62,-38,-34,-32,-30,-26,-22,-4,-4,2,8,8,10,22,52,52,58,64,66,66,66,70,82,82}); param0.add(new int[]{0,0,0,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,0,1,1,0,0,0,1,0,0,1,0,0}); param0.add(new int[]{1,2,2,9,9,12,13,26,26,33,34,35,51,57,70,79,83}); param0.add(new int[]{98,-72,2,40,-20,-14,42,8,14,-58,-18,-70,-8,-66,-68,72,82,-38,-78,2,-66,-88,-34,52,12,84,72,-28,-34,60,-60,12,-28,-42,22,-66,88,-96}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{21,85,64,20,4,5,2}); List<Integer> param1 = new ArrayList<>(); param1.add(41); param1.add(1); param1.add(20); param1.add(23); param1.add(29); param1.add(42); param1.add(9); param1.add(28); param1.add(37); param1.add(5); List<Integer> param2 = new ArrayList<>(); param2.add(44); param2.add(1); param2.add(29); param2.add(16); param2.add(24); param2.add(32); param2.add(16); param2.add(28); param2.add(27); param2.add(6); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,104
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/GIVEN_A_SORTED_AND_ROTATED_ARRAY_FIND_IF_THERE_IS_A_PAIR_WITH_A_GIVEN_SUM_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class GIVEN_A_SORTED_AND_ROTATED_ARRAY_FIND_IF_THERE_IS_A_PAIR_WITH_A_GIVEN_SUM_1{ static int f_gold ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; int cnt = 0 ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) { cnt ++ ; if ( l == ( r - 1 + n ) % n ) { return cnt ; } l = ( l + 1 ) % n ; r = ( r - 1 + n ) % n ; } else if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return cnt ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{24,54}); param0.add(new int[]{68,-30,-18,-6,70,-40,86,98,-24,-48}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{84,44,40,45,2,41,52,17,50,41,5,52,48,90,13,55,34,55,94,44,41,2}); param0.add(new int[]{-92,-76,-74,-72,-68,-64,-58,-44,-44,-38,-26,-24,-20,-12,-8,-8,-4,10,10,10,20,20,26,26,28,50,52,54,60,66,72,74,78,78,78,80,86,88}); param0.add(new int[]{1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,1}); param0.add(new int[]{5,5,15,19,22,24,26,27,28,32,37,39,40,43,49,52,55,56,58,58,59,62,67,68,77,79,79,80,81,87,95,95,96,98,98}); param0.add(new int[]{-98,28,54,44,-98,-70,48,-98,56,4,-18,26,-8,-58,30,82,4,-38,42,64,-28}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{26,72,74,86,98,86,22,6,95,36,11,82,34,3,50,36,81,94,55,30,62,53,50,95,32,83,9,16}); List<Integer> param1 = new ArrayList<>(); param1.add(1); param1.add(8); param1.add(33); param1.add(18); param1.add(29); param1.add(19); param1.add(28); param1.add(17); param1.add(24); param1.add(19); List<Integer> param2 = new ArrayList<>(); param2.add(1); param2.add(8); param2.add(28); param2.add(16); param2.add(30); param2.add(10); param2.add(34); param2.add(14); param2.add(24); param2.add(16); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,105
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/PROGRAM_DISTANCE_TWO_POINTS_EARTH.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PROGRAM_DISTANCE_TWO_POINTS_EARTH{ public static double f_gold ( double lat1 , double lat2 , double lon1 , double lon2 ) { lon1 = Math . toRadians ( lon1 ) ; lon2 = Math . toRadians ( lon2 ) ; lat1 = Math . toRadians ( lat1 ) ; lat2 = Math . toRadians ( lat2 ) ; double dlon = lon2 - lon1 ; double dlat = lat2 - lat1 ; double a = Math . pow ( Math . sin ( dlat / 2 ) , 2 ) + Math . cos ( lat1 ) * Math . cos ( lat2 ) * Math . pow ( Math . sin ( dlon / 2 ) , 2 ) ; double c = 2 * Math . asin ( Math . sqrt ( a ) ) ; double r = 6371 ; return ( c * r ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Double> param0 = new ArrayList<>(); param0.add(6578.099266893886); param0.add(-9410.77783405426); param0.add(6641.858718352012); param0.add(-4142.202863100186); param0.add(4181.4508741498075); param0.add(-7745.655002884576); param0.add(7725.024650172891); param0.add(-5881.135770052704); param0.add(8322.143446980337); param0.add(-1772.9564288056765); List<Double> param1 = new ArrayList<>(); param1.add(482.6430542568438); param1.add(-1203.2861272633245); param1.add(3498.0959749989424); param1.add(-6286.669946106916); param1.add(3845.247033476332); param1.add(-8197.864556657836); param1.add(9295.96418476119); param1.add(-4802.015139707946); param1.add(1841.108539911126); param1.add(-8246.345733364455); List<Double> param2 = new ArrayList<>(); param2.add(1342.7044674704348); param2.add(-1947.91060583419); param2.add(228.4572635598181); param2.add(-2742.3608603803173); param2.add(4909.334120366857); param2.add(-3667.1524343381157); param2.add(588.3703338670609); param2.add(-35.713164290259726); param2.add(9049.321929418034); param2.add(-9716.057194373958); List<Double> param3 = new ArrayList<>(); param3.add(3416.2819128903197); param3.add(-781.7419983063755); param3.add(5599.787943215038); param3.add(-6584.987721971118); param3.add(5159.242793722949); param3.add(-8067.806767671396); param3.add(1220.0418662747136); param3.add(-4696.734461092275); param3.add(4470.7365519306095); param3.add(-8367.588380851601); for(int i = 0; i < param0.size(); ++i) { if(Math.abs(1 - (0.0000001 + Math.abs(f_gold(param0.get(i),param1.get(i),param2.get(i),param3.get(i))) )/ (Math.abs(f_filled(param0.get(i),param1.get(i),param2.get(i),param3.get(i))) + 0.0000001)) < 0.001) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,106
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_TOTAL_SET_BITS_IN_ALL_NUMBERS_FROM_1_TO_N.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_TOTAL_SET_BITS_IN_ALL_NUMBERS_FROM_1_TO_N{ static int f_gold ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = false ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { if ( k == true ) ans += 1 ; else ans += 0 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(90); param0.add(56); param0.add(43); param0.add(31); param0.add(77); param0.add(35); param0.add(43); param0.add(66); param0.add(15); param0.add(95); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,107
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_GIVEN_SENTENCE_GIVEN_SET_SIMPLE_GRAMMER_RULES.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_GIVEN_SENTENCE_GIVEN_SET_SIMPLE_GRAMMER_RULES{ static boolean f_gold ( char [ ] str ) { int len = str . length ; if ( str [ 0 ] < 'A' || str [ 0 ] > 'Z' ) return false ; if ( str [ len - 1 ] != '.' ) return false ; int prev_state = 0 , curr_state = 0 ; int index = 1 ; while ( index <= str . length ) { if ( str [ index ] >= 'A' && str [ index ] <= 'Z' ) curr_state = 0 ; else if ( str [ index ] == ' ' ) curr_state = 1 ; else if ( str [ index ] >= 'a' && str [ index ] <= 'z' ) curr_state = 2 ; else if ( str [ index ] == '.' ) curr_state = 3 ; if ( prev_state == curr_state && curr_state != 2 ) return false ; if ( prev_state == 2 && curr_state == 0 ) return false ; if ( curr_state == 3 && prev_state != 1 ) return ( index + 1 == str . length ) ; index ++ ; prev_state = curr_state ; } return false ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = Arrays.asList("I love cinema.", "The vertex is S.", "I am single.", "My name is KG.", "I lovE cinema.", "GeeksQuiz. is a quiz site.", "I love Geeksquiz and Geeksforgeeks.", " You are my friend.", "I love cinema", "Hello world !"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i).toCharArray()) == f_gold(param0.get(i).toCharArray())) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,108
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_EXIST_TWO_ELEMENTS_ARRAY_WHOSE_SUM_EQUAL_SUM_REST_ARRAY.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_EXIST_TWO_ELEMENTS_ARRAY_WHOSE_SUM_EQUAL_SUM_REST_ARRAY{ static boolean f_gold ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } if ( sum % 2 != 0 ) { return false ; } sum = sum / 2 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int val = sum - arr [ i ] ; if ( s . contains ( val ) && val == ( int ) s . toArray ( ) [ s . size ( ) - 1 ] ) { System . out . printf ( "Pair elements are %d and %d\n" , arr [ i ] , val ) ; return true ; } s . add ( arr [ i ] ) ; } return false ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{2, 11, 5, 1, 4, 7}); param0.add(new int[]{2, 4, 2, 1, 11, 15}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{69,6,24,30,75,37,61,76,19,18,90,9,49,24,58,97,18,85,24,93,71,98,92,59,75,75,75,70,35,58,50,1,64,66,33}); param0.add(new int[]{-94,-94,-92,-74,-60,-58,-56,-44,-42,-40,-28,-14,2,4,14,20,24,28,40,42,42,66,78,78,80,82,96}); param0.add(new int[]{1,0,1,1,0,0,1,1,0,0,1,1,0,1}); param0.add(new int[]{21,26,26,27,61,62,96}); param0.add(new int[]{-54,86,20,26}); param0.add(new int[]{0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{44,35,26,15,56,6,36,53,15,66,20,53,99,96,51,12,61,19,79,40,99,42,86,8,11,54,93,46,23,47,41,26,66,5,86,52,64,51,4,21,63,14,7,53,31,8,9,63}); List<Integer> param1 = new ArrayList<>(); param1.add(6); param1.add(6); param1.add(13); param1.add(18); param1.add(26); param1.add(10); param1.add(6); param1.add(3); param1.add(4); param1.add(31); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,109
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_POSSIBLE_TRANSFORM_ONE_STRING_ANOTHER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_POSSIBLE_TRANSFORM_ONE_STRING_ANOTHER{ static boolean f_gold ( String s1 , String s2 ) { int n = s1 . length ( ) ; int m = s2 . length ( ) ; boolean dp [ ] [ ] = new boolean [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { dp [ i ] [ j ] = false ; } } dp [ 0 ] [ 0 ] = true ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { for ( int j = 0 ; j <= s2 . length ( ) ; j ++ ) { if ( dp [ i ] [ j ] ) { if ( j < s2 . length ( ) && ( Character . toUpperCase ( s1 . charAt ( i ) ) == s2 . charAt ( j ) ) ) dp [ i + 1 ] [ j + 1 ] = true ; if ( ! Character . isUpperCase ( s1 . charAt ( i ) ) ) dp [ i + 1 ] [ j ] = true ; } } } return ( dp [ n ] [ m ] ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("daBcd"); param0.add("417514"); param0.add("010000"); param0.add("ZcKYguiMrdyn"); param0.add("argaju"); param0.add("1110101101"); param0.add("ySOCoSaygi"); param0.add("204"); param0.add("10011100000010"); param0.add("nMAioozPmY"); List<String> param1 = new ArrayList<>(); param1.add("ABC"); param1.add("9"); param1.add("1111011010"); param1.add("iz"); param1.add("RAJ"); param1.add("110101001"); param1.add("aRhxkYqh"); param1.add("6986871066"); param1.add("0"); param1.add("WZFdDKw"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,110
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/FIND_SUM_EVEN_FACTORS_NUMBER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_SUM_EVEN_FACTORS_NUMBER{ public static int f_gold ( int n ) { if ( n % 2 != 0 ) return 0 ; int res = 1 ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { int count = 0 , curr_sum = 1 ; int curr_term = 1 ; while ( n % i == 0 ) { count ++ ; n = n / i ; if ( i == 2 && count == 1 ) curr_sum = 0 ; curr_term *= i ; curr_sum += curr_term ; } res *= curr_sum ; } if ( n >= 2 ) res *= ( 1 + n ) ; return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(71); param0.add(78); param0.add(39); param0.add(36); param0.add(49); param0.add(17); param0.add(53); param0.add(66); param0.add(92); param0.add(71); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,111
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CALCULATE_AREA_TETRAHEDRON.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CALCULATE_AREA_TETRAHEDRON{ static double f_gold ( int side ) { double volume = ( Math . pow ( side , 3 ) / ( 6 * Math . sqrt ( 2 ) ) ) ; return volume ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(58); param0.add(56); param0.add(35); param0.add(99); param0.add(13); param0.add(45); param0.add(40); param0.add(92); param0.add(7); param0.add(13); for(int i = 0; i < param0.size(); ++i) { if(Math.abs(1 - (0.0000001 + Math.abs(f_gold(param0.get(i))) )/ (Math.abs(f_filled(param0.get(i))) + 0.0000001)) < 0.001) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,112
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/DYNAMIC_PROGRAMMING_SET_13_CUTTING_A_ROD.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class DYNAMIC_PROGRAMMING_SET_13_CUTTING_A_ROD{ static int f_gold ( int price [ ] , int n ) { int val [ ] = new int [ n + 1 ] ; val [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int max_val = Integer . MIN_VALUE ; for ( int j = 0 ; j < i ; j ++ ) max_val = Math . max ( max_val , price [ j ] + val [ i - j - 1 ] ) ; val [ i ] = max_val ; } return val [ n ] ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{5,7,15,16,18,22,22,30,34,35,37,41,42,42,43,47,49,52,53,55,58,60,62,62,62,65,65,67,69,73,73,73,75,78,83,84,86,90,91,91,93,94,96}); param0.add(new int[]{50,-30,-84,-2,-96,-54,-14,56,-48,70,38,-86,16,-48,66,34,36,40,40,36,-16,-92,30}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{79,33,54,12,53,9,29,45,85,20,6,52,8,26,43,42,17,54,8,70,5,71,1,81,42,59,42,63,8,86,29,16,72}); param0.add(new int[]{-78,-64,-38,-22,2,8,28,32,58,72,72,90}); param0.add(new int[]{1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0}); param0.add(new int[]{1,3,6,7,10,17,18,22,23,24,28,31,37,43,48,54,56,65,70,71,73,74,79,84,87,95,96}); param0.add(new int[]{-30,20,-72,-86,-8}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{96,99,20,87,17,13,45,65,33,13,59,77,35,79,20,51,69,71,55,37,23,35,82,70}); List<Integer> param1 = new ArrayList<>(); param1.add(37); param1.add(19); param1.add(29); param1.add(22); param1.add(11); param1.add(20); param1.add(21); param1.add(3); param1.add(21); param1.add(19); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,113
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/SQUARED_TRIANGULAR_NUMBER_SUM_CUBES.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class SQUARED_TRIANGULAR_NUMBER_SUM_CUBES{ static int f_gold ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n * n * n ; if ( sum == s ) return n ; } return - 1 ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(15); param0.add(36); param0.add(39); param0.add(43); param0.add(75); param0.add(49); param0.add(56); param0.add(14); param0.add(62); param0.add(97); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,114
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/FREQUENT_ELEMENT_ARRAY.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FREQUENT_ELEMENT_ARRAY{ static int f_gold ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int max_count = 1 , res = arr [ 0 ] ; int curr_count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) curr_count ++ ; else { if ( curr_count > max_count ) { max_count = curr_count ; res = arr [ i - 1 ] ; } curr_count = 1 ; } } if ( curr_count > max_count ) { max_count = curr_count ; res = arr [ n - 1 ] ; } return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{1,1,3,11,11,11,18,20,26,26,27,30,33,39,39,42,42,48,51,51,51,51,60,66,66,68,68,69,71,72,73,76,76,77,77,77,78,90,96}); param0.add(new int[]{46,-8,64,-46,-38,92,-14,-22,-32,48,72,96,30,66,94,36,42,-18,14,-74,80,96,-4}); param0.add(new int[]{0,0,0,0,0,0,1}); param0.add(new int[]{93,32,3,31,67,96,52,80,70,49,45,23,58,87,31,56,21,71,55,97}); param0.add(new int[]{-98,-96,-84,-82,-72,-64,-62,-56,-52,-52,-48,-46,-42,-36,-32,-30,-30,-18,-16,-10,-2,0,6,18,22,22,40,42,50,54,64,68,68,72,80,82,84,96}); param0.add(new int[]{1,1,0,0,0,1,0,0,0,1,0,0,0,1,1,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,0,1,1,1,0,0,1,0,1,1,0}); param0.add(new int[]{9,12,13,28,43,46,64,66,68,89,92}); param0.add(new int[]{22,-8,-56,68,-12,-26,-40,-46,-42,-80,4,-42,-72,-22,36,22,-94,48,96,80,-52,46,90,94,36,92,-12,-24,-60,-32,92,18,76,40,-32,6,-22,86,86,-88,38,50,32,78,-82,54,-40,18}); param0.add(new int[]{0,0,0,0,0,0,1,1,1}); param0.add(new int[]{81,74,32,41,85,65,81,74,40,64,97,4,61,43,54,96,62,2,97,86,80,25,9,31,16,29,4,63,76,41,5,95}); List<Integer> param1 = new ArrayList<>(); param1.add(25); param1.add(18); param1.add(6); param1.add(15); param1.add(20); param1.add(29); param1.add(6); param1.add(41); param1.add(4); param1.add(16); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,115
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/FIND_SUM_EVEN_INDEX_BINOMIAL_COEFFICIENTS_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_SUM_EVEN_INDEX_BINOMIAL_COEFFICIENTS_1{ static int f_gold ( int n ) { return ( 1 << ( n - 1 ) ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(56); param0.add(28); param0.add(4); param0.add(24); param0.add(72); param0.add(30); param0.add(48); param0.add(32); param0.add(13); param0.add(19); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,116
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/PYTHON_PROGRAM_FIND_PERIMETER_CIRCUMFERENCE_SQUARE_RECTANGLE_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PYTHON_PROGRAM_FIND_PERIMETER_CIRCUMFERENCE_SQUARE_RECTANGLE_1{ static int f_gold ( int l , int w ) { return ( 2 * ( l + w ) ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(58); param0.add(37); param0.add(56); param0.add(22); param0.add(77); param0.add(34); param0.add(74); param0.add(37); param0.add(21); param0.add(75); List<Integer> param1 = new ArrayList<>(); param1.add(39); param1.add(49); param1.add(52); param1.add(43); param1.add(12); param1.add(31); param1.add(54); param1.add(52); param1.add(37); param1.add(30); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,117
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/LONGEST_REPEATING_AND_NON_OVERLAPPING_SUBSTRING.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LONGEST_REPEATING_AND_NON_OVERLAPPING_SUBSTRING{ static String f_gold ( String str ) { int n = str . length ( ) ; int LCSRe [ ] [ ] = new int [ n + 1 ] [ n + 1 ] ; String res = "" ; int res_length = 0 ; int i , index = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { if ( str . charAt ( i - 1 ) == str . charAt ( j - 1 ) && LCSRe [ i - 1 ] [ j - 1 ] < ( j - i ) ) { LCSRe [ i ] [ j ] = LCSRe [ i - 1 ] [ j - 1 ] + 1 ; if ( LCSRe [ i ] [ j ] > res_length ) { res_length = LCSRe [ i ] [ j ] ; index = Math . max ( i , index ) ; } } else { LCSRe [ i ] [ j ] = 0 ; } } } if ( res_length > 0 ) { for ( i = index - res_length + 1 ; i <= index ; i ++ ) { res += str . charAt ( i - 1 ) ; } } return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("fbfHTjE"); param0.add("09285256323"); param0.add("0011000101110"); param0.add("ue JkVZTt"); param0.add("48387612426300"); param0.add("010"); param0.add("ddRrUz"); param0.add("1049162633793"); param0.add("100011"); param0.add("iJfadiVaQqv"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)).equals(f_gold(param0.get(i)))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,118
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/NUMBER_N_DIGIT_STEPPING_NUMBERS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class NUMBER_N_DIGIT_STEPPING_NUMBERS{ static long f_gold ( int n ) { int dp [ ] [ ] = new int [ n + 1 ] [ 10 ] ; if ( n == 1 ) return 10 ; for ( int j = 0 ; j <= 9 ; j ++ ) dp [ 1 ] [ j ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { if ( j == 0 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] ; else if ( j == 9 ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j + 1 ] ; } } long sum = 0 ; for ( int j = 1 ; j <= 9 ; j ++ ) sum += dp [ n ] [ j ] ; return sum ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(18); param0.add(66); param0.add(73); param0.add(70); param0.add(26); param0.add(41); param0.add(20); param0.add(25); param0.add(52); param0.add(13); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,119
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/PROGRAM_FIND_STRING_START_END_GEEKS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PROGRAM_FIND_STRING_START_END_GEEKS{ static boolean f_gold ( String str , String corner ) { int n = str . length ( ) ; int cl = corner . length ( ) ; if ( n < cl ) return false ; return ( str . substring ( 0 , cl ) . equals ( corner ) && str . substring ( n - cl , n ) . equals ( corner ) ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("geeksmanishgeeks"); param0.add("shreyadhatwalia"); param0.add("10000100"); param0.add("abaa"); param0.add("30645530"); param0.add("0000011011001"); param0.add("dkqEd"); param0.add("48694119324654"); param0.add("1101010010"); param0.add("Ks"); List<String> param1 = new ArrayList<>(); param1.add("geeks"); param1.add("abc"); param1.add("100"); param1.add("a"); param1.add("30"); param1.add("001"); param1.add("d"); param1.add("654"); param1.add("11"); param1.add("KsFLmngGGOmHKs"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,120
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/FIND_NUMBER_ENDLESS_POINTS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_NUMBER_ENDLESS_POINTS{ static int f_gold ( boolean input [ ] [ ] , int n ) { boolean row [ ] [ ] = new boolean [ n ] [ n ] ; boolean col [ ] [ ] = new boolean [ n ] [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { boolean isEndless = true ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( input [ i ] [ j ] == false ) isEndless = false ; col [ i ] [ j ] = isEndless ; } } for ( int i = 0 ; i < n ; i ++ ) { boolean isEndless = true ; for ( int j = n - 1 ; j >= 0 ; j -- ) { if ( input [ i ] [ j ] == false ) isEndless = false ; row [ i ] [ j ] = isEndless ; } } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 1 ; j < n ; j ++ ) if ( row [ i ] [ j ] && col [ i ] [ j ] ) ans ++ ; return ans ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<boolean [ ] [ ]> param0 = new ArrayList<>(); param0.add(new boolean[][]{new boolean[]{false,false,false,true},new boolean[]{false,true,true,true},new boolean[]{false,false,true,true},new boolean[]{true,true,true,true}}); param0.add(new boolean[][]{new boolean[]{true,false,true,true,true,true,false,false,false},new boolean[]{false,true,true,true,true,true,false,true,true},new boolean[]{false,true,false,true,false,true,true,true,false},new boolean[]{false,false,false,false,true,true,false,false,true},new boolean[]{true,true,true,true,false,true,true,false,false},new boolean[]{false,false,true,true,false,true,false,false,true},new boolean[]{true,true,false,false,false,true,true,false,true},new boolean[]{false,true,true,false,false,false,false,false,false},new boolean[]{true,false,false,false,true,true,false,false,true}}); param0.add(new boolean[][]{new boolean[]{false,false,false,true},new boolean[]{false,false,true,true},new boolean[]{false,false,false,true},new boolean[]{false,false,true,true}}); param0.add(new boolean[][]{new boolean[]{false,true,true,false,false,true,false,false,true,false,false,false,true,false,false,true,false,true,true,false,false,true,true,true,true,true,true,false,false,true,false,false,false,true,false,true,true,true,false},new boolean[]{false,true,true,true,false,false,true,false,true,true,true,true,true,false,true,false,false,true,false,true,true,true,true,false,false,true,false,true,true,false,true,false,true,false,false,false,true,true,false},new boolean[]{false,true,true,false,true,false,false,true,false,true,true,false,true,true,false,true,false,true,false,true,false,true,true,false,true,false,true,false,true,false,false,false,false,true,false,false,true,true,true},new boolean[]{false,false,false,true,false,true,true,true,true,false,true,true,true,false,false,false,false,true,false,false,false,true,true,false,true,true,false,true,false,false,false,false,false,true,true,true,false,false,false},new boolean[]{true,false,false,true,false,false,false,true,false,true,true,false,false,true,true,true,false,false,false,false,false,true,true,false,true,false,false,true,false,true,false,false,false,true,false,true,false,true,false},new boolean[]{false,true,true,false,false,true,false,true,false,true,false,true,true,true,true,true,false,true,false,false,false,true,true,true,false,false,false,false,true,true,true,false,true,false,true,true,false,true,true},new boolean[]{false,false,true,false,true,true,true,true,false,true,true,true,true,false,false,true,false,true,false,false,false,true,true,true,false,true,true,true,false,false,false,false,false,true,true,false,true,true,false},new boolean[]{false,true,false,false,true,false,false,false,true,false,true,true,true,false,true,true,false,false,false,true,true,true,false,true,false,false,true,false,true,false,false,true,false,true,true,false,true,false,true},new boolean[]{true,true,true,false,true,true,true,false,false,false,false,true,true,false,false,false,true,false,false,true,false,false,false,true,true,false,false,false,true,true,false,true,false,true,false,false,false,true,false},new boolean[]{false,false,true,false,true,true,true,false,true,false,false,false,true,false,true,false,true,false,false,false,false,true,false,false,true,false,true,false,false,true,false,true,true,false,true,false,false,false,false},new boolean[]{true,false,true,true,true,false,true,true,false,true,false,true,false,false,false,true,true,true,true,true,false,true,true,false,true,true,true,true,false,false,true,false,false,false,false,true,false,false,false},new boolean[]{false,true,true,false,true,false,true,true,true,true,false,false,false,false,true,false,true,true,true,false,true,false,false,true,true,true,true,false,false,true,false,false,true,false,false,true,false,true,true},new boolean[]{false,false,false,false,true,false,false,true,true,true,false,true,true,false,true,false,false,false,true,true,true,true,true,false,false,true,false,false,true,false,true,false,false,false,true,true,true,false,false},new boolean[]{false,true,false,true,false,true,true,true,false,false,true,true,true,false,false,true,true,false,true,true,false,true,false,true,true,false,false,true,false,false,true,false,false,true,true,false,false,false,true},new boolean[]{false,false,true,false,true,true,false,false,false,true,true,true,true,true,false,true,false,false,false,false,false,false,true,false,false,false,false,false,true,true,false,false,false,true,false,true,true,false,false},new boolean[]{false,true,false,true,true,true,true,false,false,false,true,true,false,true,true,false,false,true,false,true,true,true,true,true,false,true,false,true,true,true,false,false,true,true,false,false,false,false,false},new boolean[]{true,true,false,false,true,true,true,false,false,false,true,true,true,true,false,true,false,false,true,true,false,true,true,true,false,true,true,false,false,false,true,true,false,false,false,false,true,false,true},new boolean[]{false,false,false,true,false,false,true,false,true,true,false,true,true,true,false,true,false,false,true,true,false,false,true,false,false,true,false,false,false,true,false,false,false,true,false,false,false,false,false},new boolean[]{false,true,false,false,true,false,true,true,true,false,true,true,true,true,true,false,false,false,true,false,true,true,true,false,true,false,true,false,false,true,true,true,true,true,false,true,true,true,true},new boolean[]{true,false,true,false,true,true,false,false,false,true,true,false,true,true,true,true,true,false,false,true,false,true,false,true,true,true,true,true,false,false,true,true,false,true,false,true,false,false,false},new boolean[]{true,true,false,false,false,false,false,true,true,true,false,true,false,true,true,true,false,true,false,true,true,false,true,true,true,false,false,true,true,true,false,true,false,true,true,false,true,false,true},new boolean[]{false,false,false,false,true,true,true,false,false,true,true,true,false,false,true,true,true,false,true,false,false,true,false,false,true,false,true,true,true,true,false,true,true,false,false,true,false,true,true},new boolean[]{false,true,true,false,true,true,true,true,false,false,true,false,false,true,true,true,false,false,false,true,true,true,false,true,true,true,true,false,true,false,true,false,false,false,true,false,false,true,true},new boolean[]{true,false,false,false,false,true,true,false,false,true,false,false,true,true,false,false,true,true,true,false,true,true,false,false,true,false,true,false,false,true,true,true,true,true,false,false,true,true,true},new boolean[]{true,true,true,false,false,true,false,true,false,true,true,true,true,false,false,true,true,true,false,false,false,true,false,false,false,false,false,true,true,true,false,true,true,false,false,false,true,true,true},new boolean[]{true,false,true,true,true,false,false,true,true,false,false,false,true,true,false,true,false,true,true,true,false,false,false,true,false,false,true,true,true,false,true,false,false,true,true,true,false,false,true},new boolean[]{false,false,false,true,true,false,false,false,true,true,false,false,false,true,false,true,false,false,false,false,true,true,true,true,true,true,true,false,false,false,false,false,false,false,false,true,false,false,true},new boolean[]{false,false,false,true,false,false,false,true,false,false,true,false,false,true,false,true,true,false,true,true,true,true,true,true,false,false,false,true,true,true,true,false,false,false,false,false,true,true,true},new boolean[]{false,true,false,true,true,false,true,true,true,true,true,true,false,false,true,true,true,true,false,false,true,false,true,false,true,true,true,true,true,true,false,true,true,true,true,false,true,true,false},new boolean[]{true,false,false,true,false,true,true,true,true,false,false,true,false,false,false,true,true,true,false,false,true,false,false,false,false,true,false,true,true,false,false,true,false,false,true,true,true,true,true},new boolean[]{false,true,true,true,false,false,true,false,false,true,false,false,true,true,true,false,false,true,false,false,false,true,false,true,true,true,false,true,false,false,true,true,false,false,false,true,false,true,false},new boolean[]{false,false,true,false,true,false,false,false,false,true,false,false,false,true,true,false,false,true,false,false,true,false,true,false,true,false,false,false,true,true,false,true,false,false,false,true,false,true,true},new boolean[]{false,true,false,false,true,true,true,true,true,true,false,false,true,false,true,false,false,true,true,true,true,false,false,true,false,true,false,true,true,true,true,true,true,false,true,false,false,true,true},new boolean[]{false,false,false,true,true,true,false,false,false,false,true,true,false,true,false,false,true,false,false,false,true,true,true,true,false,true,false,true,true,true,false,true,true,true,false,false,false,false,false},new boolean[]{false,false,true,true,true,false,true,false,true,true,true,true,false,true,false,true,false,false,true,false,false,true,false,true,false,true,false,true,true,false,false,false,true,false,false,false,true,false,true},new boolean[]{false,false,false,false,true,true,false,true,false,true,false,true,true,true,false,false,false,true,false,false,true,false,false,false,false,false,true,false,true,true,true,false,false,true,true,true,true,true,false},new boolean[]{true,true,true,true,false,false,false,true,false,false,false,true,false,false,true,false,false,false,false,false,true,true,false,false,false,false,false,true,true,true,true,true,true,true,true,false,true,true,true},new boolean[]{true,false,false,true,true,false,true,false,false,false,true,false,true,false,false,false,false,true,true,false,false,false,true,false,false,true,true,true,false,true,true,false,false,false,false,true,false,false,false},new boolean[]{true,true,false,true,true,false,true,true,false,false,true,true,true,false,true,false,true,false,true,false,true,false,true,true,true,true,false,false,false,false,false,true,true,false,false,true,true,false,false}}); param0.add(new boolean[][]{new boolean[]{false,false,false,false,false,true,true,true,true},new boolean[]{false,false,false,false,true,true,true,true,true},new boolean[]{false,false,false,false,false,true,true,true,true},new boolean[]{false,false,false,false,false,true,true,true,true},new boolean[]{false,false,false,false,false,false,true,true,true},new boolean[]{true,true,true,true,true,true,true,true,true},new boolean[]{false,false,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,true,true,true,true},new boolean[]{false,false,false,false,false,false,true,true,true}}); param0.add(new boolean[][]{new boolean[]{false,true,true,true,true,false,false,true,false,false,false,true,true,false,true,false,false,false,false,true,true,true,true,false,false},new boolean[]{false,true,false,false,false,false,true,true,true,true,false,true,true,false,true,true,true,false,true,false,true,true,false,false,true},new boolean[]{true,false,false,false,true,false,false,true,true,false,true,false,true,true,false,false,true,false,true,true,true,false,false,true,true},new boolean[]{false,true,true,false,true,true,true,true,false,true,false,false,false,true,false,false,false,false,true,false,true,true,false,true,false},new boolean[]{true,true,true,false,true,true,false,false,true,true,false,false,false,true,true,false,true,false,false,true,true,false,false,true,false},new boolean[]{true,false,false,true,false,false,true,false,true,true,true,false,false,true,false,true,true,false,false,false,false,false,true,true,false},new boolean[]{true,false,false,false,false,false,false,false,true,false,true,false,true,false,false,false,true,true,true,true,false,true,false,false,false},new boolean[]{true,false,true,false,false,false,false,false,true,false,true,false,true,false,true,false,false,true,true,false,false,true,false,true,false},new boolean[]{true,true,true,false,true,true,true,false,false,false,true,true,false,true,true,false,true,true,false,false,false,true,false,true,false},new boolean[]{true,false,true,false,true,false,true,true,false,true,true,false,false,true,true,true,true,true,false,false,true,false,true,true,false},new boolean[]{true,false,false,false,true,true,false,false,true,false,false,false,true,true,false,true,false,false,true,true,false,false,false,false,true},new boolean[]{false,true,false,true,true,false,true,false,false,true,false,false,false,false,false,true,false,true,true,true,false,true,true,false,false},new boolean[]{true,false,false,true,true,false,false,true,false,true,false,false,false,true,false,false,true,true,false,true,true,true,true,true,false},new boolean[]{false,true,true,true,true,false,false,false,false,true,true,true,true,false,true,true,false,false,true,true,true,true,true,true,false},new boolean[]{true,false,true,false,false,true,false,true,true,true,true,false,true,true,false,true,false,true,true,false,true,true,true,false,true},new boolean[]{true,true,true,false,false,false,true,false,true,false,true,false,true,true,false,false,true,true,true,false,false,true,true,false,true},new boolean[]{false,false,true,true,true,false,false,false,true,true,false,true,true,true,false,true,false,true,true,false,false,false,false,false,false},new boolean[]{false,false,false,true,true,true,true,false,false,true,true,true,false,true,true,false,true,true,true,false,false,true,false,true,false},new boolean[]{false,false,true,false,false,true,false,true,false,false,false,false,true,false,false,false,false,true,false,true,false,false,true,false,false},new boolean[]{false,false,true,true,false,false,false,true,true,true,false,false,true,false,false,true,true,false,false,false,false,true,false,true,false},new boolean[]{true,false,false,false,false,true,false,true,false,false,false,false,true,false,true,false,false,true,true,true,false,false,false,true,true},new boolean[]{false,true,false,false,true,false,false,true,false,true,true,true,true,false,true,false,true,true,false,true,true,false,false,false,false},new boolean[]{true,false,true,true,false,true,true,true,true,true,true,false,false,true,true,true,false,false,false,true,false,true,true,false,false},new boolean[]{true,true,true,false,true,false,true,true,true,false,true,true,true,false,false,false,false,true,false,true,true,true,true,false,true},new boolean[]{true,true,true,true,false,true,false,false,false,true,false,false,true,false,true,false,true,true,false,false,false,true,false,false,true}}); param0.add(new boolean[][]{new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true,true,true},new boolean[]{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,true,true,true,true,true,true,true,true,true}}); param0.add(new boolean[][]{new boolean[]{true,false,true,false,false,false,true,true,false,true,false,true,true,true,false,false,false,false,true,false,true,false,false,true,false,false,true},new boolean[]{false,true,false,true,false,false,true,true,false,false,false,true,true,false,true,false,true,false,true,false,true,false,false,false,false,true,true},new boolean[]{true,false,true,true,true,false,false,true,true,true,true,true,true,true,true,false,false,false,true,false,true,true,false,false,true,false,true},new boolean[]{true,true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true,false,true,false,false,true,true,true,false,false,true},new boolean[]{true,false,true,false,false,true,true,false,false,true,true,true,false,false,false,true,false,true,false,true,true,true,true,true,true,false,false},new boolean[]{true,false,false,true,true,false,false,true,false,true,true,true,true,false,false,true,true,true,false,false,true,false,false,true,true,true,false},new boolean[]{true,false,true,true,true,true,false,true,false,false,false,true,true,false,true,true,false,true,true,false,true,false,false,false,false,false,false},new boolean[]{true,false,false,true,false,false,true,true,true,false,true,false,false,false,true,true,true,true,false,true,false,false,true,false,true,false,true},new boolean[]{false,true,false,true,false,true,true,true,false,true,true,false,false,false,true,false,false,false,false,true,true,false,true,false,true,false,true},new boolean[]{false,true,true,true,false,true,false,true,false,true,true,false,true,true,true,true,true,true,true,false,true,true,false,false,true,false,true},new boolean[]{false,true,false,false,true,true,false,false,false,false,true,true,false,false,true,false,false,true,true,true,true,false,false,true,false,false,true},new boolean[]{false,false,true,true,false,true,true,true,false,false,false,false,true,false,true,false,true,false,false,true,false,false,true,true,true,false,false},new boolean[]{true,true,false,false,true,true,false,false,true,true,true,false,false,true,true,false,false,false,true,false,false,false,true,false,false,false,true},new boolean[]{false,true,true,true,false,true,true,true,false,false,false,false,false,true,true,false,false,false,false,false,true,false,true,true,false,true,false},new boolean[]{true,true,true,true,true,true,true,true,true,false,true,true,true,true,false,false,false,false,false,true,false,false,false,false,false,false,true},new boolean[]{false,false,false,true,false,false,false,false,false,true,false,false,false,false,false,false,false,true,false,true,false,true,false,true,false,true,false},new boolean[]{true,true,false,true,true,true,true,true,true,false,false,true,true,false,true,true,false,false,false,false,false,true,true,false,false,false,false},new boolean[]{false,false,false,false,true,true,true,false,true,true,false,true,false,false,true,true,false,false,false,false,true,true,false,true,true,false,false},new boolean[]{true,false,true,true,false,true,false,false,false,false,false,false,false,false,true,false,true,true,false,true,true,true,true,false,false,false,true},new boolean[]{true,false,false,false,true,false,true,false,true,true,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true,false,true},new boolean[]{true,false,true,true,true,true,false,true,true,false,true,true,true,false,false,true,true,false,false,false,false,false,true,false,true,true,true},new boolean[]{true,true,false,false,false,true,false,true,true,true,true,false,true,true,true,true,true,true,false,false,false,false,true,true,false,false,false},new boolean[]{true,false,false,false,false,false,false,true,true,true,false,true,false,false,false,false,true,false,false,false,true,true,false,true,true,true,true},new boolean[]{false,true,true,true,true,false,false,false,true,true,false,true,false,false,false,true,false,false,true,true,true,false,false,false,true,true,true},new boolean[]{false,false,true,true,false,true,true,false,false,true,true,true,false,false,true,false,true,true,true,true,false,true,true,true,true,false,false},new boolean[]{true,true,false,true,false,true,false,true,true,false,false,true,false,false,true,true,false,false,true,true,false,true,true,true,true,false,false},new boolean[]{true,false,true,false,true,true,true,true,true,false,false,false,false,false,false,true,true,false,false,false,false,false,false,true,false,true,true}}); param0.add(new boolean[][]{new boolean[]{false,false,false,true},new boolean[]{false,true,true,true},new boolean[]{false,false,false,true},new boolean[]{false,true,true,true}}); param0.add(new boolean[][]{new boolean[]{true,true,false,false,true,true,true,true,true,false,true,true,false,true,true,false,false,false,false,false,true,false,true,false,true,true,false,true},new boolean[]{false,false,true,true,false,false,false,true,true,false,false,true,false,true,false,false,true,true,false,false,true,true,true,true,false,true,false,false},new boolean[]{true,true,false,false,false,true,false,true,true,true,false,true,false,true,false,false,true,true,false,true,true,false,true,true,false,false,false,false},new boolean[]{true,false,true,false,true,false,true,false,false,true,true,true,true,true,true,false,true,false,false,true,false,false,false,true,false,true,false,true},new boolean[]{true,true,true,true,false,false,false,true,true,false,true,false,true,false,true,true,true,true,false,false,true,true,true,true,false,true,true,true},new boolean[]{true,false,true,true,true,true,true,true,false,true,false,false,false,false,false,true,false,true,true,false,true,true,false,true,false,false,false,true},new boolean[]{true,true,false,false,false,true,true,false,true,false,true,false,false,false,true,true,true,false,false,true,true,false,true,false,false,false,true,false},new boolean[]{false,true,true,true,true,false,false,true,false,false,false,false,false,false,false,false,true,false,true,false,false,true,false,true,true,true,false,true},new boolean[]{true,false,true,false,false,false,true,false,true,true,true,true,false,true,true,true,false,false,true,true,false,false,false,false,true,false,false,false},new boolean[]{false,false,true,true,false,true,false,false,true,true,true,true,false,false,true,false,false,true,true,false,true,false,true,true,false,true,true,true},new boolean[]{true,false,true,true,true,true,false,true,true,true,false,true,true,false,false,false,true,false,true,true,true,true,true,false,false,false,false,false},new boolean[]{false,false,false,false,true,false,true,true,true,false,false,false,false,true,false,false,true,true,false,true,true,true,true,true,true,true,true,false},new boolean[]{false,false,false,true,true,false,false,true,false,false,false,false,true,true,true,true,false,false,true,true,true,true,true,true,true,true,false,false},new boolean[]{false,true,true,true,true,true,true,true,true,true,true,true,true,true,false,true,true,true,true,true,false,false,false,false,true,false,true,false},new boolean[]{false,true,false,false,false,true,true,false,false,true,false,true,false,true,false,true,true,false,true,true,false,false,true,false,true,false,false,true},new boolean[]{true,true,false,true,true,true,true,true,false,false,false,true,true,false,false,true,true,true,false,false,false,false,true,false,true,true,false,true},new boolean[]{true,false,true,false,false,false,true,true,false,true,true,false,true,true,true,true,true,true,true,false,false,false,false,false,false,false,false,true},new boolean[]{true,false,true,false,true,false,false,false,true,true,true,false,true,true,true,false,false,false,false,false,true,true,true,true,true,true,false,false},new boolean[]{true,false,true,false,true,true,true,false,false,false,false,false,false,false,true,true,false,false,false,true,true,true,true,false,true,false,false,false},new boolean[]{false,false,true,false,true,false,true,false,true,true,false,true,true,true,false,false,true,true,true,false,false,false,false,false,false,false,false,false},new boolean[]{true,false,true,false,true,true,true,true,false,true,true,false,false,true,true,false,true,false,true,true,true,true,true,true,false,false,true,false},new boolean[]{true,false,false,true,false,false,false,false,false,true,true,false,false,true,false,false,true,false,true,false,true,false,true,true,false,true,false,false},new boolean[]{false,true,true,true,true,true,true,false,false,true,true,false,true,false,true,true,true,false,true,true,true,true,false,true,false,false,false,false},new boolean[]{true,true,false,false,true,true,false,false,true,false,false,false,true,false,false,false,false,false,true,true,true,false,true,true,false,false,true,false},new boolean[]{false,true,true,true,true,true,true,true,false,true,false,false,false,true,true,false,false,true,true,false,false,true,false,true,true,false,true,false},new boolean[]{true,true,true,true,true,true,true,true,false,true,false,false,true,false,true,false,true,true,true,true,false,false,true,false,true,false,true,true},new boolean[]{true,false,true,true,true,false,false,true,false,true,true,false,false,false,true,true,true,false,false,true,false,false,true,true,true,true,false,true},new boolean[]{false,true,true,false,false,false,true,true,true,true,false,true,true,false,false,false,true,true,true,true,false,true,true,true,true,false,true,false}}); List<Integer> param1 = new ArrayList<>(); param1.add(2); param1.add(4); param1.add(2); param1.add(30); param1.add(7); param1.add(13); param1.add(19); param1.add(15); param1.add(3); param1.add(18); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,121
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_STRING_FOLLOWS_ANBN_PATTERN_NOT.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_STRING_FOLLOWS_ANBN_PATTERN_NOT{ public static boolean f_gold ( String s ) { int l = s . length ( ) ; if ( l % 2 == 1 ) { return false ; } int i = 0 ; int j = l - 1 ; while ( i < j ) { if ( s . charAt ( i ) != 'a' || s . charAt ( j ) != 'b' ) { return false ; } i ++ ; j -- ; } return true ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("ba"); param0.add("aabb"); param0.add("abab"); param0.add("aaabb"); param0.add("aabbb"); param0.add("abaabbaa"); param0.add("abaababb"); param0.add("bbaa"); param0.add("11001000"); param0.add("ZWXv te"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,122
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/MAXIMUM_SUBARRAY_SUM_USING_PREFIX_SUM.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MAXIMUM_SUBARRAY_SUM_USING_PREFIX_SUM{ static int f_gold ( int arr [ ] , int n ) { int min_prefix_sum = 0 ; int res = Integer . MIN_VALUE ; int prefix_sum [ ] = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { res = Math . max ( res , prefix_sum [ i ] - min_prefix_sum ) ; min_prefix_sum = Math . min ( min_prefix_sum , prefix_sum [ i ] ) ; } return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{8,9,11,17,18,19,23,24,27,30,31,31,35,44,46,47,49,51,55,58,59,61,65,67,71,71,71,71,78,78,82,91,98}); param0.add(new int[]{-82,-28,-66,-52,-36,36,-88,52,-62,46,42,26,-60,18,-52,38,94,-68,44,-94,14,36,-70}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{28,36,42,42,5,52,74,86,55,82,59,81,4,90,24,34,20,99,86,25,52,48,62,5,67,83,60,72,80,73,38,55,8,70,95}); param0.add(new int[]{-92,-52,-24,36,56}); param0.add(new int[]{0,1,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0}); param0.add(new int[]{1,1,4,4,7,7,17,18,20,26,26,32,37,38,42,44,44,46,50,53,57,58,58,60,61,61,64,74,75,77,83,83,84,84,85,87,88,90,95,96,97,98,99,99}); param0.add(new int[]{-86,2,26,54,-16,16,48,24,50,-10,-32,-62,48,-12,-66}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{58,14,79,11,31,28,61,86,25,27,75,78,32,55,86,48,15,51,6,78,23,82,16,62,35,51,91,16,79,38,97,30,23,58,95,57,82,35,57,43,22,41,58,69,25,65,13,79}); List<Integer> param1 = new ArrayList<>(); param1.add(20); param1.add(15); param1.add(19); param1.add(19); param1.add(3); param1.add(13); param1.add(25); param1.add(13); param1.add(14); param1.add(39); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,123
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_INDEX_PAIRS_EQUAL_ELEMENTS_ARRAY_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_INDEX_PAIRS_EQUAL_ELEMENTS_ARRAY_1{ public static int f_gold ( int arr [ ] , int n ) { HashMap < Integer , Integer > hm = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hm . containsKey ( arr [ i ] ) ) hm . put ( arr [ i ] , hm . get ( arr [ i ] ) + 1 ) ; else hm . put ( arr [ i ] , 1 ) ; } int ans = 0 ; for ( Map . Entry < Integer , Integer > it : hm . entrySet ( ) ) { int count = it . getValue ( ) ; ans += ( count * ( count - 1 ) ) / 2 ; } return ans ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{5,11,18,22,40,46,50,51,53,55,64,67,73,78,86}); param0.add(new int[]{14,-98,98,58,-82,90,-80,-56,-30,-36,-56,-30,-58,68,72,-76,38,-90,-72,4,-32,32,-28,2,12,-72,54,2,0,-74,8,12,46,72,-84,-66,70,18,26,72,-26,44,-8,20,-32,-56,28}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{93,23,62,64,31,78,99}); param0.add(new int[]{-94,-94,-92,-86,-84,-76,-76,-68,-66,-56,-56,-54,-50,-46,-38,-34,-34,-30,-26,-18,-16,2,8,42,52,54,56,64,68,82,82,82,94,96,98}); param0.add(new int[]{0}); param0.add(new int[]{3,18,18,20,21,23,24,27,35,36,38,40,46,50,50,51,52,53,59,61,63,63,65,66,68,68,70,71,74,75,96,98}); param0.add(new int[]{-68,40,16,50,36,42,-20,-46,-92,4,-18,-12,48,0,-46,64,-74,-50,42,44,-56,28,-10,78,62,70,-60,12,-44,-78}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{31,5}); List<Integer> param1 = new ArrayList<>(); param1.add(14); param1.add(24); param1.add(13); param1.add(4); param1.add(19); param1.add(0); param1.add(19); param1.add(23); param1.add(30); param1.add(1); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,124
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/HOW_TO_COMPUTE_MOD_OF_A_BIG_NUMBER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class HOW_TO_COMPUTE_MOD_OF_A_BIG_NUMBER{ static int f_gold ( String num , int a ) { int res = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) res = ( res * 10 + ( int ) num . charAt ( i ) - '0' ) % a ; return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("RElCP"); param0.add("0139035510"); param0.add("00011110"); param0.add("TwanZWwLNXhFN"); param0.add("6247009752778"); param0.add("0100001011011"); param0.add("NCh"); param0.add("00714746542"); param0.add("101000100"); param0.add("MSTkXmlbPkV"); List<Integer> param1 = new ArrayList<>(); param1.add(13); param1.add(44); param1.add(86); param1.add(66); param1.add(55); param1.add(33); param1.add(75); param1.add(54); param1.add(93); param1.add(78); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,125
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/LARGEST_SUBARRAY_WITH_EQUAL_NUMBER_OF_0S_AND_1S.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LARGEST_SUBARRAY_WITH_EQUAL_NUMBER_OF_0S_AND_1S{ static int f_gold ( int arr [ ] , int n ) { int sum = 0 ; int maxsize = - 1 , startindex = 0 ; int endindex = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { sum = ( arr [ i ] == 0 ) ? - 1 : 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] == 0 ) sum += - 1 ; else sum += 1 ; if ( sum == 0 && maxsize < j - i + 1 ) { maxsize = j - i + 1 ; startindex = i ; } } } endindex = startindex + maxsize - 1 ; if ( maxsize == - 1 ) System . out . println ( "No such subarray" ) ; else System . out . println ( startindex + " to " + endindex ) ; return maxsize ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{56,8,67,35,19,82,81,66,10,24,82,2,42,48,18,63,48,74,60,64,64,95,95,20,95,55,63,96,54}); param0.add(new int[]{78,67,1,78,48,83,17,19,21,44,99,68,16,54,9}); param0.add(new int[]{3,69,97,21,12,67,45,53,77,70,26,43}); param0.add(new int[]{21,80,29,22,77,64,42,4,71,75,62,27,30,36,66,37,49,97}); param0.add(new int[]{18,66,9,90,21,95,74,48,44,9,43,17}); param0.add(new int[]{42,41,87,3,64,25,96,55,99,57,32,64,10,75,69,95,11,36,15,2,78,70,14,54,11,28,55,47,27,85,47,62,97,68,44,70,12,27,36,85,76,91,17,75,83,34,32,89,55}); param0.add(new int[]{44}); param0.add(new int[]{1,43,28,17,30,46,89,51,15,70,96,79,65,55,8}); param0.add(new int[]{25,91,68,4,35,49,33}); param0.add(new int[]{14,86,22,42,94,54,28,41,48,8,82,84,99,92,33,75,38,31,59,86,21,6,77,89,79,83,57,26,89,45,60,55,60,76,76,6,40,57,38,44,7,98,64,65,88,73,88,99}); List<Integer> param1 = new ArrayList<>(); param1.add(26); param1.add(8); param1.add(9); param1.add(10); param1.add(10); param1.add(41); param1.add(0); param1.add(9); param1.add(4); param1.add(26); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,126
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_PAIRS_DIFFERENCE_EQUAL_K_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_PAIRS_DIFFERENCE_EQUAL_K_1{ static int f_gold ( int arr [ ] , int n , int k ) { int count = 0 ; Arrays . sort ( arr ) ; int l = 0 ; int r = 0 ; while ( r < n ) { if ( arr [ r ] - arr [ l ] == k ) { count ++ ; l ++ ; r ++ ; } else if ( arr [ r ] - arr [ l ] > k ) l ++ ; else r ++ ; } return count ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{5,5,10,19,29,32,40,60,65,70,72,89,92}); param0.add(new int[]{-38,40,8,64,-38,56,4,8,84,60,-48,-78,-82,-88,-30,58,-58,62,-52,-98,24,22,14,68,-74,48,-56,-72,-90,26,-10,58,40,36,-80,68,58,-74,-46,-62,-12,74,-58}); param0.add(new int[]{0,0,1}); param0.add(new int[]{16,80,59,29,14,44,13,76,7,65,62,1,34,49,70,96,73,71,42,73,66,96}); param0.add(new int[]{-98,-88,-58,-56,-48,-34,-22,-18,-14,-14,-8,-4,-2,2,18,38,42,46,54,68,70,90,94,96,98}); param0.add(new int[]{0,1,1}); param0.add(new int[]{11,43,50,58,60,68,75}); param0.add(new int[]{86,94,-80,0,52,-56,42,88,-10,24,6,8}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{54,99,4,14,9,34,81,36,80,50,34,9,7}); List<Integer> param1 = new ArrayList<>(); param1.add(7); param1.add(24); param1.add(1); param1.add(12); param1.add(23); param1.add(2); param1.add(4); param1.add(11); param1.add(29); param1.add(9); List<Integer> param2 = new ArrayList<>(); param2.add(12); param2.add(36); param2.add(1); param2.add(16); param2.add(22); param2.add(1); param2.add(4); param2.add(9); param2.add(30); param2.add(8); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,127
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_ROTATIONS_DIVISIBLE_4.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_ROTATIONS_DIVISIBLE_4{ static int f_gold ( String n ) { int len = n . length ( ) ; if ( len == 1 ) { int oneDigit = n . charAt ( 0 ) - '0' ; if ( oneDigit % 4 == 0 ) return 1 ; return 0 ; } int twoDigit , count = 0 ; for ( int i = 0 ; i < ( len - 1 ) ; i ++ ) { twoDigit = ( n . charAt ( i ) - '0' ) * 10 + ( n . charAt ( i + 1 ) - '0' ) ; if ( twoDigit % 4 == 0 ) count ++ ; } twoDigit = ( n . charAt ( len - 1 ) - '0' ) * 10 + ( n . charAt ( 0 ) - '0' ) ; if ( twoDigit % 4 == 0 ) count ++ ; return count ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("MRRuQJvxe"); param0.add("87395768"); param0.add("10111100110111"); param0.add("aVDUEfzG"); param0.add("55794792"); param0.add("111010"); param0.add("cndMLMJVmzuH"); param0.add("487717559382"); param0.add("11110"); param0.add("dRMDPyr"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,128
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/DISTRIBUTING_ITEMS_PERSON_CANNOT_TAKE_TWO_ITEMS_TYPE_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class DISTRIBUTING_ITEMS_PERSON_CANNOT_TAKE_TWO_ITEMS_TYPE_1{ static boolean f_gold ( int arr [ ] , int n , int k ) { HashMap < Integer , Integer > hash = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! hash . containsKey ( arr [ i ] ) ) hash . put ( arr [ i ] , 0 ) ; hash . put ( arr [ i ] , hash . get ( arr [ i ] ) + 1 ) ; } for ( Map . Entry x : hash . entrySet ( ) ) if ( ( int ) x . getValue ( ) > 2 * k ) return false ; return true ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{1,1,2,3,1}); param0.add(new int[]{2,3,3,5,3,3}); param0.add(new int[]{0,0,1,1,1}); param0.add(new int[]{7,60,78,91,80,75,85,21,41,63,1,84,69,13,94,25,54,54,52,68,53,35,17,37,98,27,2,31}); param0.add(new int[]{-96,-94,-82,-80,-78,-66,-36,-24,-18,-12,-2,-2,6,8,10,12,36,38,42,58,64,68,82,84,86,88,94}); param0.add(new int[]{0,1,1,1,0,0,0,0,1,0,0,0,1,0,0,1,1,1,1,1,1,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,1,0,0,1,1,1,0}); param0.add(new int[]{16,19,25,25,32,37,48,59,60,60,71,74,77,81,91,94}); param0.add(new int[]{-62,-94,72,-22,86,-80,64,98,-82,-50,12,-4,56,46,-80,2,-86,-44,-26,68,-94,-82,74,26,94,40,50,-40,-42,-10}); param0.add(new int[]{0,0,0,0,0,1,1,1}); param0.add(new int[]{83,57,2,47,70,22,49,51,25,57,32,7,8,99,6,86,24,79,42,43,1,24,68,11,24,12,43,40,14,45,11,46,12,80,66}); List<Integer> param1 = new ArrayList<>(); param1.add(5); param1.add(6); param1.add(2); param1.add(24); param1.add(24); param1.add(34); param1.add(10); param1.add(20); param1.add(5); param1.add(21); List<Integer> param2 = new ArrayList<>(); param2.add(2); param2.add(2); param2.add(1); param2.add(2); param2.add(3); param2.add(2); param2.add(8); param2.add(4); param2.add(2); param2.add(33); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,129
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/MINIMUM_NUMBER_SUBSETS_DISTINCT_ELEMENTS_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MINIMUM_NUMBER_SUBSETS_DISTINCT_ELEMENTS_1{ static int f_gold ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) mp . put ( arr [ i ] , mp . get ( arr [ i ] ) == null ? 1 : mp . get ( arr [ i ] ) + 1 ) ; int res = 0 ; for ( Map . Entry < Integer , Integer > entry : mp . entrySet ( ) ) res = Math . max ( res , entry . getValue ( ) ) ; return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{2,6,9,12,15,19,21,23,24,24,25,27,29,35,36,37,41,44,44,47,48,51,56,59,59,59,60,64,64,66,67,68,68,69,73,74,77,78,81,82,83,85,89,94,95,96,98,99}); param0.add(new int[]{96,20,-40,74,-44,98,-24,92,58,-84,-76,-14,64,-2,-84,52,-8,38,-26,-10,-62,-30,-76,58}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{35,16,42,3,57,70,4,31,93,60,98,97,81,57,62,98,88,51,5,58,48,14,58,22,40,26,66,41,9,78,62,32,79,88,65,75,80,12,15,93,92,13,83,26}); param0.add(new int[]{-62,-44,-36,-18,-16,-6,4,14,22,42,68,90}); param0.add(new int[]{1,0,1,0,1,1,1,1,0,1,0,1,0,0,0,0}); param0.add(new int[]{20,25,27,29,47,47,49,53,59,66,74,82,86,86,94,94,97}); param0.add(new int[]{92,50,76,46,14,40,22}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{8,82,92,42,55,4,94,73,57,7,21,71,68,97}); List<Integer> param1 = new ArrayList<>(); param1.add(30); param1.add(20); param1.add(31); param1.add(37); param1.add(11); param1.add(12); param1.add(13); param1.add(3); param1.add(27); param1.add(12); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,130
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_SORTED_ROWS_MATRIX.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_SORTED_ROWS_MATRIX{ static int f_gold ( int mat [ ] [ ] , int r , int c ) { int result = 0 ; for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = 0 ; j < c - 1 ; j ++ ) if ( mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] ) break ; if ( j == c - 1 ) result ++ ; } for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = c - 1 ; j > 0 ; j -- ) if ( mat [ i ] [ j - 1 ] <= mat [ i ] [ j ] ) break ; if ( c > 1 && j == 0 ) result ++ ; } return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ] [ ]> param0 = new ArrayList<>(); param0.add(new int[][]{new int[]{4,12,13,24,25,26,27,35,41,60,69,71,73,78,85,86,95,99},new int[]{1,13,18,25,41,42,44,45,49,49,51,52,59,63,64,67,78,97},new int[]{1,2,11,18,23,26,30,31,41,42,45,71,75,90,91,92,95,97},new int[]{26,30,44,46,46,54,56,60,67,68,75,77,77,83,87,87,94,98},new int[]{19,20,27,31,33,34,37,41,42,49,60,60,64,67,71,73,77,92},new int[]{2,6,9,11,20,29,37,41,42,44,49,58,62,76,87,89,94,97},new int[]{7,8,9,14,20,45,49,54,63,63,64,71,72,73,73,89,94,95},new int[]{2,3,7,16,17,23,23,25,44,50,58,58,59,78,83,87,90,99},new int[]{4,16,18,22,23,33,34,43,43,46,51,56,62,75,79,85,97,97},new int[]{16,18,29,32,39,53,54,55,67,70,72,72,76,76,86,87,96,96},new int[]{6,30,34,37,38,42,52,54,59,67,71,71,72,81,85,87,91,93},new int[]{2,6,6,16,18,20,21,31,40,42,50,56,62,80,80,83,91,96},new int[]{2,5,6,14,16,21,23,37,52,59,72,86,86,87,87,89,90,91},new int[]{1,10,17,20,22,25,27,32,37,37,44,49,65,78,80,81,85,95},new int[]{1,13,14,21,43,50,52,58,62,64,65,66,66,66,67,70,81,82},new int[]{1,2,9,16,17,23,25,29,30,31,42,65,73,74,82,87,92,92},new int[]{1,5,9,13,21,28,32,33,34,38,46,60,80,86,93,94,96,98},new int[]{11,18,23,24,25,26,28,48,59,59,67,72,82,83,86,89,92,96}}); param0.add(new int[][]{new int[]{82,82,2,8,-32,90,-76,-64,-66,-46,-72,-58,-28,-86,-8,-96,-62,-32,54,-16,96,28,76,90,-40,98,88,-90,4,-50,70,32,-74,-72,-72,10,36,50,-16,-36},new int[]{-52,-6,12,-6,-64,6,38,-14,-86,74,-74,82,54,2,46,-94,88,86,-32,-72,72,88,90,-8,-58,32,-90,-68,-70,72,34,74,-30,92,90,-88,82,-54,42,94},new int[]{-4,-32,-12,-96,16,-32,32,52,2,-6,2,-10,40,-64,4,-56,-50,46,54,-6,-14,-40,-98,-4,-20,98,94,60,-70,-94,52,-4,32,20,-30,-94,-50,50,-86,-66},new int[]{10,84,2,-44,-54,-82,-64,70,-20,-40,-50,10,26,-14,-88,10,-80,-48,10,16,-14,-52,74,-60,48,-60,-62,38,56,-34,86,20,74,-20,28,-46,-44,96,-58,-8},new int[]{-48,-36,-18,-66,-20,60,-36,34,-94,44,-14,-34,-84,-26,38,48,14,12,72,-76,26,50,-58,40,90,14,-40,22,-26,-24,66,-62,-34,16,-34,-30,54,-76,-26,4},new int[]{-26,56,74,-82,58,-42,-98,96,-24,-36,-86,-80,42,78,-2,-90,-8,-52,46,-20,-16,64,-36,-8,-16,-60,96,40,66,98,14,-36,-78,-40,52,60,-20,38,26,-98},new int[]{-12,60,-56,-66,68,-20,-74,30,14,-36,-22,-54,50,62,-44,14,90,66,80,76,-86,92,-80,-6,48,44,24,40,94,-42,68,28,-20,98,40,50,-18,90,6,2},new int[]{-98,4,-32,-34,-64,58,16,48,82,10,36,32,-60,-40,2,-14,-58,28,-44,60,-28,-6,-68,46,-50,62,10,44,-4,76,60,-26,52,40,-88,-56,-36,-70,-66,-22},new int[]{18,-66,-82,52,34,-86,-50,-64,18,10,-14,8,80,-76,20,76,96,-12,-36,86,-10,16,-14,66,-4,14,-82,0,2,90,78,-48,42,-60,90,-16,80,16,-64,-58},new int[]{12,8,-74,78,46,-84,20,14,-2,-42,-80,-66,-64,34,58,0,28,-8,34,92,-14,-54,82,68,64,6,30,78,-50,-28,-74,-12,-18,82,-50,-86,-2,-78,94,-66},new int[]{10,-76,58,32,-44,60,-14,24,-92,24,16,80,90,-60,-6,8,-50,90,60,82,6,84,74,-48,-98,-2,-38,74,64,52,8,-32,-58,-58,70,-14,68,46,32,74},new int[]{84,98,78,34,-94,84,10,84,10,-58,-70,-30,98,-28,-80,56,-36,96,82,38,2,-38,28,18,82,60,-16,-64,90,34,-10,98,36,40,-6,-32,-32,-24,92,12},new int[]{54,92,-30,-12,40,48,8,34,-20,-58,8,-14,0,-34,98,-32,-98,40,-44,34,94,-56,-90,64,4,-76,-34,-68,48,28,84,-4,-46,-54,72,-82,0,-82,38,-6},new int[]{44,-66,-86,54,-4,36,62,88,-16,-88,-26,-50,-84,-90,38,14,62,14,-92,64,-50,-2,-96,-4,94,-84,26,-86,-68,6,-18,-66,-56,-88,-92,-86,64,-6,-92,-12},new int[]{-36,80,-28,-42,58,-12,-66,-38,-76,34,-52,-32,-80,66,54,-2,-40,78,14,-54,6,-92,68,-40,72,-80,52,-60,98,-60,-92,26,-24,26,46,34,80,-92,16,16},new int[]{-4,60,-72,-6,46,76,-8,82,42,-68,-86,10,20,80,-22,64,-40,22,-6,-58,-74,-86,-16,-14,-76,-54,-98,-50,-74,80,-44,18,-70,-80,58,-48,-70,44,46,88},new int[]{-80,-76,-46,-92,-78,-72,-56,72,-52,-86,-48,6,84,38,-14,66,48,86,36,-80,-54,-44,-88,-18,-50,-56,-20,-14,-52,-98,-44,-76,-42,-66,-20,62,0,-54,-82,-70},new int[]{44,98,78,56,-14,-70,-24,62,88,70,-42,72,80,42,22,-90,-50,-22,14,40,42,34,66,-58,70,22,-86,58,-82,54,-20,72,20,32,8,30,52,-6,-12,-62},new int[]{-4,70,-76,22,22,44,-84,-74,34,-36,64,-78,50,72,-40,-78,-26,-66,-84,-28,-40,-96,66,36,-28,-18,4,0,20,18,78,-74,-58,-64,-68,68,-84,20,-56,-16},new int[]{0,24,64,-50,-36,70,-88,-34,70,68,-68,80,88,12,-50,74,32,18,-14,74,58,68,-62,-30,20,94,-68,96,-32,-94,-70,-44,-76,-94,34,54,-74,62,-80,-10},new int[]{-64,-26,-26,44,14,-72,-74,36,-8,-64,-34,6,18,14,74,-90,66,-12,-6,-6,-12,-58,72,18,62,-44,12,-56,66,34,44,0,-98,96,-94,-60,76,52,48,-6},new int[]{6,-58,14,82,-72,0,92,8,-6,-18,74,-66,68,-24,-20,90,-48,54,18,-24,-8,-48,72,-78,-54,84,18,-52,-36,-30,-82,-34,8,-94,-34,-78,-28,44,92,-78},new int[]{-50,-84,-82,-12,62,-72,-36,84,-36,-82,12,-52,12,-34,36,8,-24,58,6,-34,0,-22,46,98,62,80,-88,-24,98,30,22,94,-38,-24,78,62,0,-10,2,52},new int[]{94,-10,-88,-12,-10,56,-86,18,54,-20,22,-18,76,-88,-38,38,-88,-20,82,88,-80,-34,14,54,28,-46,-88,-84,-86,38,86,26,98,-28,14,-24,-22,-80,-98,58},new int[]{60,52,12,-86,-54,-30,10,-2,-54,-74,56,74,-74,92,86,-92,-28,-54,30,-56,40,96,92,16,82,-70,-80,92,-80,14,56,-6,8,-92,20,10,-50,-64,-34,50},new int[]{64,70,-74,-72,78,46,42,44,-96,-18,-62,56,-90,-14,38,82,8,-58,52,92,-90,22,-60,62,60,-64,-56,-74,92,-2,-90,-14,-56,-64,38,18,-52,-92,30,-36},new int[]{50,84,82,36,60,34,-50,-64,-72,30,8,84,48,-24,78,80,-10,-90,82,-80,-4,-94,24,92,92,-16,-80,68,60,98,-92,52,60,8,-72,12,-60,-84,-44,-34},new int[]{-98,-30,30,36,96,74,-82,-2,-72,-38,-40,10,92,30,98,-28,56,70,-84,66,40,92,42,-86,-58,-90,-10,98,-12,-80,94,4,-84,60,94,-90,74,-68,64,-76},new int[]{2,94,38,-6,64,4,-42,92,-12,54,82,90,-64,32,0,-24,-16,-68,78,54,28,-86,-56,4,16,98,32,-18,-76,90,-6,72,40,20,6,-90,52,-62,4,30},new int[]{22,90,54,-34,-30,0,-72,-6,36,28,-96,86,-2,-48,-30,8,-60,-32,24,-50,-76,-86,32,28,-66,-88,24,86,72,96,22,-32,-92,-26,48,-52,-12,4,-94,2},new int[]{-44,70,38,36,-36,46,-68,-44,-36,34,-32,-44,-22,-80,-64,28,60,92,-52,14,42,-80,-70,50,24,-34,16,64,62,-94,18,-48,-68,16,76,-42,30,-88,46,-12},new int[]{46,46,44,16,-70,-6,-78,-46,70,30,70,88,66,56,-12,4,76,-50,-28,-98,-16,-86,-68,36,28,-92,-46,-86,-2,90,6,36,-62,-30,-26,-38,22,-60,-20,-70},new int[]{80,38,-94,-42,70,-20,42,-62,-30,54,82,-94,-78,74,60,54,-52,-56,66,86,-30,-14,0,-6,-22,56,70,-86,50,82,72,-10,54,24,-46,-26,-20,-54,-96,30},new int[]{-48,94,54,-16,70,20,-20,-2,-8,84,-60,30,-18,-14,32,42,24,26,-12,-62,2,-94,26,36,-88,-22,-64,46,36,74,-44,-56,-36,-98,70,72,-68,68,76,-32},new int[]{-4,36,0,14,-42,-38,-98,-2,-44,-90,82,80,-66,38,62,34,52,44,-22,80,-74,-88,-74,24,98,8,18,-26,-4,-82,-60,44,-2,30,20,52,26,-22,-54,96},new int[]{98,-54,-12,-12,-74,34,-6,-36,-94,40,96,42,-32,-46,-46,88,-90,26,-98,30,92,-34,74,-94,36,-68,-66,74,-2,6,94,-12,82,90,-2,78,-80,-84,18,74},new int[]{-42,30,56,-74,-16,-44,4,-62,-12,-62,-22,64,56,96,-16,40,10,88,-66,54,56,96,74,-6,-36,-70,-82,74,-14,-18,-32,-70,60,26,-88,-78,-8,32,-84,90},new int[]{-44,-14,-44,96,0,54,2,74,36,-56,-98,-16,-70,68,-88,26,-18,30,62,-88,-28,-58,62,-38,-62,28,-80,-6,88,-16,64,-58,14,94,-40,2,-12,-16,-24,-64},new int[]{20,18,-94,94,-2,-74,-56,-46,62,-88,-16,-30,-10,-54,38,22,-42,32,28,-42,44,64,46,66,-96,70,-32,10,-14,72,-42,98,-54,36,76,24,-96,86,54,-88},new int[]{74,-48,90,78,-44,0,76,-16,-28,-92,10,-32,-30,-78,-8,40,-90,74,-40,16,-78,22,-42,36,68,44,42,6,-60,36,-74,-92,92,-44,40,-92,-46,56,-36,-94}}); param0.add(new int[][]{new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}); param0.add(new int[][]{new int[]{91,8,34,7,66,59,90,78,54,77,55,29,90,69,85,42,39,49,83,59,3,41,65,60,4,45,65,29,47,40,96,11,21,74,34,83,12,3,6,67,30,29,40,87,35,73,17,13,20},new int[]{38,36,55,16,85,38,67,15,37,25,81,61,31,68,31,11,23,39,35,21,66,66,52,49,55,35,40,47,99,25,91,6,50,3,62,11,46,88,95,17,40,70,35,76,59,84,4,99,84},new int[]{61,2,63,5,81,77,7,32,74,17,53,17,86,5,86,15,80,84,94,64,86,94,64,7,90,64,15,94,56,51,64,84,77,70,49,2,46,96,64,25,18,54,39,73,77,23,46,14,23},new int[]{48,22,2,60,46,8,3,70,58,6,27,23,71,92,10,45,48,85,81,86,61,27,85,75,1,49,47,82,8,74,92,40,61,27,12,30,37,66,84,36,86,40,36,96,60,96,70,27,41},new int[]{13,6,54,10,54,19,24,61,87,77,14,45,37,15,74,4,47,61,78,91,68,99,67,70,70,26,72,19,75,93,56,66,76,80,49,45,62,85,50,51,48,40,48,13,69,62,82,13,13},new int[]{25,75,45,24,38,4,19,83,38,61,21,59,71,72,76,59,36,31,72,23,16,22,68,40,28,60,89,87,87,89,16,11,45,89,75,25,43,67,69,41,66,91,38,62,73,29,13,45,68},new int[]{30,1,39,11,69,4,8,3,52,59,24,47,88,62,30,96,38,80,62,86,81,12,72,65,10,64,95,58,60,95,51,60,89,35,54,85,67,38,58,85,12,40,5,47,35,95,26,60,33},new int[]{47,58,24,5,76,9,56,45,32,69,14,63,7,2,55,36,29,59,15,64,65,80,99,2,99,23,18,98,26,38,58,52,92,53,18,40,86,93,18,26,71,65,29,91,80,91,29,44,31},new int[]{63,5,55,56,10,58,53,43,89,30,98,71,20,94,28,27,65,65,54,66,69,28,82,30,2,13,71,16,31,55,65,62,76,66,36,70,42,66,82,73,63,21,27,89,44,99,70,75,96},new int[]{6,19,62,34,59,79,75,95,84,64,95,81,81,77,83,62,24,4,18,97,33,43,57,40,90,65,10,88,84,54,68,58,40,46,88,32,1,97,4,36,41,57,30,13,43,77,88,99,29},new int[]{23,37,24,76,53,11,28,95,2,89,27,47,2,3,12,67,25,66,7,38,45,63,15,93,2,12,44,28,68,27,52,23,85,4,59,92,35,17,27,7,91,20,84,22,26,34,63,87,54},new int[]{97,74,14,36,43,72,69,25,78,13,46,10,88,50,49,98,55,43,22,78,13,78,46,9,24,32,61,91,51,53,58,95,54,47,11,21,18,60,10,27,82,66,90,40,45,52,98,85,16},new int[]{34,59,78,37,11,87,79,40,58,33,82,33,96,86,94,40,71,85,59,22,65,73,20,63,76,91,24,29,68,27,45,97,69,33,43,86,92,31,19,32,15,39,37,19,14,38,5,53,20},new int[]{44,25,58,89,40,99,34,90,26,87,63,16,43,84,77,25,48,55,7,47,43,84,3,41,28,65,34,9,43,39,76,8,52,12,75,43,16,94,18,93,12,83,54,15,27,81,46,89,24},new int[]{67,92,60,34,46,5,80,64,53,65,94,65,36,66,56,52,82,54,32,55,69,88,43,41,11,8,33,95,32,48,71,9,89,7,2,33,29,76,33,38,99,48,99,92,68,22,70,19,14},new int[]{90,32,71,27,57,73,87,90,40,24,15,27,70,87,74,29,8,30,17,87,13,93,46,87,12,30,43,80,14,3,23,75,67,51,23,49,69,69,69,54,57,46,60,43,47,70,14,30,95},new int[]{69,58,48,20,45,70,13,66,65,42,62,76,9,8,17,28,22,2,60,6,73,54,24,32,15,11,75,62,8,99,51,36,83,15,55,18,17,78,80,82,97,70,60,46,78,16,1,26,43},new int[]{34,59,69,68,91,5,24,72,81,23,64,19,72,6,66,72,91,96,65,11,28,27,27,87,87,61,29,52,86,14,41,86,59,5,42,91,22,50,9,6,99,37,24,4,8,67,62,38,99},new int[]{62,48,96,3,14,75,47,80,50,61,51,77,82,37,31,49,87,48,94,4,92,94,99,26,65,29,18,4,9,14,35,60,54,33,52,49,44,31,53,95,28,3,14,97,53,19,80,73,5},new int[]{18,14,24,76,93,33,55,40,65,59,45,3,29,17,12,4,60,72,23,82,14,94,65,19,24,50,91,80,96,78,41,37,75,77,4,94,69,80,48,5,55,85,43,58,36,3,8,40,87},new int[]{92,18,42,47,28,4,55,10,46,52,75,20,48,62,7,14,78,95,49,58,14,2,43,29,57,98,83,90,56,62,92,91,2,69,79,44,1,5,43,54,34,88,67,60,42,37,56,51,3},new int[]{28,31,22,14,75,56,68,57,39,10,73,69,72,27,79,2,99,99,10,24,48,56,19,9,21,80,36,43,11,49,85,49,84,84,28,48,13,80,39,94,8,19,97,73,3,12,29,34,34},new int[]{99,50,58,74,49,22,2,84,94,89,94,38,68,86,42,41,43,69,49,17,17,96,78,18,93,48,18,32,87,16,6,70,97,72,55,20,40,56,51,54,3,57,69,71,74,18,64,31,39},new int[]{23,18,26,32,12,65,32,90,98,14,8,79,44,56,52,33,34,31,92,95,99,11,90,65,59,95,49,27,77,64,21,33,2,69,11,67,65,89,40,12,66,60,65,10,62,48,32,84,43},new int[]{87,26,33,4,89,44,32,68,19,61,35,74,56,55,82,66,79,76,10,64,95,33,87,89,88,67,11,14,85,99,56,78,72,51,43,44,76,11,77,14,83,70,44,58,2,46,75,61,31},new int[]{93,73,8,30,6,84,16,28,43,47,80,29,89,86,91,83,98,42,91,65,20,77,34,1,24,57,77,96,66,61,55,63,7,1,52,67,85,47,32,74,88,34,94,73,7,59,78,47,42},new int[]{90,35,30,1,10,96,62,91,53,13,6,33,44,6,62,49,40,35,55,30,96,98,51,57,83,45,52,51,64,70,92,99,91,2,7,95,50,77,82,23,2,56,39,97,86,55,72,69,92},new int[]{45,12,56,49,85,32,64,91,3,47,10,82,50,33,71,53,94,32,57,63,59,65,83,85,73,94,28,95,76,11,51,17,87,12,69,65,58,31,76,94,13,42,15,43,34,14,60,88,24},new int[]{75,34,12,19,35,60,73,5,33,74,27,12,68,58,69,94,31,99,86,32,35,78,56,6,43,71,30,56,88,14,46,41,12,6,52,15,84,52,6,13,60,49,61,45,42,72,51,82,99},new int[]{95,81,81,39,93,29,96,7,99,11,94,42,1,16,99,74,68,49,15,6,15,80,68,25,86,69,76,6,64,96,87,57,94,99,39,71,3,92,68,30,5,91,49,40,5,26,58,82,90},new int[]{4,57,97,16,67,90,23,89,24,84,90,66,76,51,21,44,41,52,54,71,14,64,80,49,88,2,94,76,10,71,78,1,59,39,18,56,45,43,95,13,30,93,86,78,21,14,31,98,76},new int[]{40,86,5,71,50,83,56,89,56,6,75,48,16,31,65,10,90,63,84,63,1,81,6,21,89,58,70,18,72,49,10,68,2,99,10,51,86,63,55,77,90,32,53,48,99,76,45,31,52},new int[]{99,19,61,12,65,15,53,96,50,46,9,32,91,55,84,30,59,58,92,99,37,68,94,78,59,47,51,4,89,10,84,84,43,83,95,2,54,81,22,60,11,30,98,59,57,37,88,43,9},new int[]{14,75,98,81,61,53,54,7,97,68,98,21,92,20,12,26,14,69,52,59,36,37,89,82,13,57,26,34,12,72,12,63,91,10,21,73,46,60,8,17,5,50,30,10,83,53,97,90,39},new int[]{64,61,79,7,82,31,35,88,41,39,61,54,15,67,50,86,79,58,54,9,51,83,47,8,43,6,53,61,51,45,90,42,38,35,70,7,1,18,26,87,51,76,34,82,76,66,10,66,7},new int[]{62,86,31,83,51,75,40,72,22,4,42,47,56,77,36,55,36,36,74,55,67,3,96,88,38,68,2,34,92,83,16,97,70,13,36,65,73,20,49,53,49,13,32,47,42,29,26,81,44},new int[]{44,18,97,11,67,31,23,89,39,31,82,62,55,55,15,83,66,6,13,58,88,97,62,21,37,75,27,18,78,11,52,47,33,9,87,49,38,67,12,14,3,5,60,63,13,22,2,31,45},new int[]{55,47,20,4,13,45,34,25,95,4,13,19,1,36,74,85,51,23,35,95,23,65,63,58,67,12,18,51,21,23,38,87,92,65,69,14,48,62,86,73,41,52,12,55,85,46,88,44,38},new int[]{83,29,86,98,92,66,4,69,74,50,78,75,3,44,78,34,12,54,17,90,23,97,21,96,6,3,73,5,58,93,45,64,2,97,33,93,14,62,68,19,53,66,78,5,52,94,84,60,54},new int[]{15,44,11,54,64,99,91,94,57,73,95,25,24,4,66,11,84,83,50,89,31,83,27,75,98,49,15,3,59,20,67,67,4,67,23,97,87,17,67,57,91,34,81,99,90,29,55,88,28},new int[]{18,89,80,81,71,51,19,14,63,18,10,40,7,64,41,55,51,75,30,89,7,18,18,89,46,98,25,1,71,6,43,89,88,30,90,30,37,57,99,3,37,91,45,69,46,32,19,51,83},new int[]{11,5,99,30,60,57,35,66,16,60,93,22,7,20,58,29,91,80,59,81,52,1,51,79,88,26,92,40,12,59,9,57,42,94,24,17,79,36,48,71,83,48,88,50,69,12,62,27,22},new int[]{50,91,58,61,4,65,8,12,10,67,97,24,59,37,57,29,58,43,66,25,7,97,93,73,98,24,86,31,8,30,64,93,66,4,91,78,70,67,33,5,63,41,16,39,7,42,21,22,75},new int[]{2,16,31,71,84,77,39,36,83,7,14,43,53,3,76,98,29,68,75,3,5,94,73,21,2,97,73,48,6,66,45,85,27,99,62,67,34,66,13,39,18,11,4,35,62,55,91,86,63},new int[]{1,57,15,25,30,61,83,28,24,17,60,56,58,7,68,10,76,6,35,18,28,55,82,52,19,18,63,40,49,95,82,76,78,85,61,79,31,48,49,40,60,67,65,86,71,44,45,58,33},new int[]{64,70,88,84,20,95,73,14,2,56,94,73,83,25,93,58,49,91,76,72,10,42,73,35,49,88,12,87,78,87,78,38,57,81,12,19,14,75,71,24,78,32,23,61,8,68,61,54,4},new int[]{22,20,70,20,61,33,74,38,14,2,88,96,31,86,10,34,61,59,92,47,92,70,52,1,39,47,62,17,92,95,7,5,56,73,86,36,25,73,10,90,38,25,42,88,3,75,44,71,61},new int[]{90,36,14,93,21,25,23,58,5,43,65,53,93,76,93,25,48,20,73,42,28,2,92,13,24,28,20,88,53,90,52,86,33,31,39,58,19,80,54,24,19,48,11,17,41,13,63,56,48},new int[]{87,89,92,89,55,51,31,4,3,3,8,39,23,32,25,74,83,66,79,54,45,97,33,22,89,1,7,91,97,2,55,18,32,69,12,71,94,85,56,47,16,27,99,80,32,15,50,79,25}}); param0.add(new int[][]{new int[]{-94,-78,-30,-16,-14,22,44,44,54,60,68,72,92,94,98},new int[]{-92,-68,-52,-40,-30,-28,-20,-16,14,38,42,54,60,72,86},new int[]{-78,-68,-58,-36,-10,-10,42,48,52,52,58,68,72,78,96},new int[]{-94,-86,-84,-60,-40,0,0,22,48,56,70,72,80,90,96},new int[]{-98,-92,-80,-68,-58,38,50,52,58,60,62,62,72,86,90},new int[]{-94,-92,-70,-64,-46,-38,-32,-14,-10,-6,18,30,32,74,98},new int[]{-72,-60,-52,-50,-26,-24,-6,4,10,40,46,86,88,98,98},new int[]{-94,-72,-40,-36,-36,-28,0,18,34,36,38,44,50,54,98},new int[]{-72,-60,-40,-38,-36,-26,-18,-8,-2,2,30,34,50,76,80},new int[]{-96,-74,-46,-38,-26,-16,-10,2,2,20,28,48,48,60,90},new int[]{-86,-60,-58,-58,-46,-40,-4,2,16,18,26,62,64,78,98},new int[]{-98,-50,-12,-10,-2,12,20,40,60,66,76,78,84,90,92},new int[]{-72,-68,-68,-52,-8,-6,10,20,42,52,54,56,72,86,90},new int[]{-80,-74,-32,10,18,54,62,74,76,78,86,86,88,94,96},new int[]{-98,-78,-76,-72,-56,-30,-26,0,36,42,44,76,84,88,94}}); param0.add(new int[][]{new int[]{0,0,0,1,0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,1,0,0,0,1,1,0},new int[]{0,0,1,0,0,0,0,0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,1,0,0,0,1},new int[]{1,0,0,1,1,0,0,1,0,1,0,0,1,1,1,1,0,1,0,1,1,1,0,0,0,1,0},new int[]{1,1,1,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,1,1,1,0,0,1,0},new int[]{1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0},new int[]{1,0,1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,1,1,0,1,1,0,0},new int[]{1,0,1,1,0,0,0,1,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,1,1},new int[]{1,0,0,0,0,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0},new int[]{0,1,1,0,1,1,0,0,1,0,1,0,1,1,1,1,1,0,1,1,1,1,1,0,0,1,1},new int[]{0,1,0,0,1,0,1,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,1},new int[]{1,1,1,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,0,1,0,0,1,0,1,1},new int[]{0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,1,1,0,0,1},new int[]{1,1,0,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,0},new int[]{1,1,1,0,1,1,1,0,0,1,0,0,1,1,1,0,0,1,1,1,0,0,0,0,0,1,0},new int[]{1,1,1,0,1,1,1,0,0,0,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,1},new int[]{0,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1,1,0,1,0,0,0,0,1,1,0},new int[]{1,1,1,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,1,1,0,1,0},new int[]{0,0,0,0,0,0,1,1,1,0,0,1,0,0,1,0,0,0,1,1,0,1,1,1,0,0,1},new int[]{1,0,0,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,1,0,0,0,0,1},new int[]{0,0,0,0,0,1,0,1,1,0,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,0,1},new int[]{1,0,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0},new int[]{1,1,0,0,1,0,1,1,1,0,0,0,1,0,0,0,0,1,1,0,1,1,1,0,1,0,0},new int[]{1,1,0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,0},new int[]{0,1,0,1,0,0,0,1,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,0,0,1},new int[]{1,1,1,1,1,0,1,1,0,1,0,1,1,1,1,1,0,0,1,1,0,1,0,0,1,1,1},new int[]{1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,0,1,1,0,1},new int[]{0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,1,1,1,1,1,1,0,0,0}}); param0.add(new int[][]{new int[]{2,21,39,67,70,73,83,86,87,93},new int[]{31,42,53,56,64,65,85,89,94,98},new int[]{3,15,17,50,52,67,73,82,91,94},new int[]{12,15,16,21,23,30,33,38,50,89},new int[]{5,7,25,28,38,43,43,58,64,86},new int[]{24,26,29,33,46,47,52,71,86,96},new int[]{7,10,23,24,36,39,47,61,77,89},new int[]{1,10,26,27,61,62,64,80,85,94},new int[]{3,8,16,32,37,48,54,58,77,82},new int[]{43,52,70,76,81,84,84,85,95,99}}); param0.add(new int[][]{new int[]{62,-24,-62,-18,46,14,90,-42,-98,-52,36,96,26,-26,38,-88,88,-98,-86},new int[]{-24,58,-70,-56,68,-66,-24,30,-86,-74,98,-24,-48,-28,24,-64,22,46,40},new int[]{2,-30,-94,6,-24,-42,-70,-20,-80,14,74,72,-68,58,36,40,88,-80,54},new int[]{-24,-50,-96,-36,36,30,-58,64,98,-86,-74,-18,-64,74,-46,-24,68,34,24},new int[]{-34,96,14,-50,-68,-72,-38,-52,56,4,60,-90,-70,16,-4,0,-82,2,-16},new int[]{22,10,54,-86,14,12,64,-54,92,2,88,50,-24,-86,-32,46,-66,-26,-90},new int[]{-22,26,44,2,70,-94,-78,32,-30,-64,90,-16,68,-60,-10,-18,-64,20,-18},new int[]{72,-14,-98,-54,72,18,24,4,-16,-26,78,-80,26,-10,18,20,22,68,20},new int[]{-32,74,14,-18,88,42,6,-6,-16,-30,80,-16,24,-96,-96,-52,-38,-34,-46},new int[]{-12,-72,-48,52,-64,-30,26,64,0,34,52,-66,98,-96,-52,-96,38,-56,-32},new int[]{-2,18,-60,-52,-46,62,-10,82,-24,34,72,50,-98,-96,78,86,6,32,-60},new int[]{-44,-52,-66,-46,24,80,-68,92,-32,26,-44,30,72,-56,-56,28,-26,22,-92},new int[]{82,-58,-60,-30,-68,-18,-72,98,92,-28,-30,44,78,10,54,56,2,-92,24},new int[]{4,96,-84,68,14,-86,6,22,-6,-60,2,-38,-48,48,-74,-52,-44,-68,-96},new int[]{46,4,16,20,-12,86,-56,88,8,-68,56,14,2,-38,-20,-42,-64,86,30},new int[]{96,68,-74,14,66,-20,72,60,56,-78,-14,2,60,16,-2,-90,-46,24,68},new int[]{-80,40,72,-88,-2,12,-96,-34,-88,94,46,-62,84,-68,14,-62,-26,-94,-66},new int[]{24,-60,-30,-22,-42,-2,-52,76,-16,26,-82,64,88,6,-42,-46,36,50,98},new int[]{-30,-16,-80,-16,-42,-6,60,-78,-94,-42,-20,44,-78,70,48,-84,-52,-22,46}}); param0.add(new int[][]{new int[]{0,0,0,0,0,0,0,0,0,1,1,1,1,1},new int[]{0,0,0,0,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,1,1,1,1,1},new int[]{0,0,0,0,0,0,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,1,1,1,1,1,1},new int[]{0,0,0,0,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,1,1,1,1,1,1,1},new int[]{0,0,0,1,1,1,1,1,1,1,1,1,1,1}}); param0.add(new int[][]{new int[]{58,85,97,21,67,89,63,21,3,59,28,4,57,94,75,40,26,76,91,6,64,58,31,26,69,56},new int[]{61,73,86,49,29,98,33,19,25,73,53,43,38,38,35,8,76,31,86,93,82,13,22,28,38,88},new int[]{36,22,61,11,68,82,29,74,11,31,71,46,70,47,91,56,26,34,52,41,82,3,21,59,15,3},new int[]{67,75,36,39,7,71,38,63,36,73,77,63,61,19,58,96,24,71,76,5,92,80,56,51,57,11},new int[]{81,94,93,62,55,71,63,25,30,12,82,98,12,57,44,59,67,18,56,20,37,80,66,57,34,64},new int[]{69,90,68,50,46,79,27,12,24,37,33,24,2,33,50,3,21,20,30,30,27,8,82,99,71,83},new int[]{4,52,66,74,99,99,10,51,25,84,50,37,10,56,36,42,92,89,70,67,17,89,44,63,1,34},new int[]{78,19,58,40,15,68,31,14,96,72,74,34,10,64,69,91,12,65,82,30,20,76,73,22,49,65},new int[]{11,46,64,46,13,96,43,95,47,18,45,16,69,36,53,50,24,68,43,91,31,48,47,1,91,44},new int[]{86,37,91,17,78,5,39,37,62,68,26,91,19,64,42,55,65,56,85,33,90,70,97,51,61,42},new int[]{47,84,97,98,53,58,83,86,30,42,4,72,67,32,50,37,43,92,40,6,1,98,25,16,36,18},new int[]{5,15,23,78,81,92,74,55,30,59,43,27,48,24,33,90,79,61,16,76,13,75,13,91,86,97},new int[]{50,81,63,53,30,92,83,19,43,90,40,66,2,92,72,35,87,11,26,55,26,92,80,79,68,73},new int[]{2,55,80,76,99,98,8,31,23,87,99,75,72,45,79,70,84,36,9,78,44,45,38,96,66,39},new int[]{78,28,1,62,38,69,48,57,89,60,15,7,67,99,63,37,65,27,1,8,17,15,1,39,11,49},new int[]{20,70,15,29,42,31,49,87,50,11,66,55,21,35,77,7,65,3,92,86,52,36,16,55,25,59},new int[]{24,90,55,67,66,96,58,49,21,1,39,30,65,55,57,64,98,27,90,65,43,26,10,77,86,9},new int[]{40,44,98,40,1,40,6,30,39,41,10,55,44,38,44,86,95,80,86,41,40,94,35,46,87,36},new int[]{30,21,73,92,41,17,19,71,53,19,80,65,93,1,69,48,95,54,81,52,50,72,91,9,73,74},new int[]{42,87,8,31,39,47,35,29,70,42,94,53,27,53,67,51,28,86,27,77,8,84,48,34,71,2},new int[]{84,68,18,85,35,63,98,68,95,24,85,10,23,88,15,70,15,46,46,52,4,72,21,75,11,21},new int[]{21,1,28,27,46,61,52,56,43,9,88,19,41,40,12,90,49,56,92,65,3,46,16,46,45,64},new int[]{65,27,31,4,16,63,97,48,45,39,37,7,89,99,19,93,57,16,25,43,80,27,70,63,50,69},new int[]{97,69,6,27,72,96,13,62,99,28,63,5,85,45,67,97,60,65,21,24,85,46,21,6,31,19},new int[]{89,76,25,93,74,3,97,44,8,25,95,57,65,17,32,72,31,85,38,53,76,1,58,41,87,76},new int[]{42,30,40,72,77,45,71,43,39,3,8,52,99,92,80,1,83,60,29,93,9,96,50,73,32,92}}); List<Integer> param1 = new ArrayList<>(); param1.add(14); param1.add(28); param1.add(28); param1.add(48); param1.add(14); param1.add(19); param1.add(6); param1.add(11); param1.add(8); param1.add(25); List<Integer> param2 = new ArrayList<>(); param2.add(17); param2.add(27); param2.add(16); param2.add(37); param2.add(7); param2.add(20); param2.add(5); param2.add(18); param2.add(10); param2.add(14); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,131
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_SUBSTRINGS_WITH_SAME_FIRST_AND_LAST_CHARACTERS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_SUBSTRINGS_WITH_SAME_FIRST_AND_LAST_CHARACTERS{ static int f_gold ( String s ) { int result = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( s . charAt ( i ) == s . charAt ( j ) ) result ++ ; return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("LZIKA"); param0.add("0556979952"); param0.add("110010"); param0.add("kGaYfd"); param0.add("413567670657"); param0.add("01001"); param0.add("EQPuFa"); param0.add("48848378"); param0.add("110"); param0.add("PLehNeP"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,132
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/DIFFERENCE_BETWEEN_HIGHEST_AND_LEAST_FREQUENCIES_IN_AN_ARRAY.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class DIFFERENCE_BETWEEN_HIGHEST_AND_LEAST_FREQUENCIES_IN_AN_ARRAY{ static int f_gold ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int count = 0 , max_count = 0 , min_count = n ; for ( int i = 0 ; i < ( n - 1 ) ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { count += 1 ; continue ; } else { max_count = Math . max ( max_count , count ) ; min_count = Math . min ( min_count , count ) ; count = 0 ; } } return ( max_count - min_count ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{5,15,19,22,28,29,39,46,46,49,51,55,62,69,72,72,72,74,79,92,92,93,95,96}); param0.add(new int[]{-26,-54,92,76,-92,-14,-24,-70,-78,-50,-48,-22,12,2,-34,-60,4,-32,-10,52,-92,-74,18,34,6,-66,42,-10,-6,56,92}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{59,35,13,79,61,97,92,48,98,38,65,54,31,49,81,22,96,29,65,48,92,66,25,21,26,1,32,73,46,5,40,17,53,93,83,29}); param0.add(new int[]{-70,-34,-32,-30,-14,80,86,90}); param0.add(new int[]{0,1,0,1,1,0,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,1,0}); param0.add(new int[]{9}); param0.add(new int[]{94,10,70,42}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{64,76,49,55,92,15,4,8,95,60,90,3,7,79,84,17,96,10,80,26,22,15}); List<Integer> param1 = new ArrayList<>(); param1.add(15); param1.add(30); param1.add(24); param1.add(29); param1.add(4); param1.add(23); param1.add(0); param1.add(2); param1.add(24); param1.add(20); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,133
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_WHETHER_NUMBER_DUCK_NUMBER_NOT.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_WHETHER_NUMBER_DUCK_NUMBER_NOT{ static int f_gold ( String num ) { int len = num . length ( ) ; int count_zero = 0 ; char ch ; for ( int i = 1 ; i < len ; i ++ ) { ch = num . charAt ( i ) ; if ( ch == '0' ) count_zero ++ ; } return count_zero ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("HLlQWSphZcIC"); param0.add("080287724"); param0.add("0000100000"); param0.add(" Q"); param0.add("4247040983"); param0.add("00001011101"); param0.add("LbNsnYTHmLbCf"); param0.add("24"); param0.add("110"); param0.add("ie"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,134
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/COUNT_SINGLE_NODE_ISOLATED_SUB_GRAPHS_DISCONNECTED_GRAPH.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_SINGLE_NODE_ISOLATED_SUB_GRAPHS_DISCONNECTED_GRAPH{ static int f_gold ( int [ ] graph , int N ) { int count = 0 ; for ( int i = 1 ; i < 7 ; i ++ ) { if ( graph [ i ] == 0 ) count ++ ; } return count ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{18,26,39,43,46,57,63,76,84,88}); param0.add(new int[]{76,-92,-40,48,84,8,28,64,84,-58,40,48,-8,22,84,-14,-32,-66,84,-74,10,50,96,92,-60,70,0,2,16,-26}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{15,76,11,70,34,54,4,33,20,93,51,9,58,50,23,97,42,28,98,3,21,39,20,11,38}); param0.add(new int[]{-96,-84,-74,-58,-52,-52,-28,-24,-22,-12,-12,-8,-6,-2,-2,8,10,20,24,32,36,36,46,54,66,88,94}); param0.add(new int[]{0,1,1,1,1,0,0,0,0,0,0,1,1,0,1,1,0,1,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,1,0,1,1,1,0,1}); param0.add(new int[]{1,1,4,9,13,18,18,21,22,32,33,39,41,44,51,55,56,59,60,61,63,68,69,71,72,73,74,74,75,81,83,87,88,92,94,97}); param0.add(new int[]{10,54,-64,30,-50,-4,14,-96,-22,80,-36,-36,-92,58,28,10,32,-82,-6,-40,0,-46,-68,-18,-16,-38,-22,-68,-82,76,70,-48,10,50,82,98,-22,-74,22,-60,-70,46,84,88,-34,-30,88,26}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{25,39,1,6,86,45,19,76,65,29,9}); List<Integer> param1 = new ArrayList<>(); param1.add(8); param1.add(15); param1.add(31); param1.add(12); param1.add(20); param1.add(24); param1.add(22); param1.add(35); param1.add(41); param1.add(7); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,135
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/AREA_SQUARE_CIRCUMSCRIBED_CIRCLE.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class AREA_SQUARE_CIRCUMSCRIBED_CIRCLE{ static int f_gold ( int r ) { return ( 2 * r * r ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(14); param0.add(78); param0.add(45); param0.add(66); param0.add(18); param0.add(32); param0.add(60); param0.add(16); param0.add(99); param0.add(65); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,136
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/NUMBER_NON_NEGATIVE_INTEGRAL_SOLUTIONS_B_C_N.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class NUMBER_NON_NEGATIVE_INTEGRAL_SOLUTIONS_B_C_N{ static int f_gold ( int n ) { int result = 0 ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n - i ; j ++ ) for ( int k = 0 ; k <= ( n - i - j ) ; k ++ ) if ( i + j + k == n ) result ++ ; return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(62); param0.add(44); param0.add(37); param0.add(81); param0.add(14); param0.add(20); param0.add(76); param0.add(72); param0.add(96); param0.add(52); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,137
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/CHECK_TWO_GIVEN_CIRCLES_TOUCH_INTERSECT.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_TWO_GIVEN_CIRCLES_TOUCH_INTERSECT{ static int f_gold ( int x1 , int y1 , int x2 , int y2 , int r1 , int r2 ) { int distSq = ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ; int radSumSq = ( r1 + r2 ) * ( r1 + r2 ) ; if ( distSq == radSumSq ) return 1 ; else if ( distSq > radSumSq ) return - 1 ; else return 0 ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(11); param0.add(87); param0.add(51); param0.add(89); param0.add(64); param0.add(57); param0.add(65); param0.add(32); param0.add(73); param0.add(3); List<Integer> param1 = new ArrayList<>(); param1.add(36); param1.add(1); param1.add(1); param1.add(67); param1.add(10); param1.add(86); param1.add(90); param1.add(23); param1.add(61); param1.add(99); List<Integer> param2 = new ArrayList<>(); param2.add(62); param2.add(62); param2.add(47); param2.add(9); param2.add(79); param2.add(99); param2.add(42); param2.add(28); param2.add(63); param2.add(6); List<Integer> param3 = new ArrayList<>(); param3.add(64); param3.add(64); param3.add(90); param3.add(52); param3.add(45); param3.add(43); param3.add(82); param3.add(26); param3.add(77); param3.add(19); List<Integer> param4 = new ArrayList<>(); param4.add(50); param4.add(54); param4.add(14); param4.add(94); param4.add(67); param4.add(83); param4.add(77); param4.add(60); param4.add(92); param4.add(21); List<Integer> param5 = new ArrayList<>(); param5.add(4); param5.add(41); param5.add(71); param5.add(21); param5.add(78); param5.add(63); param5.add(32); param5.add(45); param5.add(76); param5.add(28); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i),param3.get(i),param4.get(i),param5.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i),param3.get(i),param4.get(i),param5.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,138
0
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts
Create_ds/TransCoder/data/evaluation/geeks_for_geeks_successful_test_scripts/java/MINIMUM_NUMBER_PLATFORMS_REQUIRED_RAILWAYBUS_STATION.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MINIMUM_NUMBER_PLATFORMS_REQUIRED_RAILWAYBUS_STATION{ static int f_gold ( int arr [ ] , int dep [ ] , int n ) { Arrays . sort ( arr ) ; Arrays . sort ( dep ) ; int plat_needed = 1 , result = 1 ; int i = 1 , j = 0 ; while ( i < n && j < n ) { if ( arr [ i ] <= dep [ j ] ) { plat_needed ++ ; i ++ ; if ( plat_needed > result ) result = plat_needed ; } else { plat_needed -- ; j ++ ; } } return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{8,24,28,64,75,86,93,95}); param0.add(new int[]{2,-30,-8,-78,58,-42,-94,84,-58,14,78,34,30,6,-18,-92,0,94,-54,58,0,-86,66,86,8,-26,50,16,-30,-68,98,-28,-4,-6}); param0.add(new int[]{0,0,0,0,0,0,1}); param0.add(new int[]{51,5,48,61,71,2,4,35,50,76,59,64,81,5,21,95}); param0.add(new int[]{-64,-52,44,52,90}); param0.add(new int[]{0,0,1,0,1,0,1,1,0,1,1,1,0,1,0,1,0,1,0,0,0,1,1,1,0,1,0,1,1,1}); param0.add(new int[]{2,15,25,55,72,96,98}); param0.add(new int[]{-60,30,-58,52,40,74,74,76,-72,-48,8,-56,-24,-40,-98,-76,-56,-20,30,-30,-34,4,-34}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{37,84,20,34,56,1,87,72}); List<int [ ]> param1 = new ArrayList<>(); param1.add(new int[]{19,30,41,51,62,68,85,96}); param1.add(new int[]{40,22,-24,80,-76,-4,-8,-34,96,-98,16,28,14,52,10,-10,-62,64,-48,10,-64,-90,-52,46,34,50,50,-84,68,-12,-44,28,-22,78}); param1.add(new int[]{0,0,0,0,0,1,1}); param1.add(new int[]{67,84,86,43,50,90,49,8,40,67,5,51,40,28,31,47}); param1.add(new int[]{-62,-16,22,26,58}); param1.add(new int[]{0,0,1,1,1,0,1,1,0,0,0,0,1,1,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0}); param1.add(new int[]{3,6,11,19,26,37,39}); param1.add(new int[]{-96,-40,-76,52,-20,-28,-64,-72,36,56,52,34,14,8,-50,6,-82,-98,-8,18,-76,-66,-22}); param1.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param1.add(new int[]{68,62,84,54,15,29,70,96}); List<Integer> param2 = new ArrayList<>(); param2.add(6); param2.add(18); param2.add(6); param2.add(8); param2.add(3); param2.add(17); param2.add(6); param2.add(20); param2.add(22); param2.add(6); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
4,139
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/ServerZkClientTest.java
package org.I0Itec.zkclient; import org.I0Itec.zkclient.exception.ZkBadVersionException; import org.I0Itec.zkclient.exception.ZkInterruptedException; import org.I0Itec.zkclient.exception.ZkNoNodeException; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.apache.curator.test.TestingServer; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.data.Stat; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class ServerZkClientTest extends AbstractBaseZkClientTest { @Override @Before public void setUp() throws Exception { super.setUp(); _zkServer = new TestingServer(4711); _client = ZkTestSystem.createZkClient("localhost:4711"); } @Override @After public void tearDown() throws Exception { super.tearDown(); _client.close(); _zkServer.close(); } @Test(timeout = 15000) public void testRetryUntilConnected() throws Exception { LOG.info("--- testRetryUntilConnected"); Gateway gateway = new Gateway(4712, 4711); gateway.start(); final IZkConnection zkConnection = ZkTestSystem.createZkConnection("localhost:4712"); final ZkClient zkClient = new ZkClient(zkConnection, 5000); gateway.stop(); // start server in 250ms new DeferredGatewayStarter(gateway, 250).start(); // this should work as soon as the connection is reestablished, if it // fails it throws a ConnectionLossException zkClient.retryUntilConnected(new Callable<Object>() { @Override public Object call() throws Exception { zkConnection.exists("/a", false); return null; } }); zkClient.close(); gateway.stop(); } @Test(timeout = 15000) public void testWaitUntilConnected() throws Exception { LOG.info("--- testWaitUntilConnected"); ZkClient _client = ZkTestSystem.createZkClient("localhost:4711"); _zkServer.close(); // the _client state should change to KeeperState.Disconnected assertTrue(_client.waitForKeeperState(KeeperState.Disconnected, 1, TimeUnit.SECONDS)); // connection should not be possible and timeout after 100ms assertFalse(_client.waitUntilConnected(100, TimeUnit.MILLISECONDS)); } /* JLZ - can't emulate @Test(timeout = 15000) public void testRetryUntilConnected_SessionExpiredException() { LOG.info("--- testRetryUntilConnected_SessionExpiredException"); // Use a tick time of 100ms, because the minimum session timeout is 2 x tick-time. // ZkServer zkServer = TestUtil.startZkServer("ZkClientTest-testSessionExpiredException", 4711, 100); Gateway gateway = new Gateway(4712, 4711); gateway.start(); // Use a session timeout of 200ms final ZkClient zkClient = ZkTestSystem.createZkClient("localhost:4712", 200, 5000); gateway.stop(); // Start server in 600ms, the session should have expired by then new DeferredGatewayStarter(gateway, 600).start(); // This should work as soon as a new session has been created (and the connection is reestablished), if it fails // it throws a SessionExpiredException zkClient.retryUntilConnected(new Callable<Object>() { @Override public Object call() throws Exception { zkClient.exists("/a"); return null; } }); zkClient.close(); // zkServer.shutdown(); gateway.stop(); } */ /* JLZ - can't emulate @Test(timeout = 15000) public void testChildListenerAfterSessionExpiredException() throws Exception { LOG.info("--- testChildListenerAfterSessionExpiredException"); int sessionTimeout = 200; ZkClient connectedClient = _zkServer.getZkClient(); connectedClient.createPersistent("/root"); Gateway gateway = new Gateway(4712, 4711); gateway.start(); final ZkClient disconnectedZkClient = new ZkClient("localhost:4712", sessionTimeout, 5000); final Holder<List<String>> children = new Holder<List<String>>(); disconnectedZkClient.subscribeChildChanges("/root", new IZkChildListener() { @Override public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { children.set(currentChilds); } }); gateway.stop(); // The connected client now created a new child node connectedClient.createPersistent("/root/node"); // Wait for 3 x sessionTimeout, the session should have expired by then and start the gateway again Thread.sleep(sessionTimeout * 3); gateway.start(); Boolean hasOneChild = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return children.get() != null && children.get().size() == 1; } }, TimeUnit.SECONDS, 5); assertTrue(hasOneChild); disconnectedZkClient.close(); gateway.stop(); } */ @Test(timeout = 10000) public void testZkClientConnectedToGatewayClosesQuickly() throws Exception { LOG.info("--- testZkClientConnectedToGatewayClosesQuickly"); final Gateway gateway = new Gateway(4712, 4711); gateway.start(); ZkClient zkClient = ZkTestSystem.createZkClient("localhost:4712"); zkClient.close(); gateway.stop(); } @Test public void testCountChildren() throws InterruptedException { assertEquals(0, _client.countChildren("/a")); _client.createPersistent("/a"); assertEquals(0, _client.countChildren("/a")); _client.createPersistent("/a/b"); assertEquals(1, _client.countChildren("/a")); // test concurrent access Thread thread = new Thread() { @Override public void run() { try { while (!isInterrupted()) { _client.createPersistent("/test"); _client.delete("/test"); } } catch (ZkInterruptedException e) { // ignore and finish } } }; thread.start(); for (int i = 0; i < 1000; i++) { assertEquals(0, _client.countChildren("/test")); } thread.interrupt(); thread.join(); } @Test public void testReadDataWithStat() { _client.createPersistent("/a", "data"); Stat stat = new Stat(); _client.readData("/a", stat); assertEquals(0, stat.getVersion()); assertTrue(stat.getDataLength() > 0); } @Test public void testWriteDataWithExpectedVersion() { _client.createPersistent("/a", "data"); _client.writeData("/a", "data2", 0); try { _client.writeData("/a", "data3", 0); fail("expected exception"); } catch (ZkBadVersionException e) { // expected } } @Test public void testCreateWithParentDirs() { String path = "/a/b"; try { _client.createPersistent(path, false); fail("should throw exception"); } catch (ZkNoNodeException e) { assertFalse(_client.exists(path)); } _client.createPersistent(path, true); assertTrue(_client.exists(path)); } @Test public void testUpdateSerialized() throws InterruptedException { _client.createPersistent("/a", 0); int numberOfThreads = 2; final int numberOfIncrementsPerThread = 100; List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < numberOfThreads; i++) { Thread thread = new Thread() { @Override public void run() { for (int j = 0; j < numberOfIncrementsPerThread; j++) { _client.updateDataSerialized("/a", new DataUpdater<Integer>() { @Override public Integer update(Integer integer) { return integer + 1; } }); } } }; thread.start(); threads.add(thread); } for (Thread thread : threads) { thread.join(); } Integer finalValue = _client.readData("/a"); assertEquals(numberOfIncrementsPerThread * numberOfThreads, finalValue.intValue()); } }
4,140
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/DeferredGatewayStarter.java
package org.I0Itec.zkclient; public class DeferredGatewayStarter extends Thread { private final Gateway _zkServer; private int _delay; public DeferredGatewayStarter(Gateway gateway, int delay) { _zkServer = gateway; _delay = delay; } @Override public void run() { try { Thread.sleep(_delay); _zkServer.start(); } catch (Exception e) { // ignore } } }
4,141
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/AbstractBaseZkClientTest.java
package org.I0Itec.zkclient; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.apache.curator.test.TestingServer; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; public abstract class AbstractBaseZkClientTest { protected static final Logger LOG = Logger.getLogger(AbstractBaseZkClientTest.class); protected TestingServer _zkServer; protected ZkClient _client; @Before public void setUp() throws Exception { LOG.info("------------ BEFORE -------------"); } @After public void tearDown() throws Exception { LOG.info("------------ AFTER -------------"); } @Test(expected = RuntimeException.class, timeout = 15000) public void testUnableToConnect() throws Exception { LOG.info("--- testUnableToConnect"); // we are using port 4711 to avoid conflicts with the zk server that is // started by the Spring context ZkTestSystem.createZkClient("localhost:4712"); } @Test public void testWriteAndRead() throws Exception { LOG.info("--- testWriteAndRead"); String data = "something"; String path = "/a"; _client.createPersistent(path, data); String data2 = _client.readData(path); Assert.assertEquals(data, data2); _client.delete(path); } @Test public void testDelete() throws Exception { LOG.info("--- testDelete"); String path = "/a"; assertFalse(_client.delete(path)); _client.createPersistent(path, null); assertTrue(_client.delete(path)); assertFalse(_client.delete(path)); } @Test public void testDeleteRecursive() throws Exception { LOG.info("--- testDeleteRecursive"); // should be able to call this on a not existing directory _client.deleteRecursive("/doesNotExist"); } @Test public void testWaitUntilExists() { LOG.info("--- testWaitUntilExists"); // create /gaga node asynchronously new Thread() { @Override public void run() { try { Thread.sleep(100); _client.createPersistent("/gaga"); } catch (Exception e) { // ignore } } }.start(); // wait until this was created assertTrue(_client.waitUntilExists("/gaga", TimeUnit.SECONDS, 5)); assertTrue(_client.exists("/gaga")); // waiting for /neverCreated should timeout assertFalse(_client.waitUntilExists("/neverCreated", TimeUnit.MILLISECONDS, 100)); } @Test public void testDataChanges1() throws Exception { LOG.info("--- testDataChanges1"); String path = "/a"; final Holder<String> holder = new Holder<String>(); IZkDataListener listener = new IZkDataListener() { @Override public void handleDataChange(String dataPath, Object data) throws Exception { holder.set((String) data); } @Override public void handleDataDeleted(String dataPath) throws Exception { holder.set(null); } }; _client.subscribeDataChanges(path, listener); _client.createPersistent(path, "aaa"); // wait some time to make sure the event was triggered String contentFromHolder = TestUtil.waitUntil("b", new Callable<String>() { @Override public String call() throws Exception { return holder.get(); } }, TimeUnit.SECONDS, 5); assertEquals("aaa", contentFromHolder); } @Test public void testDataChanges2() throws Exception { LOG.info("--- testDataChanges2"); String path = "/a"; final AtomicInteger countChanged = new AtomicInteger(0); final AtomicInteger countDeleted = new AtomicInteger(0); IZkDataListener listener = new IZkDataListener() { @Override public void handleDataChange(String dataPath, Object data) throws Exception { countChanged.incrementAndGet(); } @Override public void handleDataDeleted(String dataPath) throws Exception { countDeleted.incrementAndGet(); } }; _client.subscribeDataChanges(path, listener); // create node _client.createPersistent(path, "aaa"); // wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, 5); assertEquals(1, countChanged.get()); assertEquals(0, countDeleted.get()); countChanged.set(0); countDeleted.set(0); // delete node, this should trigger a delete event _client.delete(path); // wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countDeleted.get(); } }, TimeUnit.SECONDS, 5); assertEquals(0, countChanged.get()); assertEquals(1, countDeleted.get()); // test if watch was reinstalled after the file got deleted countChanged.set(0); _client.createPersistent(path, "aaa"); // wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, 5); assertEquals(1, countChanged.get()); // test if changing the contents notifies the listener _client.writeData(path, "bbb"); // wait some time to make sure the event was triggered TestUtil.waitUntil(2, new Callable<Integer>() { @Override public Integer call() throws Exception { return countChanged.get(); } }, TimeUnit.SECONDS, 5); assertEquals(2, countChanged.get()); } @Test(timeout = 15000) public void testHandleChildChanges() throws Exception { LOG.info("--- testHandleChildChanges"); String path = "/a"; final AtomicInteger count = new AtomicInteger(0); final Holder<List<String>> children = new Holder<List<String>>(); IZkChildListener listener = new IZkChildListener() { @Override public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { count.incrementAndGet(); children.set(currentChilds); } }; _client.subscribeChildChanges(path, listener); // ---- // Create the root node should throw the first child change event // ---- _client.createPersistent(path); // wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return count.get(); } }, TimeUnit.SECONDS, 5); assertEquals(1, count.get()); assertEquals(0, children.get().size()); // ---- // Creating a child node should throw another event // ---- count.set(0); _client.createPersistent(path + "/child1"); // wait some time to make sure the event was triggered TestUtil.waitUntil(1, new Callable<Integer>() { @Override public Integer call() throws Exception { return count.get(); } }, TimeUnit.SECONDS, 5); assertEquals(1, count.get()); assertEquals(1, children.get().size()); assertEquals("child1", children.get().get(0)); // ---- // Creating another child and deleting the node should also throw an event // ---- count.set(0); _client.createPersistent(path + "/child2"); _client.deleteRecursive(path); // wait some time to make sure the event was triggered Boolean eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0 && children.get() == null; } }, TimeUnit.SECONDS, 5); assertTrue(eventReceived); assertNull(children.get()); // ---- // Creating root again should throw an event // ---- count.set(0); _client.createPersistent(path); // wait some time to make sure the event was triggered eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0 && children.get() != null; } }, TimeUnit.SECONDS, 5); assertTrue(eventReceived); assertEquals(0, children.get().size()); // ---- // Creating child now should throw an event // ---- count.set(0); _client.createPersistent(path + "/child"); // wait some time to make sure the event was triggered eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0; } }, TimeUnit.SECONDS, 5); assertTrue(eventReceived); assertEquals(1, children.get().size()); assertEquals("child", children.get().get(0)); // ---- // Deleting root node should throw an event // ---- count.set(0); _client.deleteRecursive(path); // wait some time to make sure the event was triggered eventReceived = TestUtil.waitUntil(true, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return count.get() > 0 && children.get() == null; } }, TimeUnit.SECONDS, 5); assertTrue(eventReceived); assertNull(children.get()); } @Test public void testGetCreationTime() throws Exception { long start = System.currentTimeMillis(); Thread.sleep(100); String path = "/a"; _client.createPersistent(path); Thread.sleep(100); long end = System.currentTimeMillis(); long creationTime = _client.getCreationTime(path); assertTrue(start < creationTime && end > creationTime); } @Test public void testNumberOfListeners() { IZkChildListener zkChildListener = mock(IZkChildListener.class); _client.subscribeChildChanges("/", zkChildListener); assertEquals(1, _client.numberOfListeners()); IZkDataListener zkDataListener = mock(IZkDataListener.class); _client.subscribeDataChanges("/a", zkDataListener); assertEquals(2, _client.numberOfListeners()); _client.subscribeDataChanges("/b", zkDataListener); assertEquals(3, _client.numberOfListeners()); IZkStateListener zkStateListener = mock(IZkStateListener.class); _client.subscribeStateChanges(zkStateListener); assertEquals(4, _client.numberOfListeners()); _client.unsubscribeChildChanges("/", zkChildListener); assertEquals(3, _client.numberOfListeners()); _client.unsubscribeDataChanges("/b", zkDataListener); assertEquals(2, _client.numberOfListeners()); _client.unsubscribeDataChanges("/a", zkDataListener); assertEquals(1, _client.numberOfListeners()); _client.unsubscribeStateChanges(zkStateListener); assertEquals(0, _client.numberOfListeners()); } }
4,142
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/ZkClientSerializationTest.java
package org.I0Itec.zkclient; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.util.Random; import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer; import org.I0Itec.zkclient.serialize.SerializableSerializer; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.junit.Rule; import org.junit.Test; public class ZkClientSerializationTest { @Rule public ZkTestSystem _zk = ZkTestSystem.getInstance(); @Test public void testBytes() throws Exception { ZkClient zkClient = ZkTestSystem.createZkClient(_zk.getZkServerAddress()); zkClient.setZkSerializer(new BytesPushThroughSerializer()); byte[] bytes = new byte[100]; new Random().nextBytes(bytes); zkClient.createPersistent("/a", bytes); byte[] readBytes = zkClient.readData("/a"); assertArrayEquals(bytes, readBytes); } @Test public void testSerializables() throws Exception { ZkClient zkClient = ZkTestSystem.createZkClient(_zk.getZkServerAddress()); zkClient.setZkSerializer(new SerializableSerializer()); String data = "hello world"; zkClient.createPersistent("/a", data); String readData = zkClient.readData("/a"); assertEquals(data, readData); } }
4,143
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/AbstractConnectionTest.java
package org.I0Itec.zkclient; import org.I0Itec.zkclient.testutil.ZkPathUtil; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; public abstract class AbstractConnectionTest { private final IZkConnection _connection; public AbstractConnectionTest(IZkConnection connection) { _connection = connection; } @Test public void testGetChildren_OnEmptyFileSystem() throws KeeperException, InterruptedException { InMemoryConnection connection = new InMemoryConnection(); List<String> children = connection.getChildren("/", false); assertEquals(0, children.size()); } @Test @Ignore("I don't understand this test -JZ") public void testSequentials() throws KeeperException, InterruptedException { String sequentialPath = _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL); int firstSequential = Integer.parseInt(sequentialPath.substring(2)); assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), sequentialPath); assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.PERSISTENT_SEQUENTIAL)); assertEquals("/b" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/b", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); assertEquals("/b" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/b", new byte[0], CreateMode.PERSISTENT_SEQUENTIAL)); assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); } }
4,144
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/DistributedQueueTest.java
package org.I0Itec.zkclient; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.apache.curator.test.TestingServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class DistributedQueueTest { private TestingServer _zkServer; private ZkClient _zkClient; @Before public void setUp() throws Exception { _zkServer = new TestingServer(4711); _zkClient = ZkTestSystem.createZkClient(_zkServer.getConnectString()); } @After public void tearDown() throws IOException { if (_zkClient != null) { _zkClient.close(); } if (_zkServer != null) { _zkServer.close(); } } @Test(timeout = 15000) public void testDistributedQueue() { _zkClient.createPersistent("/queue"); DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue"); distributedQueue.offer(17L); distributedQueue.offer(18L); distributedQueue.offer(19L); assertEquals(Long.valueOf(17L), distributedQueue.poll()); assertEquals(Long.valueOf(18L), distributedQueue.poll()); assertEquals(Long.valueOf(19L), distributedQueue.poll()); assertNull(distributedQueue.poll()); } @Test(timeout = 15000) public void testPeek() { _zkClient.createPersistent("/queue"); DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue"); distributedQueue.offer(17L); distributedQueue.offer(18L); assertEquals(Long.valueOf(17L), distributedQueue.peek()); assertEquals(Long.valueOf(17L), distributedQueue.peek()); assertEquals(Long.valueOf(17L), distributedQueue.poll()); assertEquals(Long.valueOf(18L), distributedQueue.peek()); assertEquals(Long.valueOf(18L), distributedQueue.poll()); assertNull(distributedQueue.peek()); } @Test(timeout = 30000) public void testMultipleReadingThreads() throws InterruptedException { _zkClient.createPersistent("/queue"); final DistributedQueue<Long> distributedQueue = new DistributedQueue<Long>(_zkClient, "/queue"); // insert 100 elements for (int i = 0; i < 100; i++) { distributedQueue.offer(new Long(i)); } // 3 reading threads final Set<Long> readElements = Collections.synchronizedSet(new HashSet<Long>()); List<Thread> threads = new ArrayList<Thread>(); final List<Exception> exceptions = new Vector<Exception>(); for (int i = 0; i < 3; i++) { Thread thread = new Thread() { @Override public void run() { try { while (true) { Long value = distributedQueue.poll(); if (value == null) { return; } readElements.add(value); } } catch (Exception e) { exceptions.add(e); e.printStackTrace(); } } }; threads.add(thread); thread.start(); } for (Thread thread : threads) { thread.join(); } assertEquals(0, exceptions.size()); assertEquals(100, readElements.size()); } }
4,145
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/MemoryZkClientTest.java
package org.I0Itec.zkclient; import org.apache.zookeeper.CreateMode; import org.junit.Assert; import org.junit.Test; public class MemoryZkClientTest extends AbstractBaseZkClientTest { @Override public void setUp() throws Exception { super.setUp(); _client = new ZkClient(new InMemoryConnection()); } @Override public void tearDown() throws Exception { super.tearDown(); _client.close(); } @Test public void testGetChildren() throws Exception { String path1 = "/a"; String path2 = "/a/a"; String path3 = "/a/a/a"; _client.create(path1, null, CreateMode.PERSISTENT); _client.create(path2, null, CreateMode.PERSISTENT); _client.create(path3, null, CreateMode.PERSISTENT); Assert.assertEquals(1, _client.getChildren(path1).size()); Assert.assertEquals(1, _client.getChildren(path2).size()); Assert.assertEquals(0, _client.getChildren(path3).size()); } }
4,146
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/ContentWatcherTest.java
package org.I0Itec.zkclient; import static org.junit.Assert.assertEquals; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.apache.curator.test.TestingServer; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ContentWatcherTest { private static final Logger LOG = Logger.getLogger(ContentWatcherTest.class); private static final String FILE_NAME = "/ContentWatcherTest"; private TestingServer _zkServer; private ZkClient _zkClient; @Before public void setUp() throws Exception { LOG.info("------------ BEFORE -------------"); _zkServer = new TestingServer(4711); _zkClient = ZkTestSystem.createZkClient(_zkServer.getConnectString()); } @After public void tearDown() throws Exception { if (_zkClient != null) { _zkClient.close(); } if (_zkServer != null) { _zkServer.close(); } LOG.info("------------ AFTER -------------"); } @Test public void testGetContent() throws Exception { LOG.info("--- testGetContent"); _zkClient.createPersistent(FILE_NAME, "a"); final ContentWatcher<String> watcher = new ContentWatcher<String>(_zkClient, FILE_NAME); watcher.start(); assertEquals("a", watcher.getContent()); // update the content _zkClient.writeData(FILE_NAME, "b"); String contentFromWatcher = TestUtil.waitUntil("b", new Callable<String>() { @Override public String call() throws Exception { return watcher.getContent(); } }, TimeUnit.SECONDS, 5); assertEquals("b", contentFromWatcher); watcher.stop(); } @Test public void testGetContentWaitTillCreated() throws InterruptedException { LOG.info("--- testGetContentWaitTillCreated"); final Holder<String> contentHolder = new Holder<String>(); Thread thread = new Thread() { @Override public void run() { ContentWatcher<String> watcher = new ContentWatcher<String>(_zkClient, FILE_NAME); try { watcher.start(); contentHolder.set(watcher.getContent()); watcher.stop(); } catch (Exception e) { e.printStackTrace(); } } }; thread.start(); // create content after 200ms Thread.sleep(200); _zkClient.createPersistent(FILE_NAME, "aaa"); // we give the thread some time to pick up the change thread.join(1000); assertEquals("aaa", contentHolder.get()); } @Test public void testHandlingNullContent() throws InterruptedException { LOG.info("--- testHandlingNullContent"); _zkClient.createPersistent(FILE_NAME, null); ContentWatcher<String> watcher = new ContentWatcher<String>(_zkClient, FILE_NAME); watcher.start(); assertEquals(null, watcher.getContent()); watcher.stop(); } @Test(timeout = 20000) public void testHandlingOfConnectionLoss() throws Exception { LOG.info("--- testHandlingOfConnectionLoss"); final Gateway gateway = new Gateway(4712, 4711); gateway.start(); final ZkClient zkClient = ZkTestSystem.createZkClient("localhost:4712"); // disconnect gateway.stop(); // reconnect after 250ms and create file with content new Thread() { @Override public void run() { try { Thread.sleep(250); gateway.start(); zkClient.createPersistent(FILE_NAME, "aaa"); zkClient.writeData(FILE_NAME, "b"); } catch (Exception e) { // ignore } } }.start(); final ContentWatcher<String> watcher = new ContentWatcher<String>(zkClient, FILE_NAME); watcher.start(); TestUtil.waitUntil("b", new Callable<String>() { @Override public String call() throws Exception { return watcher.getContent(); } }, TimeUnit.SECONDS, 5); assertEquals("b", watcher.getContent()); watcher.stop(); zkClient.close(); gateway.stop(); } }
4,147
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/InMemoryConnectionTest.java
package org.I0Itec.zkclient; public class InMemoryConnectionTest extends AbstractConnectionTest { public InMemoryConnectionTest() { super(new InMemoryConnection()); } }
4,148
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/ZkConnectionTest.java
package org.I0Itec.zkclient; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.junit.Rule; public class ZkConnectionTest extends AbstractConnectionTest { @Rule public ZkTestSystem _zk = ZkTestSystem.getInstance(); public ZkConnectionTest() { super(establishConnection()); } private static IZkConnection establishConnection() { IZkConnection zkConnection = ZkTestSystem.createZkConnection("localhost:" + ZkTestSystem.getInstance().getZkServer().getPort()); new ZkClient(zkConnection);// connect return zkConnection; } }
4,149
0
Create_ds/curator/src/test/java/org/I0Itec
Create_ds/curator/src/test/java/org/I0Itec/zkclient/TestUtil.java
package org.I0Itec.zkclient; import org.mockito.exceptions.base.MockitoAssertionError; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; public class TestUtil { /** * This waits until the provided {@link Callable} returns an object that is equals to the given expected value or * the timeout has been reached. In both cases this method will return the return value of the latest * {@link Callable} execution. * * @param expectedValue * The expected value of the callable. * @param callable * The callable. * @param <T> * The return type of the callable. * @param timeUnit * The timeout timeunit. * @param timeout * The timeout. * @return the return value of the latest {@link Callable} execution. * @throws Exception * @throws InterruptedException */ public static <T> T waitUntil(T expectedValue, Callable<T> callable, TimeUnit timeUnit, long timeout) throws Exception { long startTime = System.currentTimeMillis(); do { T actual = callable.call(); if (expectedValue.equals(actual)) { return actual; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { return actual; } Thread.sleep(50); } while (true); } /** * This waits until a mockito verification passed (which is provided in the runnable). This waits until the * virification passed or the timeout has been reached. If the timeout has been reached this method will rethrow the * {@link MockitoAssertionError} that comes from the mockito verification code. * * @param runnable * The runnable containing the mockito verification. * @param timeUnit * The timeout timeunit. * @param timeout * The timeout. * @throws InterruptedException */ public static void waitUntilVerified(Runnable runnable, TimeUnit timeUnit, int timeout) throws InterruptedException { long startTime = System.currentTimeMillis(); do { MockitoAssertionError exception = null; try { runnable.run(); } catch (MockitoAssertionError e) { exception = e; } if (exception == null) { return; } if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { throw exception; } Thread.sleep(50); } while (true); } }
4,150
0
Create_ds/curator/src/test/java/org/I0Itec/zkclient
Create_ds/curator/src/test/java/org/I0Itec/zkclient/util/ZkPathUtilTest.java
package org.I0Itec.zkclient.util; import junit.framework.TestCase; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.testutil.ZkPathUtil; import org.I0Itec.zkclient.testutil.ZkTestSystem; import org.apache.curator.test.TestingServer; public class ZkPathUtilTest extends TestCase { protected TestingServer _zkServer; protected ZkClient _client; public void testToString() throws Exception { _zkServer = new TestingServer(4711); _client = ZkTestSystem.createZkClient("localhost:4711"); final String file1 = "/files/file1"; final String file2 = "/files/file2"; final String file3 = "/files/file2/file3"; _client.createPersistent(file1, true); _client.createPersistent(file2, true); _client.createPersistent(file3, true); String stringRepresentation = ZkPathUtil.toString(_client); System.out.println(stringRepresentation); System.out.println("-------------------------"); assertTrue(stringRepresentation.contains("file1")); assertTrue(stringRepresentation.contains("file2")); assertTrue(stringRepresentation.contains("file3")); // path filtering stringRepresentation = ZkPathUtil.toString(_client, "/", new ZkPathUtil.PathFilter() { @Override public boolean showChilds(String path) { return !file2.equals(path); } }); assertTrue(stringRepresentation.contains("file1")); assertTrue(stringRepresentation.contains("file2")); assertFalse(stringRepresentation.contains("file3")); // start path stringRepresentation = ZkPathUtil.toString(_client, file2, ZkPathUtil.PathFilter.ALL); assertFalse(stringRepresentation.contains("file1")); assertTrue(stringRepresentation.contains("file2")); assertTrue(stringRepresentation.contains("file3")); _zkServer.close(); } public void testLeadingZeros() throws Exception { assertEquals("0000000001", ZkPathUtil.leadingZeros(1, 10)); } }
4,151
0
Create_ds/curator/src/test/java/org/I0Itec/zkclient
Create_ds/curator/src/test/java/org/I0Itec/zkclient/testutil/ZkTestSystem.java
package org.I0Itec.zkclient.testutil; import com.netflix.curator.x.zkclientbridge.CuratorZKClientBridge; import org.I0Itec.zkclient.IZkConnection; import org.I0Itec.zkclient.ZkClient; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.log4j.Logger; import org.junit.rules.ExternalResource; import java.io.IOException; import java.util.List; public class ZkTestSystem extends ExternalResource { protected static final Logger LOG = Logger.getLogger(ZkTestSystem.class); private static int PORT = 10002; private static ZkTestSystem _instance; private TestingServer _zkServer; private ZkClient _zkClient; private ZkTestSystem() { LOG.info("~~~~~~~~~~~~~~~ starting zk system ~~~~~~~~~~~~~~~"); try { _zkServer = new TestingServer(PORT); _zkClient = ZkTestSystem.createZkClient(_zkServer.getConnectString()); } catch ( Exception e ) { throw new RuntimeException(e); } LOG.info("~~~~~~~~~~~~~~~ zk system started ~~~~~~~~~~~~~~~"); } @Override // executed before every test method protected void before() throws Throwable { cleanupZk(); } @Override // executed after every test method protected void after() { cleanupZk(); } private void cleanupZk() { LOG.info("cleanup zk namespace"); List<String> children = getZkClient().getChildren("/"); for (String child : children) { if (!child.equals("zookeeper")) { getZkClient().deleteRecursive("/" + child); } } LOG.info("unsubscribing " + getZkClient().numberOfListeners() + " listeners"); getZkClient().unsubscribeAll(); } public static ZkTestSystem getInstance() { if (_instance == null) { _instance = new ZkTestSystem(); _instance.cleanupZk(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info("shutting zk down"); try { getInstance().getZkClient().close(); getInstance().getZkServer().close(); } catch ( IOException e ) { throw new RuntimeException(e); } } }); } return _instance; } public TestingServer getZkServer() { return _zkServer; } public String getZkServerAddress() { return "localhost:" + getServerPort(); } public ZkClient getZkClient() { return _zkClient; } public int getServerPort() { return PORT; } public static IZkConnection createZkConnection(String connectString) { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { return new CuratorZKClientBridge(client); } catch ( Exception e ) { throw new RuntimeException(e); } } public static ZkClient createZkClient(String connectString) { try { Timing timing = new Timing(); return new ZkClient(createZkConnection(connectString), timing.connection()); } catch ( Exception e ) { throw new RuntimeException(e); } } public ZkClient createZkClient() { return createZkClient("localhost:" + PORT); } public void showStructure() { getZkClient().showFolders(System.out); } }
4,152
0
Create_ds/curator/src/test/java/org/I0Itec/zkclient
Create_ds/curator/src/test/java/org/I0Itec/zkclient/testutil/ZkPathUtil.java
package org.I0Itec.zkclient.testutil; import org.I0Itec.zkclient.ZkClient; import java.util.List; // JLZ - copied from https://raw.github.com/sgroschupf/zkclient/master/src/main/java/org/I0Itec/zkclient/util/ZkPathUtil.java public class ZkPathUtil { public static String leadingZeros(long number, int numberOfLeadingZeros) { return String.format("%0" + numberOfLeadingZeros + "d", number); } public static String toString(ZkClient zkClient) { return toString(zkClient, "/", PathFilter.ALL); } public static String toString(ZkClient zkClient, String startPath, PathFilter pathFilter) { final int level = 1; final StringBuilder builder = new StringBuilder("+ (" + startPath + ")"); builder.append("\n"); addChildrenToStringBuilder(zkClient, pathFilter, level, builder, startPath); return builder.toString(); } private static void addChildrenToStringBuilder(ZkClient zkClient, PathFilter pathFilter, final int level, final StringBuilder builder, final String startPath) { final List<String> children = zkClient.getChildren(startPath); for (final String node : children) { String nestedPath; if (startPath.endsWith("/")) { nestedPath = startPath + node; } else { nestedPath = startPath + "/" + node; } if (pathFilter.showChilds(nestedPath)) { builder.append(getSpaces(level - 1) + "'-" + "+" + node + "\n"); addChildrenToStringBuilder(zkClient, pathFilter, level + 1, builder, nestedPath); } else { builder.append(getSpaces(level - 1) + "'-" + "-" + node + " (contents hidden)\n"); } } } private static String getSpaces(final int level) { String s = ""; for (int i = 0; i < level; i++) { s += " "; } return s; } public static interface PathFilter { public static PathFilter ALL = new PathFilter() { @Override public boolean showChilds(String path) { return true; } }; boolean showChilds(String path); } }
4,153
0
Create_ds/curator/src/main/java/com/netflix/curator/x
Create_ds/curator/src/main/java/com/netflix/curator/x/zkclientbridge/CuratorZKClientBridge.java
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.curator.x.zkclientbridge; import org.I0Itec.zkclient.IZkConnection; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorListener; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * <p> * Bridge between ZKClient and Curator. Accomplished via an implementation for * {@link IZkConnection} which is the abstraction ZKClient uses to wrap the raw ZooKeeper handle * </p> * * <p> * Once allocated, bridge to ZKClient via: * <tt> * ZKClient zkClient = new ZkClient(new CuratorZKClientBridge(curatorInstance, timeout)); * </tt> * </p> */ public class CuratorZKClientBridge implements IZkConnection { private final CuratorFramework curator; private final AtomicReference<CuratorListener> listener = new AtomicReference<CuratorListener>(null); /** * @param curator Curator instance to bridge */ public CuratorZKClientBridge(CuratorFramework curator) { this.curator = curator; } /** * Return the client * * @return client */ public CuratorFramework getCurator() { return curator; } @Override public void connect(final Watcher watcher) { if ( watcher != null ) { CuratorListener localListener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getWatchedEvent() != null ) { watcher.process(event.getWatchedEvent()); } } }; curator.getCuratorListenable().addListener(localListener); listener.set(localListener); try { BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { WatchedEvent fakeEvent = new WatchedEvent(Watcher.Event.EventType.None, curator.getZookeeperClient().isConnected() ? Watcher.Event.KeeperState.SyncConnected : Watcher.Event.KeeperState.Disconnected, null); watcher.process(fakeEvent); } }; curator.checkExists().inBackground(callback).forPath("/foo"); } catch ( Exception e ) { throw new RuntimeException(e); } } } @Override public void close() throws InterruptedException { // NOTE: the curator instance is NOT closed here CuratorListener localListener = listener.getAndSet(null); if ( localListener != null ) { curator.getCuratorListenable().removeListener(localListener); } } @Override public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { try { return curator.create().withMode(mode).forPath(path, data); } catch ( Exception e ) { adjustException(e); } return null; // will never execute } @Override public void delete(String path) throws InterruptedException, KeeperException { try { curator.delete().forPath(path); } catch ( Exception e ) { adjustException(e); } } @Override public boolean exists(String path, boolean watch) throws KeeperException, InterruptedException { try { return watch ? (curator.checkExists().watched().forPath(path) != null) : (curator.checkExists().forPath(path) != null); } catch ( Exception e ) { adjustException(e); } return false; // will never execute } @Override public List<String> getChildren(String path, boolean watch) throws KeeperException, InterruptedException { try { return watch ? curator.getChildren().watched().forPath(path) : curator.getChildren().forPath(path); } catch ( Exception e ) { adjustException(e); } return null; // will never execute } @Override public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException { try { if ( stat != null ) { return watch ? curator.getData().storingStatIn(stat).watched().forPath(path) : curator.getData().storingStatIn(stat).forPath(path); } else { return watch ? curator.getData().watched().forPath(path) : curator.getData().forPath(path); } } catch ( Exception e ) { adjustException(e); } return null; // will never execute } @Override public void writeData(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { writeDataReturnStat(path, data, expectedVersion); } @Override public Stat writeDataReturnStat(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { try { curator.setData().withVersion(expectedVersion).forPath(path, data); } catch ( Exception e ) { adjustException(e); } return null; // will never execute } @Override public ZooKeeper.States getZookeeperState() { try { return curator.getZookeeperClient().getZooKeeper().getState(); } catch ( Exception e ) { throw new RuntimeException(e); } } @Override public long getCreateTime(String path) throws KeeperException, InterruptedException { try { Stat stat = curator.checkExists().forPath(path); return (stat != null) ? stat.getCtime() : 0; } catch ( Exception e ) { adjustException(e); } return 0; } @Override public String getServers() { return curator.getZookeeperClient().getCurrentConnectionString(); } private void adjustException(Exception e) throws KeeperException, InterruptedException { if ( e instanceof KeeperException ) { throw (KeeperException)e; } if ( e instanceof InterruptedException ) { throw (InterruptedException)e; } throw new RuntimeException(e); } }
4,154
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/test/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/test/java/com/facebook/business/cloudbridge/pl/server/DeploymentParamsTest.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.Before; import org.junit.Test; public class DeploymentParamsTest { private DeploymentParams deploymentParams = null; @Before public void setUp() { DeploymentParams deploymentParams = new DeploymentParams(); deploymentParams.region = "us-west-2"; deploymentParams.accountId = "123456789012"; deploymentParams.pubAccountId = "012345678901"; deploymentParams.vpcId = "vpc-0123456789abcdefg"; deploymentParams.configStorage = "test-bucket-1"; deploymentParams.dataStorage = "test-bucket-2"; deploymentParams.tag = "tag-postfix-123"; deploymentParams.enableSemiAutomatedDataIngestion = true; deploymentParams.logLevel = LogLevel.DEBUG; deploymentParams.awsAccessKeyId = "awsAccessKeyId1"; deploymentParams.awsSecretAccessKey = "awsSecretAccessKey2"; deploymentParams.awsSessionToken = "awsSessionToken3"; this.deploymentParams = deploymentParams; } @Test public void testLogLevel() { String logLevelString = "DEBUG"; LogLevel expectedLogLevel = LogLevel.DEBUG; LogLevel actualLogLevel = LogLevel.getLogLevelFromName(logLevelString); assertEquals(actualLogLevel, expectedLogLevel); } @Test public void testValidateWhenAllFieldsAreValid() { assertDoesNotThrow(deploymentParams::validate); } @Test public void testValidateWhenValidationErrors() { String region = deploymentParams.region; deploymentParams.region = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.region = region; String accountId = deploymentParams.accountId; deploymentParams.accountId = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.accountId = accountId; String pubAccountId = deploymentParams.pubAccountId; deploymentParams.pubAccountId = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.pubAccountId = pubAccountId; String vpcId = deploymentParams.vpcId; deploymentParams.vpcId = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.vpcId = vpcId; String configStorage = deploymentParams.configStorage; deploymentParams.configStorage = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.configStorage = configStorage; String dataStorage = deploymentParams.dataStorage; deploymentParams.dataStorage = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.dataStorage = dataStorage; String tag = deploymentParams.tag; deploymentParams.tag = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.tag = tag; String awsAccessKeyId = deploymentParams.awsAccessKeyId; deploymentParams.awsAccessKeyId = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.awsAccessKeyId = awsAccessKeyId; String awsSecretAccessKey = deploymentParams.awsSecretAccessKey; deploymentParams.awsSecretAccessKey = ""; assertThrows(InvalidDeploymentArgumentException.class, deploymentParams::validate); deploymentParams.awsSecretAccessKey = awsSecretAccessKey; } @Test public void testToString() { boolean enabledSemiAutoValue = deploymentParams.enableSemiAutomatedDataIngestion; String regexTemplate = ".*%s.*"; String stringValue = deploymentParams.toString(); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.region))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.accountId))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.pubAccountId))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.vpcId))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.configStorage))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.dataStorage))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.tag))); assertTrue(stringValue.matches(String.format(regexTemplate, enabledSemiAutoValue))); assertTrue(stringValue.matches(String.format(regexTemplate, deploymentParams.logLevel))); } }
4,155
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/test/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/test/java/com/facebook/business/cloudbridge/pl/server/ApplicationTest.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class ApplicationTest { @Test public void contextLoads() {} }
4,156
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/InstallationRunner.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.fasterxml.jackson.annotation.JsonValue; import java.io.*; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class InstallationRunner extends Thread { private Logger logger = LoggerFactory.getLogger(DeployController.class); private List<String> installationCommand; private Map<String, String> environmentVariables; private Runnable installationFinishedCallback; private Process provisioningProcess; private BufferedWriter installationLogFile; private int exitValue; public int getExitValue() { return exitValue; } private Object processOutputMutex = new Object(); private String processOutput = new String(); public String getOutput() { String output; synchronized (processOutputMutex) { output = processOutput; processOutput = new String(); } if (installationState == InstallationState.STATE_FINISHED) { halt(); } return output; } enum InstallationState { STATE_NOT_STARTED("not started"), STATE_RUNNING("running"), STATE_FINISHED("finished"), STATE_HALTED("halted"); private String state; private InstallationState(String state) { this.state = state; } @JsonValue public String toString() { return state; } }; private InstallationState installationState; public InstallationState getInstallationState() { return installationState; } public InstallationRunner( boolean shouldInstall, ToolkitInstallationParams installationParams, Runnable installationFinishedCallback) { this.installationState = InstallationState.STATE_NOT_STARTED; this.installationFinishedCallback = installationFinishedCallback; buildInstallationCommand(shouldInstall, installationParams); buildEnvironmentVariables(installationParams); try { installationLogFile = new BufferedWriter(new FileWriter("/tmp/deploy.log", true)); } catch (IOException e) { logger.error("An exception happened: ", e.getMessage()); } } private void buildInstallationCommand( boolean shouldInstall, ToolkitInstallationParams installationParams) { installationCommand = new ArrayList<String>(); installationCommand.add("/bin/bash"); installationCommand.add("/terraform_deployment/deploy_pc_infra.sh"); if (shouldInstall) { installationCommand.add("deploy"); } else { installationCommand.add("undeploy"); } installationCommand.add("-r"); installationCommand.add(installationParams.region); installationCommand.add("-a"); installationCommand.add(installationParams.awsAccountId); installationCommand.add("-t"); installationCommand.add(installationParams.tag); // always enable semi-automated data ingestion installationCommand.add("-b"); logger.info(" PC toolkit installation command built: " + installationCommand); } private void buildEnvironmentVariables(ToolkitInstallationParams installationParams) { environmentVariables = new HashMap<String, String>(); environmentVariables.put("AWS_ACCESS_KEY_ID", installationParams.awsAccessKeyId); environmentVariables.put("AWS_SECRET_ACCESS_KEY", installationParams.awsSecretAccessKey); if (!installationParams.awsSessionToken.isEmpty()) { environmentVariables.put("AWS_SESSION_TOKEN", installationParams.awsSessionToken); } environmentVariables.put("TF_LOG_STREAMING", Constants.DEPLOYMENT_STREAMING_LOG_FILE); environmentVariables.put("TF_RESOURCE_OUTPUT", Constants.DEPLOYMENT_RESOURCE_OUTPUT_FILE); if (installationParams.logLevel != LogLevel.DISABLED) { if (installationParams.logLevel == null) { installationParams.logLevel = LogLevel.DEBUG; } environmentVariables.put("TF_LOG", installationParams.logLevel.getLevel()); environmentVariables.put("TF_LOG_PATH", "/tmp/terraform.log"); } } private String readOutput(BufferedReader stdout) { StringBuilder sb = new StringBuilder(); try { String s; while (stdout.ready() && (s = stdout.readLine()) != null) { sb.append(s); sb.append('\n'); } } catch (IOException e) { logger.debug(" Problem reading installation process logs: " + e.getMessage()); } logger.trace(" Read " + sb.length() + " chars from installation process logs"); return sb.toString(); } private void logOutput(String output) { synchronized (processOutputMutex) { processOutput += output; } if (installationLogFile != null) { try { installationLogFile.write(output); installationLogFile.flush(); } catch (IOException e) { logger.error("Failed to log to Logger File"); } } } private void halt() { installationState = InstallationState.STATE_HALTED; try { installationLogFile.close(); } catch (IOException e) { logger.error("Failed to close Logger File"); } logger.info(" Installation finished"); } public void run() { installationState = InstallationState.STATE_RUNNING; BufferedReader stdout = null; try { ProcessBuilder pb = new ProcessBuilder(installationCommand); Map<String, String> env = pb.environment(); env.putAll(environmentVariables); pb.redirectErrorStream(true); pb.directory(new File("/terraform_deployment")); provisioningProcess = pb.start(); logger.info(" Creating installation process"); stdout = new BufferedReader(new InputStreamReader(provisioningProcess.getInputStream())); while (provisioningProcess.isAlive()) { logOutput(readOutput(stdout)); try { Thread.sleep(500); } catch (InterruptedException e) { } } exitValue = provisioningProcess.exitValue(); logger.info(" Installation process exited with value: " + exitValue); } catch (IOException e) { logger.error(" Installation could not be started. Message: " + e.getMessage()); throw new InstallationException("Installation could not be started"); } finally { if (stdout != null) { logOutput(readOutput(stdout)); } installationFinishedCallback.run(); installationState = InstallationState.STATE_FINISHED; } } }
4,157
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/DeploymentParams.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.amazonaws.regions.Regions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeploymentParams { public String region; public String accountId; public String pubAccountId; public String vpcId; public String configStorage; public String dataStorage; public String tag; public boolean enableSemiAutomatedDataIngestion; public LogLevel logLevel; public String awsAccessKeyId; public String awsSecretAccessKey; public String awsSessionToken; public String publisherPCEId; public String publisherPCEInstanceId; private final Logger logger = LoggerFactory.getLogger(DeploymentParams.class); public boolean validRegion() { try { Regions.fromName(region); } catch (IllegalArgumentException e) { return false; } return true; } // Amazon account identifier format can be found in // https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html private boolean validAccountID(String id) { return id != null && id.matches("^\\d{12}$"); } public boolean validPubAccountID() { return validAccountID(pubAccountId); } public boolean validAccountID() { return validAccountID(accountId); } // Amazon VPC ID identifier format can be found in // https://aws.amazon.com/about-aws/whats-new/2018/02/longer-format-resource-ids-are-now-available-in-amazon-ec2/ public boolean validVpcID() { return vpcId != null && !vpcId.isEmpty() && vpcId.matches("^vpc-[a-z0-9]{17}$"); } public boolean validConfigStorage() { return configStorage == null || validBucketID(configStorage); } public boolean validDataStorage() { return dataStorage == null || validBucketID(dataStorage); } // Amazon S3 Buck identifier format can be found in // https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html // This is not a perfect validation, as it does not test for invalid S3 names formatted as IP // addresses. But it's not a hard security issue, rather than a usability one, and theoretically // the user would not be able to create a bucket with such a name anyway. public boolean validBucketID(String id) { return id != null && !id.isEmpty() && id.matches("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$"); } // Amazon tag identifier format can be found in // https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html public boolean validTagPostfix() { return tag.matches("^([a-z0-9-][a-z0-9-]{1,18}[a-z0-9])$"); } public boolean validAccessKeyID() { return awsAccessKeyId != null && !awsAccessKeyId.isEmpty(); } public boolean validSecretAccessKey() { return awsSecretAccessKey != null && !awsSecretAccessKey.isEmpty(); } private void logAndThrow(String message) throws InvalidDeploymentArgumentException { logger.error(" " + message); throw new InvalidDeploymentArgumentException(message); } public void validate() throws InvalidDeploymentArgumentException { if (!validRegion()) { logAndThrow("Invalid Region: " + region); } if (!validAccountID()) { logAndThrow("Invalid Account ID: " + accountId); } if (!validPubAccountID()) { logAndThrow("Invalid Publisher Account ID: " + pubAccountId); } if (!validVpcID()) { logAndThrow("Invalid VPC ID: " + vpcId); } if (!validTagPostfix()) { logAndThrow( "Invalid Tag Postfix: " + tag + "\nMake sure the tag length is less than 20 characters, and using lowercase letters, numbers and dash only."); } if (!validConfigStorage()) { logAndThrow("Invalid Configuration Storage: " + configStorage); } if (!validDataStorage()) { logAndThrow("Invalid Data Storage: " + dataStorage); } if (!validAccessKeyID()) { logAndThrow("Invalid AWS Access Key ID"); } if (!validSecretAccessKey()) { logAndThrow("Invalid AWS Secret Access Key"); } } public String toString() { StringBuilder sb = new StringBuilder() .append("{Region: ") .append(region) .append(", Account ID: ") .append(accountId) .append(", Publisher Account ID: ") .append(pubAccountId) .append(", VPC ID: ") .append(vpcId) .append(", Configuration Storage: ") .append(configStorage) .append(", Data Storage: ") .append(dataStorage) .append(", Tag: ") .append(tag) .append(", publisherPCEId: ") .append(publisherPCEId) .append(", publisherPCEInstanceId: ") .append(publisherPCEInstanceId) .append(", Enable Semi-Automated Data Ingestion: ") .append(String.valueOf(enableSemiAutomatedDataIngestion)); if (logLevel != null) { sb.append(", Terraform Log Level: ").append(logLevel); } sb.append("}"); return sb.toString(); } }
4,158
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/Application.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
4,159
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/LogStreamer.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import java.io.*; import java.util.ArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogStreamer { private BufferedReader deploymentStreamFileReader; private FileInputStream deploymentFileStream; private Logger logger = LoggerFactory.getLogger(DeployController.class); enum LogStreamerState { STATE_NOT_STARTED("not started"), STATE_PAUSED("paused"), STATE_RUNNING("running"); private String state; private LogStreamerState(String state) { this.state = state; } }; private LogStreamerState state = LogStreamerState.STATE_NOT_STARTED; public LogStreamerState getState() { return state; } public void startFresh() { try { // ensure reset reset(); // ensure file is created & erased, or truncated to 0 if it existed before new PrintWriter(Constants.DEPLOYMENT_STREAMING_LOG_FILE).close(); deploymentFileStream = new FileInputStream(Constants.DEPLOYMENT_STREAMING_LOG_FILE); deploymentStreamFileReader = new BufferedReader(new InputStreamReader(deploymentFileStream)); state = LogStreamerState.STATE_RUNNING; } catch (IOException e) { logger.error("An exception happened during start: " + e.getMessage()); } } public void pause() { state = LogStreamerState.STATE_PAUSED; } private void resume() { if (state != LogStreamerState.STATE_NOT_STARTED) { state = LogStreamerState.STATE_RUNNING; } } public void reset() { if (state == LogStreamerState.STATE_NOT_STARTED) return; try { deploymentFileStream.close(); deploymentStreamFileReader.close(); } catch (final Exception e) { logger.error("An exception happened during reset: " + e.getMessage()); } finally { state = LogStreamerState.STATE_NOT_STARTED; } } public ArrayList<String> getStreamingLogs(boolean reset) { String s = null; ArrayList<String> messages = new ArrayList<String>(); if (reset) { resume(); } if (state == LogStreamerState.STATE_PAUSED || state == LogStreamerState.STATE_NOT_STARTED) { return messages; } try { if (reset) { // seek to beginning of the file deploymentFileStream.getChannel().position(0); deploymentStreamFileReader = new BufferedReader(new InputStreamReader(deploymentFileStream)); } while (deploymentStreamFileReader.ready() && (s = deploymentStreamFileReader.readLine()) != null) { messages.add(s); } } catch (final Exception e) { logger.error("An exception happened during reading: " + e.getMessage()); } return messages; } }
4,160
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/InstallationException.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; public class InstallationException extends RuntimeException { public InstallationException(String message) { super(message); } private static final long serialVersionUID = 856L; }
4,161
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/DeployController.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import static com.facebook.business.cloudbridge.pl.server.Constants.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class DeployController { private final Logger logger = LoggerFactory.getLogger(DeployController.class); private DeploymentRunner deploymentRunner; private InstallationRunner installationRunner; private Semaphore singleProvisioningLock = new Semaphore(1); private LogStreamer logStreamer = new LogStreamer(); private Validator validator = new Validator(); // == For PC toolkit installation @PostMapping( path = "/v2/installation", consumes = "application/json", produces = "application/json") public APIReturn installToolkit(@RequestBody ToolkitInstallationParams installationParams) { logger.info("Received PC toolkit installation request: " + installationParams.toString()); return runInstallation(true /* shouldInstall */, installationParams); } private APIReturn runInstallation( boolean shouldInstall, ToolkitInstallationParams installationParams) { try { installationParams.validate(); Validator.ValidatorResult preValidationResult = validator.validateForInstallation(installationParams, shouldInstall); if (!preValidationResult.isSuccessful) { return new APIReturn(APIReturn.Status.STATUS_FAIL, preValidationResult.message); } } catch (final Exception ex) { return new APIReturn(APIReturn.Status.STATUS_FAIL, ex.getMessage()); } String operation = shouldInstall ? "Installation" : "Uninstallation"; logger.info(" Validated input (installation/uninstallaion params)"); try { if (!singleProvisioningLock.tryAcquire()) { String errorMessage = "Another " + operation + " is in progress"; logger.error(" " + errorMessage); return new APIReturn(APIReturn.Status.STATUS_FAIL, errorMessage); } logger.info(" No " + operation + "conflicts found"); logStreamer.startFresh(); installationRunner = new InstallationRunner( shouldInstall, installationParams, () -> { singleProvisioningLock.release(); }); installationRunner.start(); return new APIReturn(APIReturn.Status.STATUS_SUCCESS, operation + " started successfully"); } catch (InstallationException ex) { return new APIReturn(APIReturn.Status.STATUS_ERROR, ex.getMessage()); } finally { logger.info(operation + "request finalized"); } } @DeleteMapping( path = "/v2/installation", consumes = "application/json", produces = "application/json") public APIReturn uninstallToolkit(@RequestBody ToolkitInstallationParams installationParams) { logger.info("Received PC toolkit uninstallation request: " + installationParams.toString()); return runInstallation(false /* shouldInstall */, installationParams); } @GetMapping(path = "/v2/installation", produces = "application/json") public APIReturn installationStatus() { logger.info("Received status request"); InstallationRunner.InstallationState state; String output = ""; ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = mapper.createObjectNode(); try { synchronized (this) { if (installationRunner == null) { logger.debug(" No installation created yet"); output = ""; } else { state = installationRunner.getInstallationState(); output = installationRunner.getOutput(); rootNode.put("state", state.toString()); if (state == InstallationRunner.InstallationState.STATE_HALTED) { rootNode.put("exitValue", installationRunner.getExitValue()); readAndMapResourceOutputFromFile(rootNode); installationRunner = null; } } return new APIReturn(APIReturn.Status.STATUS_SUCCESS, output, rootNode); } } catch (final Exception e) { logger.error(" Error happened : " + e.getMessage()); } return new APIReturn(APIReturn.Status.STATUS_ERROR, output, rootNode); } // === For MPC deployment & undeployment @PostMapping( path = "/v1/deployment", consumes = "application/json", produces = "application/json") public APIReturn deploymentCreate(@RequestBody DeploymentParams deployment) { logger.info("Received deployment request: " + deployment.toString()); return runDeployment(true, deployment); } @DeleteMapping( path = "/v1/deployment", consumes = "application/json", produces = "application/json") public APIReturn deploymentDelete(@RequestBody DeploymentParams deployment) { logger.info("Received un-deployment request: " + deployment.toString()); return runDeployment(false, deployment); } private APIReturn runDeployment(boolean shouldDeploy, DeploymentParams deployment) { try { deployment.validate(); Validator.ValidatorResult preValidationResult = validator.validate(deployment, shouldDeploy); if (!preValidationResult.isSuccessful) { return new APIReturn(APIReturn.Status.STATUS_FAIL, preValidationResult.message); } } catch (final Exception ex) { return new APIReturn(APIReturn.Status.STATUS_FAIL, ex.getMessage()); } logger.info(" Validated input"); try { if (!singleProvisioningLock.tryAcquire()) { String errorMessage = "Another deployment is in progress"; logger.error(" " + errorMessage); return new APIReturn(APIReturn.Status.STATUS_FAIL, errorMessage); } logger.info(" No deployment conflicts found"); logStreamer.startFresh(); deploymentRunner = new DeploymentRunner( shouldDeploy, deployment, () -> { singleProvisioningLock.release(); }); deploymentRunner.start(); if (shouldDeploy) { return new APIReturn(APIReturn.Status.STATUS_SUCCESS, "Deployment Started Successfully"); } else { return new APIReturn(APIReturn.Status.STATUS_SUCCESS, "Undeployment Started Successfully"); } } catch (DeploymentException ex) { return new APIReturn(APIReturn.Status.STATUS_ERROR, ex.getMessage()); } finally { logger.info(" Deployment request finalized"); } } private Map<String, Object> readAndMapResourceOutputFromFile(final ObjectNode objectNode) { Map<String, Object> resourceMap = new HashMap<>(); try { final ObjectMapper resourceOutputMapper = new ObjectMapper(); resourceMap = resourceOutputMapper.readValue( Paths.get(DEPLOYMENT_RESOURCE_OUTPUT_FILE).toFile(), HashMap.class); resourceMap.forEach((key, value) -> objectNode.put(key, value.toString())); } catch (final Exception e) { logger.error("Caught exception during reading JSON output from terraform deployment" + e); } return resourceMap; } @GetMapping(path = "/v1/deployment", produces = "application/json") public APIReturn deploymentStatus() { logger.info("Received status request"); DeploymentRunner.DeploymentState state; String output = ""; ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = mapper.createObjectNode(); try { synchronized (this) { if (deploymentRunner == null) { logger.debug(" No deployment created yet"); output = ""; } else { state = deploymentRunner.getDeploymentState(); output = deploymentRunner.getOutput(); rootNode.put("state", state.toString()); if (state == DeploymentRunner.DeploymentState.STATE_HALTED) { rootNode.put("exitValue", deploymentRunner.getExitValue()); // TODO refactor whole class to include a Response Structure readAndMapResourceOutputFromFile(rootNode); deploymentRunner = null; } } return new APIReturn(APIReturn.Status.STATUS_SUCCESS, output, rootNode); } } catch (final Exception e) { logger.error(" Error happened : " + e.getMessage()); } return new APIReturn(APIReturn.Status.STATUS_ERROR, output, rootNode); } @GetMapping(path = "/v2/deployment/healthCheck", produces = "application/json") public void checkHealth() { logger.info("checkHealth: Received status request"); } @GetMapping( path = "/v1/deployment/streamLogs", produces = "application/json", consumes = "application/json") public List<String> deploymentStreamLogs(@RequestBody Boolean refresh) { logger.info("Received getStream log request: refresh " + refresh); List<String> result = new ArrayList<>(); result = logStreamer.getStreamingLogs(refresh); if (deploymentRunner == null) { logStreamer.pause(); } return result; } @GetMapping( path = "/v2/deployment/pceValidator", produces = "application/json", consumes = "application/json") public PCEValidatorAPIReturn runPCEValidator(@RequestBody DeploymentParams deployment) { logger.info("Received request to run PCE validator: "); final PCEValidatorAPIReturn result = new PCEValidatorRunner().start(deployment); return result; } @GetMapping(path = "/v1/deployment/logs") public byte[] downloadDeploymentLogs() { logger.info("Received logs request"); ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { ZipOutputStream zout = new ZipOutputStream(bo); compressIfExists("/tmp/server.log", "server.log", zout); compressIfExists("/tmp/deploy.log", "deploy.log", zout); compressIfExists("/tmp/terraform.log", "terraform.log", zout); compressIfExists(PCE_VALIDATOR_LOG_STREAMING, "pceValidatorStream.log", zout); compressIfExists(DEPLOYMENT_STREAMING_LOG_FILE, "deploymentStream.log", zout); zout.close(); } catch (IOException e) { logger.debug( " Could not compress logs. Message: " + e.getMessage() + "\n" + e.getStackTrace()); } logger.info("Logs request finalized"); return bo.toByteArray(); } private void compressIfExists(String fullFilePath, String zipName, ZipOutputStream zout) { Path file = Paths.get(fullFilePath); logger.info(" Compressing \"" + fullFilePath + "\""); if (Files.exists(file)) { logger.trace(" File exists"); try { byte[] bytes = Files.readAllBytes(file); ZipEntry ze = new ZipEntry(zipName); zout.putNextEntry(ze); zout.write(bytes); zout.closeEntry(); } catch (IOException e) { logger.debug( " Could not read file. Message: " + e.getMessage() + "\n" + e.getStackTrace()); } } else { logger.debug(" File does not exist"); } } }
4,162
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/Validator.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeVpcsResult; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.HeadBucketRequest; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest; import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult; import com.amazonaws.services.servicequotas.AWSServiceQuotas; import com.amazonaws.services.servicequotas.AWSServiceQuotasClient; import com.amazonaws.services.servicequotas.model.GetServiceQuotaRequest; import com.amazonaws.services.servicequotas.model.ServiceQuota; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Validator { private final Logger logger = LoggerFactory.getLogger(Validator.class); private static final String VPC_QUOTA_CODE = "L-F678F1CE"; private static final String VPC_SERVICE_CODE = "vpc"; public class ValidatorResult { public boolean isSuccessful; public String message; ValidatorResult(boolean isSuccessful, String message) { this.isSuccessful = isSuccessful; this.message = message; } } private AWSStaticCredentialsProvider getCredentials(DeploymentParams deploymentParams) { if (!deploymentParams.awsSessionToken.isEmpty()) { return new AWSStaticCredentialsProvider( new BasicSessionCredentials( deploymentParams.awsAccessKeyId, deploymentParams.awsSecretAccessKey, deploymentParams.awsSessionToken)); } return new AWSStaticCredentialsProvider( new BasicAWSCredentials( deploymentParams.awsAccessKeyId, deploymentParams.awsSecretAccessKey)); } private Integer countCurrentVPCInRegion(DeploymentParams deploymentParams) { AmazonEC2 ec2Client = AmazonEC2Client.builder() .withRegion(deploymentParams.region) .withCredentials(getCredentials(deploymentParams)) .build(); DescribeVpcsResult result = ec2Client.describeVpcs(); return result.getVpcs().size(); } private ValidatorResult validateVpcQuotaPerRegion(DeploymentParams deploymentParams) { final AWSServiceQuotas serviceQuotaClient = AWSServiceQuotasClient.builder() .withRegion(deploymentParams.region) .withCredentials(getCredentials(deploymentParams)) .build(); final ServiceQuota quota = serviceQuotaClient .getServiceQuota( new GetServiceQuotaRequest() .withQuotaCode(VPC_QUOTA_CODE) .withServiceCode(VPC_SERVICE_CODE)) .getQuota(); final Integer currentVPCsInThisRegion = countCurrentVPCInRegion(deploymentParams); logger.info( "current vpc count : " + currentVPCsInThisRegion + " , max VPC allowed: " + quota.getValue()); if (currentVPCsInThisRegion >= quota.getValue()) { return new ValidatorResult( false, String.format( "VPC limit is at peak in region %s. Contact your Meta representatives for more information if needed.", deploymentParams.region)); } return new ValidatorResult(true, "VPC limit validation successful"); } private String getAccountIDUsingAccessKey(DeploymentParams deploymentParams) { AWSSecurityTokenService stsService = AWSSecurityTokenServiceClientBuilder.standard() .withCredentials(getCredentials(deploymentParams)) .withRegion(deploymentParams.region) .build(); try { GetCallerIdentityResult callerIdentity = stsService.getCallerIdentity(new GetCallerIdentityRequest()); logger.info("account info: " + callerIdentity.getAccount()); return callerIdentity.getAccount(); } catch (final Exception e) { logger.error("Got exception while verifying credentials " + e.getMessage()); return null; } } public ValidatorResult validateCredentials(DeploymentParams deploymentParams) { final String accountIdFromAws = getAccountIDUsingAccessKey(deploymentParams); if (accountIdFromAws == null) { logger.error("Invalid credentials received"); return new ValidatorResult(false, "The AWS access key or secret key provided is invalid"); } if (!accountIdFromAws.equals(deploymentParams.accountId)) { logger.error( "Invalid credentials received vs provided, received from AWS: " + accountIdFromAws + " provided by user: " + deploymentParams.accountId); return new ValidatorResult( false, "The AWS account id provided doesn't match with the AWS credentials provided"); } return new ValidatorResult(true, "credentials provided are valid"); } public ValidatorResult validateDataBucket(DeploymentParams deploymentParams) { if (StringUtils.isNotEmpty(deploymentParams.dataStorage)) { final AmazonS3 s3 = AmazonS3ClientBuilder.standard() .withRegion(deploymentParams.region) .withCredentials( new AWSStaticCredentialsProvider( StringUtils.isEmpty(deploymentParams.awsSessionToken) ? new BasicAWSCredentials( deploymentParams.awsAccessKeyId, deploymentParams.awsSecretAccessKey) : new BasicSessionCredentials( deploymentParams.awsAccessKeyId, deploymentParams.awsSecretAccessKey, deploymentParams.awsSessionToken))) .build(); try { s3.headBucket(new HeadBucketRequest(deploymentParams.dataStorage)); } catch (AmazonServiceException e) { logger.error("Head bucket for {} failed: {}", deploymentParams.dataStorage, e.getMessage()); String msg = "The specified data bucket does not exist in the region or the " + "provided credential does not have access to it"; if (e.getStatusCode() == 400 || e.getStatusCode() == 404) { msg = "The specified data bucket does not exist in the region"; } else if (e.getStatusCode() == 403) { msg = "The provided credential does not have access to the data bucket"; } return new ValidatorResult(false, msg); } catch (Exception e) { logger.error("Head bucket for {} failed: {}", deploymentParams.dataStorage, e.getMessage()); return new ValidatorResult( false, "The specified data bucket does not exist in the region or the " + "provided credential does not have access to it"); } } return new ValidatorResult(true, "The provided data bucket is valid"); } public ValidatorResult validate(DeploymentParams deploymentParams, boolean deploy) { final ValidatorResult credentialsValidationResult = validateCredentials(deploymentParams); if (!credentialsValidationResult.isSuccessful) { return credentialsValidationResult; } if (deploy) { final ValidatorResult vpcValidationResult = validateVpcQuotaPerRegion(deploymentParams); if (!vpcValidationResult.isSuccessful) { return vpcValidationResult; } } ValidatorResult dataStorageValidationRes = validateDataBucket(deploymentParams); if (!dataStorageValidationRes.isSuccessful) { return dataStorageValidationRes; } // TODO S3 bucket limit validation T119080329 return new ValidatorResult(true, "No pre validation issues found so far!"); } public ValidatorResult validateForInstallation( ToolkitInstallationParams installationParams, boolean install) { final ValidatorResult credentialsValidationResult = validateCredentials(installationParams.toDeploymentParams()); if (!credentialsValidationResult.isSuccessful) { return credentialsValidationResult; } ValidatorResult dataStorageValidationRes = validateDataBucket(installationParams.toDeploymentParams()); if (!dataStorageValidationRes.isSuccessful) { return dataStorageValidationRes; } return new ValidatorResult(true, "No pre validation issues found so far!"); } }
4,163
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/LogLevel.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; enum LogLevel { DISABLED("Disabled"), ERROR("ERROR"), WARNING("WARN"), INFORMATION("INFO"), DEBUG("DEBUG"), TRACE("TRACE"); private final String level; LogLevel() { this.level = "DEBUG"; } LogLevel(final String level) { this.level = level; } public String getLevel() { return this.level; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static LogLevel getLogLevelFromName(@JsonProperty("logLevel") String level) { for (LogLevel l : LogLevel.values()) { if (l.getLevel().equals(level)) { return l; } } return DEBUG; } }
4,164
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/PCEValidatorRunner.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.facebook.business.cloudbridge.pl.server.command.ShellCommandHandler; import com.facebook.business.cloudbridge.pl.server.command.ShellCommandRunner; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; public class PCEValidatorRunner { private Logger logger = LoggerFactory.getLogger(DeployController.class); private ShellCommandRunner shellCommandRunner = new ShellCommandHandler("pceValidator"); private List<String> buildPCEValidateCommand(final @NonNull DeploymentParams deployment) { final Stream.Builder<String> commandBuilder = Stream.builder(); final Stream<String> commandStream = commandBuilder .add("/bin/bash") .add("/terraform_deployment/pceValidator.sh") .add(deployment.region) .add(deployment.tag) .build(); return commandStream.collect(Collectors.toList()); } private Map<String, String> buildEnvironmentVariables( final @NonNull DeploymentParams deployment) { final Map<String, String> environmentVariables = new HashMap<String, String>(); environmentVariables.put("AWS_ACCESS_KEY_ID", deployment.awsAccessKeyId); environmentVariables.put("AWS_SECRET_ACCESS_KEY", deployment.awsSecretAccessKey); if (!deployment.awsSessionToken.isEmpty()) { environmentVariables.put("AWS_SESSION_TOKEN", deployment.awsSessionToken); } environmentVariables.put("PCE_VALIDATOR_LOG_FILE", Constants.PCE_VALIDATOR_LOG_STREAMING); return environmentVariables; } public PCEValidatorAPIReturn start(final @NonNull DeploymentParams deployment) { final Validator.ValidatorResult credentialValidationResult = new Validator().validateCredentials(deployment); if (credentialValidationResult.isSuccessful == false) { return new PCEValidatorAPIReturn( PCEValidatorAPIReturn.Status.STATUS_FAIL, "The AWS access key ID and secret access key provided are invalid. Please review the information provided and try again."); } final ShellCommandRunner.CommandRunnerResult pceValidationResult = shellCommandRunner.run( buildPCEValidateCommand(deployment), buildEnvironmentVariables(deployment), "/terraform_deployment", "pceValidator.log"); return new PCEValidatorAPIReturn( pceValidationResult.getExitCode() == 0 ? PCEValidatorAPIReturn.Status.STATUS_SUCCESS : PCEValidatorAPIReturn.Status.STATUS_FAIL, ""); } }
4,165
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/DeploymentException.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; public class DeploymentException extends RuntimeException { public DeploymentException(String message) { super(message); } private static final long serialVersionUID = 856L; }
4,166
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/ToolkitInstallationParams.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.amazonaws.regions.Regions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ToolkitInstallationParams { public String region; public String awsAccountId; public String configStorage; public String dataStorage; public String awsAccessKeyId; public String awsSecretAccessKey; public String awsSessionToken; public String tag; public LogLevel logLevel; private final Logger logger = LoggerFactory.getLogger(DeploymentParams.class); public boolean validRegion() { try { Regions.fromName(region); } catch (IllegalArgumentException e) { return false; } return true; } // Amazon account identifier format can be found in // https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html public boolean validAwsAccountID() { return awsAccountId != null && awsAccountId.matches("^\\d{12}$"); } public boolean validConfigStorage() { return configStorage == null || validBucketID(configStorage); } public boolean validDataStorage() { return dataStorage == null || validBucketID(dataStorage); } // Amazon S3 Buck identifier format can be found in // https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html // This is not a perfect validation, as it does not test for invalid S3 names formatted as IP // addresses. But it's not a hard security issue, rather than a usability one, and theoretically // the user would not be able to create a bucket with such a name anyway. public boolean validBucketID(String id) { return id != null && !id.isEmpty() && id.matches("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$"); } // Amazon tag identifier format can be found in // https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html public boolean validTagPostfix() { return tag.matches("^([a-z0-9-][a-z0-9-]{1,18}[a-z0-9])$"); } public boolean validAccessKeyID() { return awsAccessKeyId != null && !awsAccessKeyId.isEmpty(); } public boolean validSecretAccessKey() { return awsSecretAccessKey != null && !awsSecretAccessKey.isEmpty(); } private void logAndThrow(String message) throws InvalidDeploymentArgumentException { logger.error(" " + message); throw new InvalidDeploymentArgumentException(message); } public void validate() throws InvalidDeploymentArgumentException { if (!validRegion()) { logAndThrow("Invalid Region: " + region); } if (!validAwsAccountID()) { logAndThrow("Invalid AWS Account ID: " + awsAccountId); } if (!validTagPostfix()) { logAndThrow( "Invalid Tag Postfix: " + tag + "\nMake sure the tag length is less than 20 characters, and using lowercase letters, numbers and dash only."); } if (!validConfigStorage()) { logAndThrow("Invalid Configuration Storage: " + configStorage); } if (!validDataStorage()) { logAndThrow("Invalid Data Storage: " + dataStorage); } if (!validAccessKeyID()) { logAndThrow("Invalid AWS Access Key ID"); } if (!validSecretAccessKey()) { logAndThrow("Invalid AWS Secret Access Key"); } } public String toString() { StringBuilder sb = new StringBuilder() .append("{Region: ") .append(region) .append(", AWS Account ID: ") .append(awsAccountId) .append(", Configuration Storage: ") .append(configStorage) .append(", Data Storage: ") .append(dataStorage) .append(", Tag: ") .append(tag); if (logLevel != null) { sb.append(", Terraform Log Level: ").append(logLevel); } sb.append("}"); return sb.toString(); } public DeploymentParams toDeploymentParams() { DeploymentParams params = new DeploymentParams(); params.region = region; params.accountId = awsAccountId; params.configStorage = configStorage; params.dataStorage = dataStorage; params.tag = tag; params.logLevel = logLevel; params.awsAccessKeyId = awsAccessKeyId; params.awsSecretAccessKey = awsSecretAccessKey; params.awsSessionToken = awsSessionToken; return params; } }
4,167
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/InvalidDeploymentArgumentException.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; public class InvalidDeploymentArgumentException extends Exception { public InvalidDeploymentArgumentException(String message) { super(message); } private static final long serialVersionUID = 855L; }
4,168
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/APIReturn.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonValue; class APIReturn { enum Status { STATUS_SUCCESS("success"), STATUS_FAIL("fail"), STATUS_ERROR("error"); private String status; Status(String status) { this.status = status; } @JsonValue public String getStatus() { return status; } } public Status status; public String message; @JsonInclude(Include.NON_NULL) public Object data; public APIReturn(Status status, String message) { this.status = status; this.message = message; this.data = null; } public APIReturn(Status status, String message, Object data) { this.status = status; this.message = message; this.data = data; } }
4,169
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/PCEValidatorAPIReturn.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.fasterxml.jackson.annotation.JsonValue; public class PCEValidatorAPIReturn { enum Status { STATUS_SUCCESS("success"), STATUS_FAIL("fail"); private String status; Status(String status) { this.status = status; } @JsonValue public String getStatus() { return status; } } public Status status; public String message; public PCEValidatorAPIReturn(Status status, String message) { this.status = status; this.message = message; } }
4,170
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/DeploymentRunner.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; import com.fasterxml.jackson.annotation.JsonValue; import java.io.*; import java.util.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeploymentRunner extends Thread { private Logger logger = LoggerFactory.getLogger(DeployController.class); private List<String> deployCommand; private Map<String, String> environmentVariables; private Runnable deploymentFinishedCallback; private Process provisioningProcess; private BufferedWriter deployLogFile; private int exitValue; public int getExitValue() { return exitValue; } private Object processOutputMutex = new Object(); private String processOutput = new String(); public String getOutput() { String output; synchronized (processOutputMutex) { output = processOutput; processOutput = new String(); } if (deploymentState == DeploymentState.STATE_FINISHED) { halt(); } return output; } enum DeploymentState { STATE_NOT_STARTED("not started"), STATE_RUNNING("running"), STATE_FINISHED("finished"), STATE_HALTED("halted"); private String state; private DeploymentState(String state) { this.state = state; } @JsonValue public String toString() { return state; } }; private DeploymentState deploymentState; public DeploymentState getDeploymentState() { return deploymentState; } public DeploymentRunner( boolean shouldDeploy, DeploymentParams deployment, Runnable deploymentFinishedCallback) { this.deploymentState = DeploymentState.STATE_NOT_STARTED; this.deploymentFinishedCallback = deploymentFinishedCallback; buildDeployCommand(shouldDeploy, deployment); buildEnvironmentVariables(deployment); try { deployLogFile = new BufferedWriter(new FileWriter("/tmp/deploy.log", true)); } catch (IOException e) { logger.error("An exception happened: ", e.getMessage()); } } private void buildDeployCommand(boolean shouldDeploy, DeploymentParams deployment) { deployCommand = new ArrayList<String>(); deployCommand.add("/bin/bash"); deployCommand.add("/terraform_deployment/deploy.sh"); if (shouldDeploy) { deployCommand.add("deploy"); } else { deployCommand.add("undeploy"); } deployCommand.add("-r"); deployCommand.add(deployment.region); deployCommand.add("-a"); deployCommand.add(deployment.accountId); deployCommand.add("-p"); deployCommand.add(deployment.pubAccountId); deployCommand.add("-v"); deployCommand.add(deployment.vpcId); deployCommand.add("-t"); deployCommand.add(deployment.tag); if (deployment.configStorage != null) { deployCommand.add("-s"); deployCommand.add(deployment.configStorage); } if (deployment.dataStorage != null) { deployCommand.add("-d"); deployCommand.add(deployment.dataStorage); } if (!StringUtils.isBlank(deployment.publisherPCEInstanceId)) { deployCommand.add("-e"); deployCommand.add(deployment.publisherPCEInstanceId); } if (deployment.enableSemiAutomatedDataIngestion) { deployCommand.add("-b"); } logger.info(" Deploy command built: " + deployCommand); } private void buildEnvironmentVariables(DeploymentParams deployment) { environmentVariables = new HashMap<String, String>(); environmentVariables.put("AWS_ACCESS_KEY_ID", deployment.awsAccessKeyId); environmentVariables.put("AWS_SECRET_ACCESS_KEY", deployment.awsSecretAccessKey); environmentVariables.put( "SHOULD_SKIP_VPC_PEERING_VALIDATION", StringUtils.isEmpty(deployment.publisherPCEId) ? "1" : "0"); if (!deployment.awsSessionToken.isEmpty()) { environmentVariables.put("AWS_SESSION_TOKEN", deployment.awsSessionToken); } environmentVariables.put("TF_LOG_STREAMING", Constants.DEPLOYMENT_STREAMING_LOG_FILE); environmentVariables.put("TF_RESOURCE_OUTPUT", Constants.DEPLOYMENT_RESOURCE_OUTPUT_FILE); if (deployment.logLevel != LogLevel.DISABLED) { if (deployment.logLevel == null) deployment.logLevel = LogLevel.DEBUG; environmentVariables.put("TF_LOG", deployment.logLevel.getLevel()); environmentVariables.put("TF_LOG_PATH", "/tmp/terraform.log"); } } private String readOutput(BufferedReader stdout) { StringBuilder sb = new StringBuilder(); try { String s; while (stdout.ready() && (s = stdout.readLine()) != null) { sb.append(s); sb.append('\n'); } } catch (IOException e) { logger.debug(" Problem reading deployment process logs: " + e.getMessage()); } logger.trace(" Read " + sb.length() + " chars from deployment process logs"); return sb.toString(); } private void logOutput(String output) { synchronized (processOutputMutex) { processOutput += output; } if (deployLogFile != null) { try { deployLogFile.write(output); deployLogFile.flush(); } catch (IOException e) { logger.error("Failed to log to Logger File"); } } } private void halt() { deploymentState = DeploymentState.STATE_HALTED; try { deployLogFile.close(); } catch (IOException e) { logger.error("Failed to close Logger File"); } logger.info(" Deployment finished"); } public void run() { deploymentState = DeploymentState.STATE_RUNNING; BufferedReader stdout = null; try { ProcessBuilder pb = new ProcessBuilder(deployCommand); Map<String, String> env = pb.environment(); env.putAll(environmentVariables); pb.redirectErrorStream(true); pb.directory(new File("/terraform_deployment")); provisioningProcess = pb.start(); logger.info(" Creating deployment process"); stdout = new BufferedReader(new InputStreamReader(provisioningProcess.getInputStream())); while (provisioningProcess.isAlive()) { logOutput(readOutput(stdout)); try { Thread.sleep(500); } catch (InterruptedException e) { } } exitValue = provisioningProcess.exitValue(); logger.info(" Deployment process exited with value: " + exitValue); } catch (IOException e) { logger.error(" Deployment could not be started. Message: " + e.getMessage()); throw new DeploymentException("Deployment could not be started"); } finally { if (stdout != null) { logOutput(readOutput(stdout)); } deploymentFinishedCallback.run(); deploymentState = DeploymentState.STATE_FINISHED; } } }
4,171
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/Constants.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server; public final class Constants { public static final String DEPLOYMENT_STREAMING_LOG_FILE = "/tmp/deploymentStream.log"; public static final String PCE_VALIDATOR_LOG_STREAMING = "/tmp/pceValidatorStream.log"; public static final String DEPLOYMENT_RESOURCE_OUTPUT_FILE = "/tmp/resourceOutput.log"; }
4,172
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment/cache/ThreadSafeCache.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.deployment.cache; import java.util.concurrent.ConcurrentHashMap; public class ThreadSafeCache<K, V> { private ConcurrentHashMap<K, V> map; public ThreadSafeCache() { map = new ConcurrentHashMap<K, V>(); } public void put(K key, V value) { map.put(key, value); } public V get(K key) { return map.get(key); } public void remove(K key) { map.remove(key); } public boolean containsKey(K key) { return map.containsKey(key); } public int size() { return map.size(); } public void clear() { map.clear(); } }
4,173
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment/models/DeploymentMeta.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.deployment.models; public class DeploymentMeta { private String deploymentId; private DeploymentStatus deploymentStatus; public DeploymentMeta(final String deploymentId, final DeploymentStatus deploymentStatus) { this.deploymentId = deploymentId; this.deploymentStatus = deploymentStatus; } public String getDeploymentId() { return this.deploymentId; } public DeploymentStatus getDeploymentStatus() { return this.deploymentStatus; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setDeploymentStatus(DeploymentStatus deploymentStatus) { this.deploymentStatus = deploymentStatus; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof DeploymentMeta)) return false; DeploymentMeta other = (DeploymentMeta) o; Object this$deploymentId = this.getDeploymentId(); Object other$deploymentId = other.getDeploymentId(); if (this$deploymentId == null ? other$deploymentId != null : !this$deploymentId.equals(other$deploymentId)) return false; Object this$deploymentStatus = this.getDeploymentStatus(); Object other$deploymentStatus = other.getDeploymentStatus(); if (this$deploymentStatus == null ? other$deploymentStatus != null : !this$deploymentStatus.equals(other$deploymentStatus)) return false; return true; } @Override public int hashCode() { int PRIME = 59; int result = 1; Object $deploymentId = this.getDeploymentId(); result = result * PRIME + ($deploymentId == null ? 43 : $deploymentId.hashCode()); Object $deploymentStatus = this.getDeploymentStatus(); result = result * PRIME + ($deploymentStatus == null ? 43 : $deploymentStatus.hashCode()); return result; } @Override public String toString() { return "DeploymentMeta(deploymentId=" + getDeploymentId() + ", deploymentStatus=" + getDeploymentStatus() + ")"; } }
4,174
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment/models/DeploymentStatus.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.deployment.models; public enum DeploymentStatus { NOT_STARTED("NOT_STARTED"), STARTED("STARTED"), ERROR("ERROR"), COMPLETED("COMPLETED"), ; private final String status; private DeploymentStatus(final String status) { this.status = status; } public String getStatus() { return this.status; } }
4,175
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/deployment/controller/DeploymentController.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.deployment.controller; import com.facebook.business.cloudbridge.pl.server.DeploymentParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class DeploymentController { private final Logger logger = LoggerFactory.getLogger(com.facebook.business.cloudbridge.pl.server.DeployController.class); // get @GetMapping(path = "/v1/pl/status", produces = "application/json") public void deploymentStatus() {} @GetMapping(path = "/v1/pl/healthCheck", produces = "application/json") public void checkHealth() { logger.info("checkHealth: Received status request"); } @GetMapping(path = "/v1/pl/logs") public void downloadDeploymentLogs() { // } // post @PostMapping(path = "/v1/pl/deploy", consumes = "application/json", produces = "application/json") public void deploy(@RequestBody DeploymentParams deployment) { logger.info("Received deployment request: " + deployment.toString()); } // delete @DeleteMapping( path = "/v1/pl/undeploy", consumes = "application/json", produces = "application/json") public void undeploy(@RequestBody DeploymentParams deployment) { logger.info("Received un-deployment request: " + deployment.toString()); } }
4,176
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/command/ShellCommandRunner.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.command; import java.util.List; import java.util.Map; public interface ShellCommandRunner { class CommandRunnerResult { Integer exitCode; public Integer getExitCode() { return this.exitCode; } CommandRunnerResult(Integer exitCode) { this.exitCode = exitCode; } } public CommandRunnerResult run( final List<String> commandToRun, final Map<String, String> commandEnvironment, String commandOutputDirectoryPath, String commandOutputFilePath); }
4,177
0
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server
Create_ds/fbpcs/fbpcs/infra/cloud_bridge/server/src/main/java/com/facebook/business/cloudbridge/pl/server/command/ShellCommandHandler.java
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.business.cloudbridge.pl.server.command; import com.facebook.business.cloudbridge.pl.server.DeployController; import java.io.*; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShellCommandHandler implements ShellCommandRunner { private final Logger logger = LoggerFactory.getLogger(DeployController.class); private final Integer PROCESS_SLEEP_TIME_IN_MS = 500; private String name; private BufferedWriter logStreamer; public ShellCommandHandler(final String name) { this.name = name; } private String formatLog(final String log) { return this.name + " : " + log; } private String readOutput(BufferedReader stdout) { final StringBuilder sb = new StringBuilder(); try { String logLine = null; while (stdout.ready() && (logLine = stdout.readLine()) != null) { sb.append(logLine); sb.append('\n'); logger.info(logLine); } } catch (final IOException e) { logger.debug(formatLog("Problem reading deployment process logs: ") + e.getMessage()); } return sb.toString(); } private void logOutput(String output) { if (logStreamer != null) { try { logStreamer.write(output); logStreamer.flush(); } catch (final Exception e) { logger.error(formatLog("Failed to write to logStream: ") + e.getMessage()); } } } private String createFilePath( final String commandOutputDirectoryPath, final String commandOutputFileName) { return commandOutputDirectoryPath + "/" + commandOutputFileName; } private void ensureFileOpen(final String outputFilePath) throws IOException { try { logStreamer = new BufferedWriter(new FileWriter(outputFilePath, true)); } catch (final Exception e) { logger.error(formatLog("An exception happened: ") + e.getMessage()); throw e; } } @Override public CommandRunnerResult run( final List<String> commandToRun, final Map<String, String> commandEnvironment, final String commandOutputDirectoryPath, final String commandOutputFileName) { try { ensureFileOpen(createFilePath(commandOutputDirectoryPath, commandOutputFileName)); final ProcessBuilder processBuilder = new ProcessBuilder(commandToRun); processBuilder.environment().putAll(commandEnvironment); processBuilder.directory(new File(commandOutputDirectoryPath)); processBuilder.redirectErrorStream(true); final Process provisioningProcess = processBuilder.start(); final BufferedReader stdout = new BufferedReader(new InputStreamReader(provisioningProcess.getInputStream())); while (provisioningProcess.isAlive()) { logOutput(readOutput(stdout)); try { Thread.sleep(PROCESS_SLEEP_TIME_IN_MS); } catch (final InterruptedException e) { logger.error(formatLog(" exited with exception: ") + e.getMessage()); } } logger.info(formatLog(" exited with value: ") + provisioningProcess.exitValue()); return new CommandRunnerResult(provisioningProcess.exitValue()); } catch (final Exception e) { logger.error(formatLog(" exited with exception: ") + e.getMessage()); } return new CommandRunnerResult(1); } }
4,178
0
Create_ds/s2n-tls/tests/integrationv2
Create_ds/s2n-tls/tests/integrationv2/bin/SSLSocketClient.java
import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.KeyStore; import java.io.FileInputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocket; /* * Simple JDK SSL client for integration testing purposes */ public class SSLSocketClient { public static void main(String[] args) throws Exception { int port = Integer.parseInt(args[0]); String certificatePath = args[1]; String protocol = sslProtocols(args[2]); String[] protocolList = new String[] {protocol}; String[] cipher = new String[] {args[3]}; String host = "localhost"; byte[] buffer = new byte[100]; SSLSocketFactory socketFactory = createSocketFactory(certificatePath, protocol); try ( SSLSocket socket = (SSLSocket)socketFactory.createSocket(host, port); OutputStream out = new BufferedOutputStream(socket.getOutputStream()); BufferedInputStream stdIn = new BufferedInputStream(System.in); ) { socket.setEnabledProtocols(protocolList); socket.setEnabledCipherSuites(cipher); socket.startHandshake(); System.out.println("Starting handshake"); while (true) { int read = stdIn.read(buffer); if (read == -1) break; out.write(buffer, 0, read); } out.flush(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } public static SSLSocketFactory createSocketFactory(String certificatePath, String protocol) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); FileInputStream is = new FileInputStream(certificatePath); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is); is.close(); KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); caKeyStore.load(null, null); caKeyStore.setCertificateEntry("ca-certificate", cert); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); SSLContext context = SSLContext.getInstance(protocol); context.init(null, trustManagerFactory.getTrustManagers(), null); return context.getSocketFactory(); } catch(Exception e) { e.printStackTrace(); } return null; } public static String sslProtocols(String s2nProtocol) { switch (s2nProtocol) { case "TLS1.3": return "TLSv1.3"; case "TLS1.2": return "TLSv1.2"; case "TLS1.1": return "TLSv1.1"; case "TLS1.0": return "TLSv1.0"; } return null; } }
4,179
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/NamedJobInfo.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.runtime.codec.JsonType; public class NamedJobInfo implements JsonType { private final String name; private final String jobId; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public NamedJobInfo(@JsonProperty("name") String name, @JsonProperty("jobId") String jobId) { this.name = name; this.jobId = jobId; } public String getName() { return name; } public String getJobId() { return jobId; } }
4,180
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/JobCompletedReason.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; /** * Enum for the various types of Job Completions. */ public enum JobCompletedReason { /** * Job completed normally due to SLA enforcement or runtime limit. */ Normal, /** * Job completed due to an abnormal condition. */ Error, /** * Does not apply to Jobs. */ Lost, /** * Job was explicitly killed. */ Killed, /** * Unused. */ Relaunched }
4,181
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/Status.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.ArrayList; import java.util.List; import java.util.Optional; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.runtime.MantisJobState; import io.mantisrx.server.core.domain.WorkerId; //import io.mantisrx.server.master.domain.WorkerId; public class Status { private static final ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } @JsonIgnore private final Optional<WorkerId> workerId; private String jobId; private int stageNum; private int workerIndex; private int workerNumber; private String hostname = null; private TYPE type; private String message; private long timestamp; private MantisJobState state; private JobCompletedReason reason = JobCompletedReason.Normal; private List<Payload> payloads; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Status(@JsonProperty("jobId") String jobId, @JsonProperty("stageNum") int stageNum, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("type") TYPE type, @JsonProperty("message") String message, @JsonProperty("state") MantisJobState state) { this(jobId, stageNum, workerIndex, workerNumber, type, message, state, System.currentTimeMillis()); } public Status(String jobId, int stageNum, int workerIndex, int workerNumber, TYPE type, String message, MantisJobState state, long ts) { this.jobId = jobId; this.stageNum = stageNum; this.workerIndex = workerIndex; this.workerNumber = workerNumber; if (workerIndex >= 0 && workerNumber >= 0) { this.workerId = Optional.of(new WorkerId(jobId, workerIndex, workerNumber)); } else { this.workerId = Optional.empty(); } this.type = type; this.message = message; this.state = state; timestamp = ts; this.payloads = new ArrayList<>(); } public String getJobId() { return jobId; } public int getStageNum() { return stageNum; } public void setStageNum(int stageNum) { this.stageNum = stageNum; } public int getWorkerIndex() { return workerIndex; } public void setWorkerIndex(int workerIndex) { this.workerIndex = workerIndex; } public int getWorkerNumber() { return workerNumber; } public Optional<WorkerId> getWorkerId() { return workerId; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public TYPE getType() { return type; } public String getMessage() { return message; } public MantisJobState getState() { return state; } public JobCompletedReason getReason() { return reason; } public void setReason(JobCompletedReason reason) { this.reason = reason; } public List<Payload> getPayloads() { return payloads; } public void setPayloads(List<Payload> payloads) { this.payloads = payloads; } public long getTimestamp() { return timestamp; } @Override public String toString() { try { return mapper.writeValueAsString(this); } catch (JsonProcessingException e) { return "Error getting string for status on job " + jobId; } } public enum TYPE { ERROR, WARN, INFO, DEBUG, HEARTBEAT } public static class Payload { private final String type; private final String data; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Payload(@JsonProperty("type") String type, @JsonProperty("data") String data) { this.type = type; this.data = data; } public String getType() { return type; } public String getData() { return data; } } }
4,182
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/ExecuteStageRequest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.net.URL; import java.util.LinkedList; import java.util.List; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.common.WorkerPorts; import io.mantisrx.runtime.MantisJobDurationType; import io.mantisrx.runtime.descriptor.SchedulingInfo; import io.mantisrx.runtime.parameter.Parameter; public class ExecuteStageRequest { private final boolean hasJobMaster; private final long subscriptionTimeoutSecs; private final long minRuntimeSecs; private final WorkerPorts workerPorts; private String jobName; private String jobId; private int workerIndex; private int workerNumber; private URL jobJarUrl; private int stage; private int totalNumStages; private int metricsPort; private List<Integer> ports = new LinkedList<Integer>(); private long timeoutToReportStart; private List<Parameter> parameters = new LinkedList<Parameter>(); private SchedulingInfo schedulingInfo; private MantisJobDurationType durationType; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public ExecuteStageRequest(@JsonProperty("jobName") String jobName, @JsonProperty("jobID") String jobId, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("jobJarUrl") URL jobJarUrl, @JsonProperty("stage") int stage, @JsonProperty("totalNumStages") int totalNumStages, @JsonProperty("ports") List<Integer> ports, @JsonProperty("timeoutToReportStart") long timeoutToReportStart, @JsonProperty("metricsPort") int metricsPort, @JsonProperty("parameters") List<Parameter> parameters, @JsonProperty("schedulingInfo") SchedulingInfo schedulingInfo, @JsonProperty("durationType") MantisJobDurationType durationType, @JsonProperty("subscriptionTimeoutSecs") long subscriptionTimeoutSecs, @JsonProperty("minRuntimeSecs") long minRuntimeSecs, @JsonProperty("workerPorts") WorkerPorts workerPorts ) { this.jobName = jobName; this.jobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.jobJarUrl = jobJarUrl; this.stage = stage; this.totalNumStages = totalNumStages; this.ports.addAll(ports); this.metricsPort = metricsPort; this.timeoutToReportStart = timeoutToReportStart; if (parameters != null) { this.parameters = parameters; } else { this.parameters = new LinkedList<>(); } this.schedulingInfo = schedulingInfo; this.durationType = durationType; hasJobMaster = schedulingInfo != null && schedulingInfo.forStage(0) != null; this.subscriptionTimeoutSecs = subscriptionTimeoutSecs; this.minRuntimeSecs = minRuntimeSecs; this.workerPorts = workerPorts; } public SchedulingInfo getSchedulingInfo() { return schedulingInfo; } public List<Parameter> getParameters() { return parameters; } public int getMetricsPort() { return metricsPort; } public String getJobName() { return jobName; } public String getJobId() { return jobId; } public int getWorkerIndex() { return workerIndex; } public int getWorkerNumber() { return workerNumber; } public URL getJobJarUrl() { return jobJarUrl; } public int getStage() { return stage; } public int getTotalNumStages() { return totalNumStages; } public List<Integer> getPorts() { return ports; } public WorkerPorts getWorkerPorts() { return workerPorts; } public long getTimeoutToReportStart() { return timeoutToReportStart; } public MantisJobDurationType getDurationType() { return durationType; } public boolean getHasJobMaster() { return hasJobMaster; } public long getSubscriptionTimeoutSecs() { return subscriptionTimeoutSecs; } public long getMinRuntimeSecs() { return minRuntimeSecs; } @Override public String toString() { return "ExecuteStageRequest{" + "jobName='" + jobName + '\'' + ", jobId='" + jobId + '\'' + ", workerIndex=" + workerIndex + ", workerNumber=" + workerNumber + ", jobJarUrl=" + jobJarUrl + ", stage=" + stage + ", totalNumStages=" + totalNumStages + ", metricsPort=" + metricsPort + ", ports=" + ports + ", timeoutToReportStart=" + timeoutToReportStart + ", parameters=" + parameters + ", schedulingInfo=" + schedulingInfo + ", durationType=" + durationType + ", hasJobMaster=" + hasJobMaster + ", subscriptionTimeoutSecs=" + subscriptionTimeoutSecs + ", minRuntimeSecs=" + minRuntimeSecs + ", workerPorts=" + workerPorts + '}'; } }
4,183
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/WorkerHost.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.List; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.runtime.MantisJobState; public class WorkerHost { private final MantisJobState state; private final int workerNumber; private final int workerIndex; private final String host; private final List<Integer> port; private final int metricsPort; private final int customPort; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public WorkerHost(@JsonProperty("host") String host, @JsonProperty("workerIndex") int workerIndex, @JsonProperty("port") List<Integer> port, @JsonProperty("state") MantisJobState state, @JsonProperty("workerNumber") int workerNumber, @JsonProperty("metricsPort") int metricsPort, @JsonProperty("customPort") int customPort) { this.host = host; this.workerIndex = workerIndex; this.port = port; this.state = state; this.workerNumber = workerNumber; this.metricsPort = metricsPort; this.customPort = customPort; } public int getWorkerNumber() { return workerNumber; } public MantisJobState getState() { return state; } public String getHost() { return host; } public List<Integer> getPort() { return port; } public int getWorkerIndex() { return workerIndex; } public int getMetricsPort() { return metricsPort; } public int getCustomPort() { return customPort; } @Override public String toString() { return "WorkerHost [state=" + state + ", workerIndex=" + workerIndex + ", host=" + host + ", port=" + port + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((host == null) ? 0 : host.hashCode()); for (int p : port) result = prime * result + p; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WorkerHost other = (WorkerHost) obj; if (host == null) { if (other.host != null) return false; } else if (!host.equals(other.host)) return false; if (port == null) { return other.port == null; } else { if (other.port == null) return false; if (port.size() != other.port.size()) return false; for (int p = 0; p < port.size(); p++) if (port.get(p) != other.port.get(p)) return false; } return true; } }
4,184
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/CoreConfiguration.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import io.mantisrx.common.metrics.MetricsPublisher; import org.skife.config.Config; import org.skife.config.Default; /** * The configurations declared in this interface should be the ones that are shared by both worker and master (and * potentially other sub-projects). */ public interface CoreConfiguration { @Config("mantis.zookeeper.connectionTimeMs") @Default("10000") int getZkConnectionTimeoutMs(); @Config("mantis.zookeeper.connection.retrySleepMs") @Default("500") int getZkConnectionRetrySleepMs(); @Config("mantis.zookeeper.connection.retryCount") @Default("5") int getZkConnectionMaxRetries(); @Config("mantis.zookeeper.connectString") @Default("localhost:2181") String getZkConnectionString(); @Config("mantis.zookeeper.leader.announcement.path") @Default("/leader") String getLeaderAnnouncementPath(); @Config("mantis.zookeeper.root") String getZkRoot(); @Config("mantis.localmode") @Default("true") boolean isLocalMode(); @Config("mantis.metricsPublisher") @Default("io.mantisrx.common.metrics.MetricsPublisherNoOp") MetricsPublisher getMetricsPublisher(); @Config("mantis.metricsPublisher.publishFrequencyInSeconds") @Default("15") int getMetricsPublisherFrequencyInSeconds(); @Config("mantis.metricsPublisher.config.prefix") @Default("") String getMetricsPublisherConfigPrefix(); }
4,185
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/PostJobStatusRequest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class PostJobStatusRequest { private String jobId; private Status status; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public PostJobStatusRequest(@JsonProperty("jobId") String jobId, @JsonProperty("status") Status status) { this.jobId = jobId; this.status = status; } public String getJobId() { return jobId; } public Status getStatus() { return status; } }
4,186
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/StatusPayloads.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class StatusPayloads { public enum Type { SubscriptionState, IncomingDataDrop, ResourceUsage } public static class DataDropCounts { private final long onNextCount; private final long droppedCount; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public DataDropCounts(@JsonProperty("onNextCount") long onNextCount, @JsonProperty("droppedCount") long droppedCount) { this.onNextCount = onNextCount; this.droppedCount = droppedCount; } public long getOnNextCount() { return onNextCount; } public long getDroppedCount() { return droppedCount; } } public static class ResourceUsage { private final double cpuLimit; private final double cpuUsageCurrent; private final double cpuUsagePeak; private final double memLimit; private final double memCacheCurrent; private final double memCachePeak; private final double totMemUsageCurrent; private final double totMemUsagePeak; private final double nwBytesCurrent; private final double nwBytesPeak; @JsonCreator public ResourceUsage(@JsonProperty("cpuLimit") double cpuLimit, @JsonProperty("cpuUsageCurrent") double cpuUsageCurrent, @JsonProperty("cpuUsagePeak") double cpuUsagePeak, @JsonProperty("memLimit") double memLimit, @JsonProperty("memCacheCurrent") double memCacheCurrent, @JsonProperty("memCachePeak") double memCachePeak, @JsonProperty("totMemUsageCurrent") double totMemUsageCurrent, @JsonProperty("totMemUsagePeak") double totMemUsagePeak, @JsonProperty("nwBytesCurrent") double nwBytesCurrent, @JsonProperty("nwBytesPeak") double nwBytesPeak) { this.cpuLimit = cpuLimit; this.cpuUsageCurrent = cpuUsageCurrent; this.cpuUsagePeak = cpuUsagePeak; this.memLimit = memLimit; this.memCacheCurrent = memCacheCurrent; this.memCachePeak = memCachePeak; this.totMemUsageCurrent = totMemUsageCurrent; this.totMemUsagePeak = totMemUsagePeak; this.nwBytesCurrent = nwBytesCurrent; this.nwBytesPeak = nwBytesPeak; } public double getCpuLimit() { return cpuLimit; } public double getCpuUsageCurrent() { return cpuUsageCurrent; } public double getCpuUsagePeak() { return cpuUsagePeak; } public double getMemLimit() { return memLimit; } public double getMemCacheCurrent() { return memCacheCurrent; } public double getMemCachePeak() { return memCachePeak; } public double getTotMemUsageCurrent() { return totMemUsageCurrent; } public double getTotMemUsagePeak() { return totMemUsagePeak; } public double getNwBytesCurrent() { return nwBytesCurrent; } public double getNwBytesPeak() { return nwBytesPeak; } @Override public String toString() { return "cpuLimit=" + cpuLimit + ", cpuUsageCurrent=" + cpuUsageCurrent + ", cpuUsagePeak=" + cpuUsagePeak + ", memLimit=" + memLimit + ", memCacheCurrent=" + memCacheCurrent + ", memCachePeak=" + memCachePeak + ", totMemUsageCurrent=" + totMemUsageCurrent + ", totMemUsagePeak=" + totMemUsagePeak + ", nwBytesCurrent=" + nwBytesCurrent + ", nwBytesPeak=" + nwBytesPeak; } } }
4,187
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/JobSchedulingInfo.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.Map; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.runtime.codec.JsonType; public class JobSchedulingInfo implements JsonType { public static final String HB_JobId = "HB_JobId"; public static final String SendHBParam = "sendHB"; private String jobId; private Map<Integer, WorkerAssignments> workerAssignments; // index by stage num @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobSchedulingInfo(@JsonProperty("jobId") String jobId, @JsonProperty("workerAssignments") Map<Integer, WorkerAssignments> workerAssignments) { this.jobId = jobId; this.workerAssignments = workerAssignments; } public String getJobId() { return jobId; } public Map<Integer, WorkerAssignments> getWorkerAssignments() { return workerAssignments; } @Override public String toString() { return "SchedulingChange [jobId=" + jobId + ", workerAssignments=" + workerAssignments + "]"; } }
4,188
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/Service.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; public interface Service { void start(); void shutdown(); void enterActiveMode(); }
4,189
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/WorkerTopologyInfo.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.HashMap; import java.util.Map; import io.mantisrx.runtime.descriptor.StageSchedulingInfo; public class WorkerTopologyInfo { private static final String MANTIS_JOB_NAME = "MANTIS_JOB_NAME"; private static final String MANTIS_JOB_ID = "MANTIS_JOB_ID"; private static final String MANTIS_WORKER_INDEX = "MANTIS_WORKER_INDEX"; private static final String MANTIS_WORKER_NUMBER = "MANTIS_WORKER_NUMBER"; private static final String MANTIS_WORKER_STAGE_NUMBER = "MANTIS_WORKER_STAGE_NUMBER"; private static final String MANTIS_NUM_STAGES = "MANTIS_NUM_STAGES"; private static final String MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS = "MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS"; private static final String MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS = "MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS"; private static final String MANTIS_METRICS_PORT = "MANTIS_METRICS_PORT"; private static final String MANTIS_WORKER_CUSTOM_PORT = "MANTIS_WORKER_CUSTOM_PORT"; public static class Data { private String jobName; private String JobId; private int workerIndex; private int workerNumber; private int stageNumber; private int numStages; private int prevStageInitialNumWorkers = -1; private int nextStageInitialNumWorkers = -1; private int metricsPort; public Data(String jobName, String jobId, int workerIndex, int workerNumber, int stageNumber, int numStages) { this.jobName = jobName; JobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.stageNumber = stageNumber; this.numStages = numStages; } public Data(String jobName, String jobId, int workerIndex, int workerNumber, int stageNumber, int numStages, int prevStageInitialNumWorkers, int nextStageInitialNumWorkers, int metricsPort) { this.jobName = jobName; JobId = jobId; this.workerIndex = workerIndex; this.workerNumber = workerNumber; this.stageNumber = stageNumber; this.numStages = numStages; this.prevStageInitialNumWorkers = prevStageInitialNumWorkers; this.nextStageInitialNumWorkers = nextStageInitialNumWorkers; this.metricsPort = metricsPort; } public String getJobName() { return jobName; } public String getJobId() { return JobId; } public int getWorkerIndex() { return workerIndex; } public int getWorkerNumber() { return workerNumber; } public int getStageNumber() { return stageNumber; } public int getNumStages() { return numStages; } public int getPrevStageInitialNumWorkers() { return prevStageInitialNumWorkers; } public int getNextStageInitialNumWorkers() { return nextStageInitialNumWorkers; } public int getMetricsPort() { return metricsPort; } } public static class Writer { private final Map<String, String> envVars; public Writer(ExecuteStageRequest request) { envVars = new HashMap<>(); envVars.put(MANTIS_JOB_NAME, request.getJobName()); envVars.put(MANTIS_JOB_ID, request.getJobId()); envVars.put(MANTIS_WORKER_INDEX, request.getWorkerIndex() + ""); envVars.put(MANTIS_WORKER_NUMBER, request.getWorkerNumber() + ""); envVars.put(MANTIS_WORKER_STAGE_NUMBER, request.getStage() + ""); envVars.put(MANTIS_NUM_STAGES, request.getTotalNumStages() + ""); final int totalNumWorkerStages = request.getTotalNumStages() - (request.getHasJobMaster() ? 1 : 0); if (totalNumWorkerStages > 1 && request.getStage() > 1) { StageSchedulingInfo prevStage = request.getSchedulingInfo().forStage(request.getStage() - 1); envVars.put(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS, prevStage.getNumberOfInstances() + ""); if (totalNumWorkerStages > request.getStage()) { StageSchedulingInfo nextStage = request.getSchedulingInfo().forStage( request.getStage() + 1); envVars.put(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS, nextStage.getNumberOfInstances() + ""); } } envVars.put(MANTIS_METRICS_PORT, request.getMetricsPort() + ""); envVars.put(MANTIS_WORKER_CUSTOM_PORT, request.getWorkerPorts().getCustomPort() + ""); } public Map<String, String> getEnvVars() { return envVars; } } public static class Reader { private static Data data; static { data = new Data( System.getenv(MANTIS_JOB_NAME), System.getenv(MANTIS_JOB_ID), System.getenv(MANTIS_WORKER_INDEX) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_INDEX)), System.getenv(MANTIS_WORKER_NUMBER) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_NUMBER)), System.getenv(MANTIS_WORKER_STAGE_NUMBER) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_WORKER_STAGE_NUMBER)), System.getenv(MANTIS_NUM_STAGES) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_NUM_STAGES)), System.getenv(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_PREV_STAGE_INITIAL_NUM_WORKERS)), System.getenv(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_NEXT_STAGE_INITIAL_NUM_WORKERS)), System.getenv(MANTIS_METRICS_PORT) == null ? -1 : Integer.parseInt(System.getenv(MANTIS_METRICS_PORT)) ); } public static Data getData() { return data; } } }
4,190
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/WorkerAssignments.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.Map; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; public class WorkerAssignments { private int stage; private int numWorkers; private int activeWorkers; private Map<Integer, WorkerHost> hosts; // lookup by workerNumber @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public WorkerAssignments(@JsonProperty("stage") Integer stage, @JsonProperty("numWorkers") Integer numWorkers, @JsonProperty("hosts") Map<Integer, WorkerHost> hosts) { this.stage = stage; this.numWorkers = numWorkers; this.hosts = hosts; } public int getStage() { return stage; } public int getNumWorkers() { return numWorkers; } public void setNumWorkers(int numWorkers) { this.numWorkers = numWorkers; } public int getActiveWorkers() { return activeWorkers; } public void setActiveWorkers(int activeWorkers) { this.activeWorkers = activeWorkers; } public Map<Integer, WorkerHost> getHosts() { return hosts; } @Override public String toString() { return "WorkerAssignments [stage=" + stage + ", numWorkers=" + numWorkers + ", hosts=" + hosts + "]"; } }
4,191
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/WorkerOutlier.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.mantisrx.server.core.stats.SimpleStats; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; import rx.functions.Action1; import rx.observers.SerializedObserver; import rx.subjects.PublishSubject; public class WorkerOutlier { private static final Logger logger = LoggerFactory.getLogger(WorkerOutlier.class); private final PublishSubject<DataPoint> subject = PublishSubject.create(); private final Observer<DataPoint> observer = new SerializedObserver<>(subject); private final long cooldownSecs; private final Action1<Integer> outlierTrigger; private long lastTriggeredAt = 0L; private long minDataPoints = 16; private long maxDataPoints = 20; public WorkerOutlier(long cooldownSecs, Action1<Integer> outlierTrigger) { this.cooldownSecs = cooldownSecs; if (outlierTrigger == null) throw new NullPointerException("outlierTrigger is null"); this.outlierTrigger = outlierTrigger; start(); } private void start() { logger.info("Starting Worker outlier detector"); final Map<Integer, Double> values = new HashMap<>(); final Map<Integer, List<Boolean>> isOutlierMap = new HashMap<>(); subject .doOnNext(new Action1<DataPoint>() { @Override public void call(DataPoint dataPoint) { values.put(dataPoint.index, dataPoint.value); final int currSize = values.size(); if (currSize > dataPoint.numWorkers) { for (int i = dataPoint.numWorkers; i < currSize; i++) { values.remove(i); isOutlierMap.remove(i); } } SimpleStats simpleStats = new SimpleStats(values.values()); List<Boolean> booleans = isOutlierMap.get(dataPoint.index); if (booleans == null) { booleans = new ArrayList<>(); isOutlierMap.put(dataPoint.index, booleans); } if (booleans.size() >= maxDataPoints) // for now hard code to 20 items booleans.remove(0); booleans.add(dataPoint.value > simpleStats.getOutlierThreshold()); if ((System.currentTimeMillis() - lastTriggeredAt) > cooldownSecs * 1000) { if (booleans.size() > minDataPoints) { int total = 0; int outlierCnt = 0; for (boolean b : booleans) { total++; if (b) outlierCnt++; } if (outlierCnt > (Math.round((double) total * 0.7))) { // again, hardcode for now outlierTrigger.call(dataPoint.index); lastTriggeredAt = System.currentTimeMillis(); booleans.clear(); } } } } }) .subscribe(); } public void addDataPoint(int workerIndex, double value, int numWorkers) { observer.onNext(new DataPoint(workerIndex, value, numWorkers)); } public void completed() { observer.onCompleted(); } private static class DataPoint { private final int index; private final double value; private final int numWorkers; private DataPoint(int index, double value, int numWorkers) { this.index = index; this.value = value; this.numWorkers = numWorkers; } } }
4,192
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/BaseService.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Action0; public abstract class BaseService implements Service { private static AtomicInteger SERVICES_COUNTER = new AtomicInteger(0); private final boolean awaitsActiveMode; private final ActiveMode activeMode = new ActiveMode(); private final int myServiceCount; private BaseService predecessor = null; protected BaseService() { this(false); } protected BaseService(boolean awaitsActiveMode) { this.awaitsActiveMode = awaitsActiveMode; if (!this.awaitsActiveMode) { activeMode.isInited.set(true); } myServiceCount = SERVICES_COUNTER.getAndIncrement(); } @Override public abstract void start(); /** * If this is set to await active mode, then, asynchronously (in a new thread) waits for entering active mode * and then calls the action parameter. It then also waits for any predecessor to be initialized before setting this * as initialized. * If this is set to not await active mode, then it just sets this as initialized and returns. * * @param onActive Action to call after waiting for entering active mode. */ protected void awaitActiveModeAndStart(Action0 onActive) { activeMode.waitAndStart(onActive, predecessor); } protected boolean getIsInited() { return activeMode.getIsInited() && (predecessor == null || predecessor.getIsInited()); } @Override public void enterActiveMode() { activeMode.enterActiveMode(); } @Override public void shutdown() { } public void addPredecessor(BaseService service) { this.predecessor = service; } public int getMyServiceCount() { return myServiceCount; } public class ActiveMode { private final AtomicBoolean isLeaderMode = new AtomicBoolean(false); private final AtomicBoolean isInited = new AtomicBoolean(false); Logger logger = LoggerFactory.getLogger(ActiveMode.class); public boolean getIsInited() { return isInited.get(); } private void awaitLeaderMode() { while (!isLeaderMode.get()) { synchronized (isLeaderMode) { try { isLeaderMode.wait(10000); } catch (InterruptedException e) { logger.info("Interrupted waiting for leaderModeLatch"); Thread.currentThread().interrupt(); } } } } public void waitAndStart(final Action0 onActive, final BaseService predecessor) { logger.info(myServiceCount + ": Setting up thread to wait for entering leader mode"); Runnable runnable = new Runnable() { @Override public void run() { awaitLeaderMode(); logger.info(myServiceCount + ": done waiting for leader mode"); if (predecessor != null) { predecessor.activeMode.awaitInit(); } logger.info(myServiceCount + ": done waiting for predecessor init"); if (onActive != null) { onActive.call(); } synchronized (isInited) { isInited.set(true); isInited.notify(); } } }; Thread thr = new Thread(runnable, "BaseService-LeaderModeWaitThread-" + myServiceCount); thr.setDaemon(true); thr.start(); } private void awaitInit() { while (!isInited.get()) { synchronized (isInited) { try { isInited.wait(5000); } catch (InterruptedException e) { logger.info("Interrupted waiting for predecessor init"); Thread.currentThread().interrupt(); } } } if (predecessor != null) { predecessor.activeMode.awaitInit(); } } public void enterActiveMode() { logger.info(myServiceCount + ": Entering leader mode"); synchronized (isLeaderMode) { isLeaderMode.set(true); isLeaderMode.notify(); } } } }
4,193
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/MetricsCoercer.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.Map.Entry; import java.util.Properties; import io.mantisrx.common.metrics.MetricsPublisher; import org.skife.config.Coercer; import org.skife.config.Coercible; public class MetricsCoercer implements Coercible<MetricsPublisher> { private Properties props; public MetricsCoercer(Properties props) { this.props = props; } @Override public Coercer<MetricsPublisher> accept(Class<?> clazz) { if (MetricsPublisher.class.isAssignableFrom(clazz)) { return new Coercer<MetricsPublisher>() { @Override public MetricsPublisher coerce(String className) { try { // get properties for publisher Properties publishProperties = new Properties(); String configPrefix = (String) props.get("mantis.metricsPublisher.config.prefix"); if (configPrefix != null && configPrefix.length() > 0) { for (Entry<Object, Object> entry : props.entrySet()) { if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith(configPrefix)) { publishProperties.put(entry.getKey(), entry.getValue()); } } } return (MetricsPublisher) Class.forName(className).getConstructor(Properties.class) .newInstance(publishProperties); } catch (Exception e) { throw new IllegalArgumentException( String.format( "The value %s is not a valid class name for %s implementation. ", className, MetricsPublisher.class.getName() ), e); } } }; } return null; } }
4,194
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/JobAssignmentResult.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core; import java.util.List; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty; import io.mantisrx.runtime.codec.JsonType; public class JobAssignmentResult implements JsonType { private final String jobId; private final List<Failure> failures; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public JobAssignmentResult(@JsonProperty("jobId") String jobId, @JsonProperty("failures") List<Failure> failures) { this.jobId = jobId; this.failures = failures; } private static boolean failuresIdentical(List<Failure> first, List<Failure> second) { if (first == null) { return second == null; } if (second == null) return false; if (first.size() != second.size()) return false; int item = 0; for (Failure f : first) { boolean found = false; for (int fi = 0; fi < second.size() && !found; fi++) { if (f.isIdentical(second.get(fi))) found = true; } if (!found) return false; } return true; } public String getJobId() { return jobId; } public List<Failure> getFailures() { return failures; } public boolean isIdentical(JobAssignmentResult that) { if (that == null) return false; if (this == that) return true; if (!jobId.equals(that.jobId)) return false; return failuresIdentical(failures, that.failures); } public static class Failure { private int workerNumber; private String type; private double asking; private double used; private double available; @JsonCreator @JsonIgnoreProperties(ignoreUnknown = true) public Failure(@JsonProperty("workerNumber") int workerNumber, @JsonProperty("type") String type, @JsonProperty("asking") double asking, @JsonProperty("used") double used, @JsonProperty("available") double available) { this.workerNumber = workerNumber; this.type = type; this.asking = asking; this.used = used; this.available = available; } public int getWorkerNumber() { return workerNumber; } public String getType() { return type; } public double getAsking() { return asking; } public double getUsed() { return used; } public double getAvailable() { return available; } private boolean isIdentical(Failure that) { if (that == null) return false; return workerNumber == that.workerNumber && type.equals(that.type) && asking == that.asking && used == that.used && available == that.available; } } }
4,195
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/metrics/MetricsPublisherService.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.metrics; import java.util.HashMap; import java.util.Map; import io.mantisrx.common.metrics.MetricsPublisher; import io.mantisrx.server.core.Service; public class MetricsPublisherService implements Service { private MetricsPublisher publisher; private int publishFrequency; private Map<String, String> commonTags = new HashMap<>(); public MetricsPublisherService(MetricsPublisher publisher, int publishFrequency, Map<String, String> commonTags) { this.publisher = publisher; this.publishFrequency = publishFrequency; this.commonTags.putAll(commonTags); } public MetricsPublisherService(MetricsPublisher publisher, int publishFrequency) { this(publisher, publishFrequency, new HashMap<String, String>()); } @Override public void start() { publisher.start(publishFrequency, commonTags); } @Override public void shutdown() { publisher.shutdown(); } @Override public void enterActiveMode() {} }
4,196
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/metrics/MetricsServerService.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.metrics; import java.util.Map; import io.mantisrx.common.metrics.MetricsServer; import io.mantisrx.server.core.Service; public class MetricsServerService implements Service { private MetricsServer server; public MetricsServerService(final int port, final int publishRateInSeconds, final Map<String, String> tags) { server = new MetricsServer(port, publishRateInSeconds, tags); } @Override public void start() { server.start(); } @Override public void shutdown() { server.shutdown(); } @Override public void enterActiveMode() {} }
4,197
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/zookeeper/CuratorService.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.zookeeper; import io.mantisrx.shaded.com.google.common.util.concurrent.MoreExecutors; import io.mantisrx.common.metrics.Gauge; import io.mantisrx.common.metrics.Metrics; import io.mantisrx.common.metrics.MetricsRegistry; import io.mantisrx.server.core.BaseService; import io.mantisrx.server.core.CoreConfiguration; import io.mantisrx.server.core.Service; import io.mantisrx.server.core.master.MasterDescription; import io.mantisrx.server.core.master.MasterMonitor; import io.mantisrx.server.core.master.ZookeeperMasterMonitor; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.GzipCompressionProvider; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.utils.ZKPaths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This {@link Service} implementation is responsible for managing the lifecycle of a {@link org.apache.curator.framework.CuratorFramework} * instance. */ public class CuratorService extends BaseService { private static final Logger LOG = LoggerFactory.getLogger(CuratorService.class); private static final String isConnectedGaugeName = "isConnected"; private final CuratorFramework curator; private final ZookeeperMasterMonitor masterMonitor; private final CoreConfiguration configs; private final Gauge isConnectedGauge; public CuratorService(CoreConfiguration configs, MasterDescription initialMasterDescription) { super(false); this.configs = configs; Metrics m = new Metrics.Builder() .name(CuratorService.class.getCanonicalName()) .addGauge(isConnectedGaugeName) .build(); m = MetricsRegistry.getInstance().registerAndGet(m); isConnectedGauge = m.getGauge(isConnectedGaugeName); curator = CuratorFrameworkFactory.builder() .compressionProvider(new GzipCompressionProvider()) .connectionTimeoutMs(configs.getZkConnectionTimeoutMs()) .retryPolicy(new ExponentialBackoffRetry(configs.getZkConnectionRetrySleepMs(), configs.getZkConnectionMaxRetries())) .connectString(configs.getZkConnectionString()) .build(); masterMonitor = new ZookeeperMasterMonitor( curator, ZKPaths.makePath(configs.getZkRoot(), configs.getLeaderAnnouncementPath()), initialMasterDescription); } private void setupCuratorListener() { LOG.info("Setting up curator state change listener"); curator.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState.isConnected()) { LOG.info("Curator connected"); isConnectedGauge.set(1L); } else { // ToDo: determine if it is safe to restart our service instead of committing suicide LOG.error("Curator connection lost"); isConnectedGauge.set(0L); } } }, MoreExecutors.newDirectExecutorService()); } @Override public void start() { isConnectedGauge.set(0L); setupCuratorListener(); curator.start(); masterMonitor.start(); } @Override public void shutdown() { try { masterMonitor.shutdown(); curator.close(); } catch (Exception e) { // A shutdown failure should not affect the subsequent shutdowns, so // we just warn here LOG.warn("Failed to shut down the curator service: " + e.getMessage(), e); } } public CuratorFramework getCurator() { return curator; } public MasterMonitor getMasterMonitor() { return masterMonitor; } }
4,198
0
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core
Create_ds/mantis-control-plane/core/src/main/java/io/mantisrx/server/core/json/DefaultObjectMapper.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.server.core.json; import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonFactory; import io.mantisrx.shaded.com.fasterxml.jackson.core.Version; import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.MapperFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper; import io.mantisrx.shaded.com.fasterxml.jackson.databind.SerializationFeature; import io.mantisrx.shaded.com.fasterxml.jackson.databind.module.SimpleModule; import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module; public class DefaultObjectMapper extends ObjectMapper { private static DefaultObjectMapper INSTANCE = new DefaultObjectMapper(); private DefaultObjectMapper() { this(null); } public DefaultObjectMapper(JsonFactory factory) { super(factory); SimpleModule serializerModule = new SimpleModule("Mantis Default JSON Serializer", new Version(1, 0, 0, null)); registerModule(serializerModule); configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); configure(MapperFeature.AUTO_DETECT_GETTERS, false); configure(MapperFeature.AUTO_DETECT_FIELDS, false); registerModule(new Jdk8Module()); } public static DefaultObjectMapper getInstance() { return INSTANCE; } }
4,199