blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
63f0e024fc95628b37c78dcf40f2bade1c409a21
0800f457bf20efdcc41ef1262ea30ebdf56c2a6e
/src/main/java/decorator/Surgeon.java
59c3e8f24a595aad86a3ccfad4d0dc9b9af35a95
[]
no_license
blokhina1605/CDP
a4f4983af4b9192cfda8d8fc39cf4963c71b91e9
b21257b0d68bf40cbbc3021b1c6ca6221f64d842
refs/heads/master
2021-01-19T14:57:29.815410
2015-09-16T18:19:12
2015-09-16T18:19:12
42,604,804
0
0
null
null
null
null
UTF-8
Java
false
false
311
java
package decorator; /** * Created by Yevheniia_Blokhina on 9/16/2015. */ public class Surgeon extends Specialty { public Surgeon(InterfaceDoctor doctor) { super(doctor); } @Override public String treat() { return super.treat() + "And your hand will soon disappear. "; } }
5572967597cc81a3371f500bad8bad9d2d9f43c9
8526b8ef292657e24d72571905a5f56ec1a2ff2f
/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableFilterToCalcRule.java
db260a011f9b7c6e89c75268e2e9552df5433235
[ "Apache-2.0", "MIT" ]
permissive
jh3507/calcite
cac7e8f08ddefe7e80f12d97d842a6bc1f0d8938
532f903fe495d741053619c13a51537e57dcd619
refs/heads/master
2021-06-27T17:43:24.208096
2020-10-03T23:33:29
2020-10-07T17:49:59
162,769,449
2
1
Apache-2.0
2018-12-22T00:32:51
2018-12-22T00:32:51
null
UTF-8
Java
false
false
2,911
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.adapter.enumerable; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelRule; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexProgram; import org.apache.calcite.rex.RexProgramBuilder; import org.apache.calcite.tools.RelBuilderFactory; /** Variant of {@link org.apache.calcite.rel.rules.FilterToCalcRule} for * {@link org.apache.calcite.adapter.enumerable.EnumerableConvention enumerable calling convention}. * * @see EnumerableRules#ENUMERABLE_FILTER_TO_CALC_RULE */ public class EnumerableFilterToCalcRule extends RelRule<EnumerableFilterToCalcRule.Config> { /** Creates an EnumerableFilterToCalcRule. */ protected EnumerableFilterToCalcRule(Config config) { super(config); } @Deprecated // to be removed before 2.0 public EnumerableFilterToCalcRule(RelBuilderFactory relBuilderFactory) { this(Config.DEFAULT.withRelBuilderFactory(relBuilderFactory) .as(Config.class)); } @Override public void onMatch(RelOptRuleCall call) { final EnumerableFilter filter = call.rel(0); final RelNode input = filter.getInput(); // Create a program containing a filter. final RexBuilder rexBuilder = filter.getCluster().getRexBuilder(); final RelDataType inputRowType = input.getRowType(); final RexProgramBuilder programBuilder = new RexProgramBuilder(inputRowType, rexBuilder); programBuilder.addIdentity(); programBuilder.addCondition(filter.getCondition()); final RexProgram program = programBuilder.getProgram(); final EnumerableCalc calc = EnumerableCalc.create(input, program); call.transformTo(calc); } /** Rule configuration. */ public interface Config extends RelRule.Config { Config DEFAULT = EMPTY .withOperandSupplier(b -> b.operand(EnumerableFilter.class).anyInputs()) .as(Config.class); @Override default EnumerableFilterToCalcRule toRule() { return new EnumerableFilterToCalcRule(this); } } }
7d99cbfbfc3c73dcc5fa7d624d52a5c0f3184629
d7c5121237c705b5847e374974b39f47fae13e10
/airspan.netspan/src/main/java/Netspan/NBI_15_5/Server/CtsGetResponse.java
849c93e727ee0c980170836701141fbeb0e6803d
[]
no_license
AirspanNetworks/SWITModules
8ae768e0b864fa57dcb17168d015f6585d4455aa
7089a4b6456621a3abd601cc4592d4b52a948b57
refs/heads/master
2022-11-24T11:20:29.041478
2020-08-09T07:20:03
2020-08-09T07:20:03
184,545,627
1
0
null
2022-11-16T12:35:12
2019-05-02T08:21:55
Java
UTF-8
Java
false
false
1,568
java
package Netspan.NBI_15_5.Server; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CtsGetResult" type="{http://Airspan.Netspan.WebServices}CtsGetResult" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "ctsGetResult" }) @XmlRootElement(name = "CtsGetResponse") public class CtsGetResponse { @XmlElement(name = "CtsGetResult") protected CtsGetResult ctsGetResult; /** * Gets the value of the ctsGetResult property. * * @return * possible object is * {@link CtsGetResult } * */ public CtsGetResult getCtsGetResult() { return ctsGetResult; } /** * Sets the value of the ctsGetResult property. * * @param value * allowed object is * {@link CtsGetResult } * */ public void setCtsGetResult(CtsGetResult value) { this.ctsGetResult = value; } }
[ "build.Airspan.com" ]
build.Airspan.com
ae1d15adb6370006036e5e1b56302b7da07d0469
071a9fa7cfee0d1bf784f6591cd8d07c6b2a2495
/corpus/norm-class/tomcat70/307.java
fd814fe5c3cbd2d5bf1b0aea03acb714e3961bcc
[ "MIT" ]
permissive
masud-technope/ACER-Replication-Package-ASE2017
41a7603117f01382e7e16f2f6ae899e6ff3ad6bb
cb7318a729eb1403004d451a164c851af2d81f7a
refs/heads/master
2021-06-21T02:19:43.602864
2021-02-13T20:44:09
2021-02-13T20:44:09
187,748,164
0
0
null
null
null
null
UTF-8
Java
false
false
974
java
licensed apache software foundation asf contributor license agreements notice file distributed work additional copyright ownership asf licenses file apache license version license file compliance license copy license http apache org licenses license required applicable law agreed writing software distributed license distributed basis warranties conditions kind express implied license specific language governing permissions limitations license org apache util java input stream inputstream tester suppress warnings suppresswarnings unused test a testa input stream inputstream param string param suppress warnings suppresswarnings unused test a testa param string param suppress warnings suppresswarnings unused test b testb input stream inputstream param string param suppress warnings suppresswarnings unused test b testb param string param suppress warnings suppresswarnings unused test c testc param suppress warnings suppresswarnings unused test d testd string param
f421423fbdf83e19983bbba99172aa17fee0d614
f4724029e63a5206dd1d72bbe6dd49bb14c2f9ea
/nawr.java
ab98e6630215bd26b10e724637779f5730d99fd7
[]
no_license
ruma24/addition
44b2669b8bf9084ff609a32c03f3442a89a9ee3c
b49eca9626c56fd8a423657a3ac101de0e855af6
refs/heads/master
2020-03-26T03:36:51.993117
2018-08-12T12:31:04
2018-08-12T12:31:04
144,463,189
0
0
null
null
null
null
UTF-8
Java
false
false
418
java
import java.util.*; public class nawr { int a,b,c; Scanner s=new Scanner(System.in); public int add() { System.out.println("Enter the A value="); a=s.nextInt(); System.out.println("Enter the B value="); b=s.nextInt(); c=a+b; return c; } public static void main(String ar[]) { nawr g=new nawr(); int v; v=g.add(); System.out.println("The sum of "+g.a+"+"+g.b+"="+v); } }
0b3887906c9f1b1b87010fc50836d87a529714ea
401c3cf04507f577bfc285da86a6af25ecea7a69
/CoastLine 2.1/app/src/main/java/com/coastline20/activity/miaoli/tongxiao/Tongxiao3Activity.java
1f595d9e2555d4baeff9f390ffb55d78cfc22763
[]
no_license
SpicyBoyd/CoastLineApp
59139e76f7fa7af8b8e55955320ee53e4ddf6578
8f24f63de925f4c30ac35527f7efd21f13b481b4
refs/heads/master
2021-09-14T09:15:35.834398
2018-05-11T04:24:55
2018-05-11T04:24:55
124,340,147
1
0
null
null
null
null
UTF-8
Java
false
false
3,447
java
package com.coastline20.activity.miaoli.tongxiao; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import com.coastline20.R; import com.coastline20.entity.SpotEntity; import com.coastline20.adapter.SpotPagerAdapter; public class Tongxiao3Activity extends AppCompatActivity { private CollapsingToolbarLayout toolbarLayout; private ImageView imageView; private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private String[] titles; private SpotEntity entity; // Spot 修改資料的地方 private void init() { toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout); imageView = (ImageView) findViewById(R.id.toolbar_image); toolbar = (Toolbar) findViewById(R.id.toolbar); tabLayout = (TabLayout) findViewById(R.id.tab_layout); viewPager = (ViewPager) findViewById(R.id.view_pager); entity = new SpotEntity( getResources(), R.drawable.tongxiaospot3, R.array.tongxiao_spot_name, 3, new int[]{R.drawable.tongxiaospot3_1, R.drawable.tongxiaospot3_2, R.drawable.tongxiaospot3_3}, R.array.tongxiao3_info, R.array.tongxiao_spot_address); titles = getResources().getStringArray(entity.getTabTitle()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_spot); init(); setToolbar(); setToolbarLayout(); setTabLayout(); setViewPager(); tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager)); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); } // 設定 CollapsingToolbarLayout private void setToolbarLayout() { imageView.setImageResource(entity.getToolbarImage()); toolbarLayout.setTitle(getResources().getStringArray(entity.getSpotName())[entity.getSpotNum()]); toolbarLayout.setCollapsedTitleTextColor(Color.WHITE); toolbarLayout.setExpandedTitleColor(Color.WHITE); } // 設定 Toolbar private void setToolbar() { setSupportActionBar(toolbar); } // 設定 TabLayout private void setTabLayout() { for (String title : titles) { tabLayout.addTab(tabLayout.newTab().setText(title)); } } // 設定 ViewPager private void setViewPager() { SpotPagerAdapter pagerAdapter = new SpotPagerAdapter(getSupportFragmentManager(), titles, entity.getFragmentList()); viewPager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(viewPager); } // 設定 FloatingActionButton public void mapGuide(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + getResources().getStringArray(entity.getAddress())[entity.getSpotNum()])); startActivity(intent); } }
cc5ea05c6142690af797e53a6cf93680b30f1b87
c6428967f87dec95b050ba2ab6309e4ac9a54b70
/hangugi77-tobytv7/src/main/java/com/daou/tobytv7/Practice.java
79e3fa24727bdd7989fa5a17f25772fbcf6e21b2
[]
no_license
mskwak/hangugi77
aefc3298a936c982af501d23d9fa685ab9aa6b57
6b7bac33b17f7003b410f0021b8522e751ea9298
refs/heads/master
2022-10-17T17:41:42.185808
2019-10-14T13:52:15
2019-10-14T13:52:15
135,868,642
0
0
null
2023-08-24T20:27:00
2018-06-03T02:55:34
Java
UTF-8
Java
false
false
180
java
package com.daou.tobytv7; import reactor.core.publisher.Flux; public class Practice { public static void main(String[] args) { Flux.just("test").subscribe(); } }
9af736c7f68f568a03ce4f791e8ea59c2436c8b7
472566e5ce6bde442b996054c23fe3b7bb209454
/src/main/java/com/fangminx/anno/AdminOnly.java
7666847d952f5eb3d9da9c8be9137af510f453ed
[]
no_license
fangminx/execution-demo
d7c303e081e31e39feb6eb500edfd831bf6eee1a
4a34b2de6b058c2a9ce00dc4d8239c382b6e5029
refs/heads/master
2021-05-16T12:06:14.287708
2017-09-28T16:31:35
2017-09-28T16:31:35
105,172,150
0
1
null
null
null
null
UTF-8
Java
false
false
286
java
package com.fangminx.anno; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AdminOnly { }
d79d41c9200bc9fc142391d9560949632a12d316
2f4e9d56b6c85c7de119818e6e09f01d488d26d0
/app/src/main/java/cn/dianedun/bean/WaterChartBean.java
c8aef587f074eadd56c4c5f748cd562a56c40e3a
[]
no_license
PengLius/dianedun
5044f42a2e368da0c8d9fad7a59d97c6da141c7b
c6ad63c9460cc8d02edbcddf8e64faf454159a66
refs/heads/master
2021-01-02T09:16:01.426964
2018-03-30T02:38:02
2018-03-30T02:38:02
99,173,413
0
2
null
2018-03-29T06:58:18
2017-08-03T00:40:00
Java
UTF-8
Java
false
false
3,332
java
package cn.dianedun.bean; import java.util.List; /** * Created by Administrator on 2017/10/21. */ public class WaterChartBean { /** * code : 0 * msg : 成功 * data : {"waterList":["0","0","0","0","0","0","1","1","0","0","0","0","1","1","0","0","0","0","1","1","1","1","0","0","0","0","0","0","1","1","0","0","1","1","0","0","0","0","1","1","0","0","1","1","0","0","0","0","1","1","1","1","0","1","1","1","0","0","1","1","0","0","0","0","0","0","0","0","0","0","0","0","1","1","0","0","0","1","0","0","0","0","1","1","0","0","0","0","0","0","0","0","0","0"],"xList":["2017-09-26 00:45","2017-09-26 00:48","2017-09-26 01:15","2017-09-26 01:18","2017-09-26 01:45","2017-09-26 01:48","2017-09-26 02:15","2017-09-26 02:18","2017-09-26 02:45","2017-09-26 02:48","2017-09-26 03:15","2017-09-26 03:18","2017-09-26 03:45","2017-09-26 03:48","2017-09-26 04:15","2017-09-26 04:18","2017-09-26 04:45","2017-09-26 04:48","2017-09-26 05:15","2017-09-26 05:18","2017-09-26 06:15","2017-09-26 06:18","2017-09-26 06:45","2017-09-26 06:48","2017-09-26 07:15","2017-09-26 07:18","2017-09-26 07:45","2017-09-26 07:48","2017-09-26 08:15","2017-09-26 08:18","2017-09-26 08:45","2017-09-26 08:48","2017-09-26 09:15","2017-09-26 09:18","2017-09-26 09:45","2017-09-26 09:48","2017-09-26 10:15","2017-09-26 10:18","2017-09-26 10:45","2017-09-26 10:48","2017-09-26 11:15","2017-09-26 11:18","2017-09-26 11:45","2017-09-26 11:48","2017-09-26 12:15","2017-09-26 12:18","2017-09-26 12:45","2017-09-26 12:48","2017-09-26 13:15","2017-09-26 13:18","2017-09-26 13:45","2017-09-26 13:48","2017-09-26 14:15","2017-09-26 14:18","2017-09-26 14:45","2017-09-26 14:48","2017-09-26 15:15","2017-09-26 15:18","2017-09-26 15:45","2017-09-26 15:48","2017-09-26 16:15","2017-09-26 16:18","2017-09-26 16:45","2017-09-26 16:48","2017-09-26 17:15","2017-09-26 17:18","2017-09-26 17:45","2017-09-26 17:48","2017-09-26 18:15","2017-09-26 18:18","2017-09-26 18:45","2017-09-26 18:48","2017-09-26 19:15","2017-09-26 19:18","2017-09-26 19:45","2017-09-26 19:48","2017-09-26 20:15","2017-09-26 20:18","2017-09-26 20:45","2017-09-26 20:48","2017-09-26 21:15","2017-09-26 21:18","2017-09-26 21:45","2017-09-26 21:48","2017-09-26 22:15","2017-09-26 22:18","2017-09-26 22:45","2017-09-26 22:48","2017-09-26 23:15","2017-09-26 23:18","2017-09-26 23:45","2017-09-26 23:48","2017-09-27 00:15","2017-09-27 00:18"]} */ private int code; private String msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { private List<String> waterList; private List<String> xList; public List<String> getWaterList() { return waterList; } public void setWaterList(List<String> waterList) { this.waterList = waterList; } public List<String> getXList() { return xList; } public void setXList(List<String> xList) { this.xList = xList; } } }
[ "20091016xe" ]
20091016xe
3cb2792c5dc41e8999171acc23a39ce40e5fb34f
1a966e82580d91707afd0d01aefe92b798f3a956
/Pro24.java
761da1e8546f83d47064179bbb81dcd7d41adf32
[]
no_license
SuvethaBala/suvehunter
69244167af9f10bb8125b4dfae1a0348b3afb6b7
da5f3af406882d7b63f5581885579bef1bb244f8
refs/heads/master
2020-05-03T05:05:17.147353
2019-06-14T16:40:55
2019-06-14T16:40:55
178,439,321
0
2
null
null
null
null
UTF-8
Java
false
false
2,048
java
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int ip = n; int a[]=new int[10000]; int c[]=new int[10000]; String b[]=new String[10000]; n=(int)Math.pow(2,ip); //System.out.println(n); for(int i=0;i<n;i++){ a[i]=i; //System.out.println(a[i]); int temp = i; int count =0; while(temp>0){ int j=temp%2; if(j==1){ count++; } temp=temp/2; } c[i]=count; b[i]=Integer.toBinaryString(a[i]); for(int l=0;b[i].length()<ip;l++){ b[i]="0"+b[i]; } //b[i]=String.format("%4s", b[i]); //b[i]=b[i].replace(" ","0"); //b[0]="0000"; //System.out.println("no = "+a[i]+" binary = "+b[i]+" ones = "+c[i]); //System.out.println("no = "+a[i]+" binary = "+b[i]); } for(int j=0;j<n;j++){ for(int i=0;i<n-j-1;i++){ if(c[i]==c[i+1]){ if(a[i]>a[i+1]){ int tempc = c[i]; int tempa = a[i]; String temps = b[i]; c[i]=c[i+1]; a[i] = a[i+1]; b[i] = b[i+1]; c[i+1]=tempc; a[i+1] = tempa; b[i+1] = temps; } } else if(c[i]>c[i+1]){ int tempc = c[i]; int tempa = a[i]; String temps = b[i]; c[i]=c[i+1]; a[i] = a[i+1]; b[i] = b[i+1]; c[i+1]=tempc; a[i+1] = tempa; b[i+1] = temps; } } } for(int i=0;i<n;i++) System.out.println(b[i]); } }
bbc889b374c2236416b26531abc2948171f67c83
b7581364a567f3720ae22d9bac4ad1e726b7ed44
/Stage4/bootgiftsec_springboot/service/src/test/java/com/epam/esm/common_service/TestConfig.java
a5584514f6f602225d30a04fae1f53784708e59e
[]
no_license
romanoidprg/MJC_School
bd9197be81fca7ccb0e8a9a42c84074ecf1cb6ae
a327f5b465bd5cfcc8fbf0cbfd4532d4175d8637
refs/heads/main
2023-06-26T00:02:44.501317
2021-08-01T17:04:50
2021-08-01T17:04:50
371,099,505
1
0
null
null
null
null
UTF-8
Java
false
false
4,999
java
package com.epam.esm.common_service; import com.epam.esm.common_service.impl.CertRepoService; import com.epam.esm.common_service.impl.OrderRepoService; import com.epam.esm.common_service.impl.TagRepoService; import com.epam.esm.common_service.impl.UserRepoService; import com.epam.esm.dao.CertRepo; import com.epam.esm.dao.CommonDao; import com.epam.esm.dao.CustomCertDao; import com.epam.esm.dao.CustomTagDao; import com.epam.esm.dao.OrderRepo; import com.epam.esm.dao.TagRepo; import com.epam.esm.dao.UserRepo; import com.epam.esm.model.CertCriteria; import com.epam.esm.model.GiftCertificate; import com.epam.esm.model.Order; import com.epam.esm.model.OrderCriteria; import com.epam.esm.model.Tag; import com.epam.esm.model.TagCriteria; import com.epam.esm.model.User; import com.epam.esm.model.UserCriteria; import org.aspectj.weaver.ast.Or; import org.hibernate.SessionFactory; import org.hibernate.internal.SessionFactoryImpl; import org.mockito.Mockito; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import javax.jws.soap.SOAPBinding; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import static org.mockito.ArgumentMatchers.*; @SpringBootConfiguration public class TestConfig { // @Bean // public SessionFactory sessionFactory() { // SessionFactory sf = Mockito.mock(SessionFactoryImpl.class); // return sf; // } @Bean public CommonService<GiftCertificate> certRepoService() { return new CertRepoService(); } @Bean public CustomCertService customCertRepoService() { return new CertRepoService(); } @Bean public CommonService<User> userRepoService() { return new UserRepoService(); } @Bean public CommonService<Order> orderRepoService() { return new OrderRepoService(); } @Bean public CommonService<Tag> tagRepoService() { return new TagRepoService(); } @Bean public CustomTagService customTagRepoService() { return new TagRepoService(); } @Bean public CertRepo certRepo() { GiftCertificate cert = new GiftCertificate(); GiftCertificate cert1 = new GiftCertificate(); cert.setId(1L); cert1.setId(1L); CertRepo mockCertRepo = Mockito.mock(CertRepo.class); Mockito.when(mockCertRepo.save(any())).thenReturn(cert); Mockito.when(mockCertRepo.exists(any())).thenReturn(false); Mockito.when(mockCertRepo.findById(anyLong())).thenReturn(Optional.of(cert)); Mockito.when(mockCertRepo.findByNameContainingAndDescriptionContainingAndTagsNameContaining(any(), any(), any(), any())) .thenReturn(new PageImpl<>(Arrays.asList(cert, cert1))); return mockCertRepo; } @Bean public TagRepo tagRepo() { Tag tag = new Tag(); tag.setId(1L); Tag tag1 = new Tag(); tag1.setId(1L); TagRepo mockTagRepo = Mockito.mock(TagRepo.class); Mockito.when(mockTagRepo.save(any())).thenReturn(tag); Mockito.when(mockTagRepo.exists(any())).thenReturn(false); Mockito.when(mockTagRepo.findById(anyLong())).thenReturn(Optional.of(new Tag())); Mockito.when(mockTagRepo.findAll(any(),any(Pageable.class))) .thenReturn(new PageImpl<>(Arrays.asList(tag,tag1))); Mockito.when(mockTagRepo.getIdOfMostUsefullTagByUserId(anyLong())).thenReturn(Arrays.asList(1L,2L)); return mockTagRepo; } @Bean public OrderRepo orderRepo() { Order order = new Order(); Order order1 = new Order(); order.setId(1L); order1.setId(1L); OrderRepo mockOrderRepo = Mockito.mock(OrderRepo.class); Mockito.when(mockOrderRepo.save(any())).thenReturn(order); Mockito.when(mockOrderRepo.exists(any())).thenReturn(false); Mockito.when(mockOrderRepo.findById(anyLong())).thenReturn(Optional.of(new Order())); Mockito.when(mockOrderRepo.findAll(any(),any(Pageable.class))) .thenReturn(new PageImpl<>(Arrays.asList(order,order1))); return mockOrderRepo; } @Bean public UserRepo userRepo () { User user = new User(); User user1 = new User(); user.setId(1L); user1.setId(1L); UserRepo mockUserRepo = Mockito.mock(UserRepo.class); Mockito.when(mockUserRepo.save(any())).thenReturn(user); Mockito.when(mockUserRepo.exists(any())).thenReturn(false); Mockito.when(mockUserRepo.findById(anyLong())).thenReturn(Optional.of(new User())); Mockito.when(mockUserRepo.findAll(any(),any(Pageable.class))) .thenReturn(new PageImpl<>(Arrays.asList(user,user1))); return mockUserRepo; } }
c9cb3ff2e1d76088c119d93367471a50ca1278c4
8583886aef23ff8b2b611a6c6bd70e691b845ad0
/RabbitRssReader/src/com/jackey/android/rss/model/RssSite.java
6c730cb8066f2da15634259292cf80d94e5fb05e
[]
no_license
hejackey/heproject
9f596c7e5f4d57d4f7aa1661a3314a313c965fd3
3efad5550a9d7500b808d0d8cc7d384267ef2785
refs/heads/master
2016-09-05T09:16:55.396484
2012-09-06T16:13:45
2012-09-06T16:13:45
41,244,232
0
0
null
null
null
null
UTF-8
Java
false
false
343
java
package com.jackey.android.rss.model; public class RssSite { private String title; private String url; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
2ef952a975d612abeedc538af3cd1a65e8a905b4
f4e7f6b83f1754e3570e5846d6f6786c5090e9c7
/src/model/common/Address.java
241257e00ea05e4bc015481abea6556ab4d63e71
[]
no_license
MYunFeiYang/Network_recuiting_system
f80e426ce4139bdc2cece65e4c13bbc15eb4b935
d529965b415c95cc680d226741a0687be8e5c9c5
refs/heads/master
2023-01-07T00:46:22.804127
2019-06-10T14:06:59
2019-06-10T14:06:59
108,945,526
1
0
null
2023-01-03T21:01:06
2017-10-31T04:31:36
JavaScript
UTF-8
Java
false
false
359
java
package model.common; public class Address { private String href; private String text; public String getHref() { return href; } public void setHref(String href) { this.href = href; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
239172c388e1524ac9b177a874dcc6ecf1886052
ef6e6c17f857d04c5f92c7795b699379fa9897c4
/Javahe HTTP Web Server Asynchr -1.0.0/src/Server.java
75748d115f95bc6e405f746b4107bef3e36228a1
[]
no_license
yvelikov/Java-Web-Fundamentals
d405b859280ce8f8daa616e98bee66fd3e89f0b8
fcff8e2580e0d94f2a1ee6b294c48130b6b0f82a
refs/heads/master
2021-05-10T11:17:37.564641
2018-02-22T06:05:38
2018-02-22T06:05:38
118,407,874
0
0
null
null
null
null
UTF-8
Java
false
false
1,121
java
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.concurrent.FutureTask; public class Server { private int port; private int timeouts; private ServerSocket server; public Server(int port) { this.port = port; this.timeouts = 0; } public void run() throws IOException { this.server = new ServerSocket(this.port); this.server.setSoTimeout(5000); System.out.println("Listening on port: " + this.port); while(true) { try(Socket clientSocket = this.server.accept()) { clientSocket.setSoTimeout(5000); System.out.println("Client connected: " + clientSocket.getPort()); RequestHandler requestHandler = new RequestHandler(clientSocket); FutureTask<?> task = new FutureTask<>(requestHandler, null); task.run(); } catch(SocketTimeoutException e) { System.out.println("Timeout detected!"); this.timeouts++; } } } }
[ "Powerslave#88" ]
Powerslave#88
8df8497d9c28605a35ed0ff29e6f97d3a356bb1f
c374fd6fa69c7dc002f67ba957525469d7c471a8
/SQLite/obj/Debug/android/sqlite/sqlite/R.java
5d557e1d2fd68cc59441edb4e81413f32c1e7923
[]
no_license
rahul51193/SQLite
83fdf4fe2855eaa3036ba2c01890e783cd7ce985
061dc629c514a379ab538a03eb46a4452260f07f
refs/heads/master
2021-08-22T05:55:05.415925
2017-11-29T12:12:46
2017-11-29T12:12:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,500
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package sqlite.sqlite; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; public static final int rescyou=0x7f020001; public static final int rescyoularge=0x7f020002; } public static final class id { public static final int btn_reg_create=0x7f060008; public static final int btnlogin=0x7f060004; public static final int btnregister=0x7f060005; public static final int textView1=0x7f060001; public static final int txt_reg_password=0x7f060007; public static final int txt_reg_username=0x7f060006; public static final int txtpwd=0x7f060003; public static final int txtusername=0x7f060002; public static final int welcomeMesssage=0x7f060000; } public static final class integer { public static final int google_play_services_version=0x7f040000; } public static final class layout { public static final int home=0x7f030000; public static final int main=0x7f030001; public static final int newuser=0x7f030002; } public static final class string { public static final int ApplicationName=0x7f050001; public static final int Hello=0x7f050000; } }
0f0f96f4c0c1895031bde0634e90af16f9a9ef33
06dc0fe82ce8a45ebc079c0fd6c205cd4751b6a0
/EnverHW/src/JavaHomework/StaticVariable.java
f8e472f459d5fc97518fa2ab05d94dfaf7a46821
[]
no_license
ANWAIERJUMAI/WeekenedHW
c11bd9fd4407755e8dc91bb116e2f07d33d8fa9c
4d67a060bef763b126c1f5228ee875492aab3446
refs/heads/master
2020-03-27T19:35:09.651533
2018-09-01T13:09:44
2018-09-01T13:09:44
146,998,889
0
0
null
null
null
null
UTF-8
Java
false
false
297
java
package JavaHomework; public class StaticVariable { //static variable static String name="Enver"; static int age=26; public static void main(String[] args) { System.out.println("my name is:" + name); System.out.println("my age is:" + age); } }
[ "enlem@DESKTOP-KFSKP86" ]
enlem@DESKTOP-KFSKP86
fed419f9a32ca16cee08f2ea5467152a6bbb6051
e03e04b0329a252dc5a1bb65efb271b4251deca1
/src/test/java/io/github/incplusplus/peerprocessing/server/QueryProcessingReassignmentIT.java
5ac8b54d1215866e26ea8f7646af30d6bcbafa69
[ "MIT" ]
permissive
IncPlusPlus/NetProgFinalProject
6b380b6b5c0df8af340c4ca83f5b685c97bf395e
e39d651fca9c8bf905aaac49274933719e53904d
refs/heads/master
2020-08-28T06:46:19.633219
2019-12-13T05:04:50
2019-12-13T05:04:50
217,625,419
0
0
MIT
2020-08-19T06:47:27
2019-10-25T22:50:33
Java
UTF-8
Java
false
false
5,507
java
package io.github.incplusplus.peerprocessing.server; import static io.github.incplusplus.peerprocessing.NormalIT.VERBOSE_TEST_OUTPUT; import static io.github.incplusplus.peerprocessing.common.MiscUtils.randInt; import io.github.incplusplus.peerprocessing.client.Client; import io.github.incplusplus.peerprocessing.linear.BigDecimalMatrix; import io.github.incplusplus.peerprocessing.slave.Slave; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.*; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @Timeout(value = 5, unit = TimeUnit.MINUTES) class QueryProcessingReassignmentIT { private static int serverPort; private static final Server server = new Server(); @BeforeAll static void setUp() throws IOException { serverPort = server.start(9999, VERBOSE_TEST_OUTPUT); //noinspection StatementWithEmptyBody while (!server.started()) {} } @AfterAll static void tearDown() throws IOException { server.stop(); } @ParameterizedTest @MethodSource("io.github.incplusplus.peerprocessing.NormalIT#provideMatrices") void whenSlaveDisconnects_IfSlaveHeldJobs_ThenJobsGetReassigned( BigDecimalMatrix matrix1, BigDecimalMatrix matrix2) throws IOException, ExecutionException, InterruptedException { FutureTask<BigDecimalMatrix> task; try (Client myClient = new Client("localhost", serverPort)) { ExecutorService executor = Executors.newSingleThreadExecutor(); SlaveFuzzer slaveFuzzer = new SlaveFuzzer("localhost", serverPort, 10); myClient.setVerbose(VERBOSE_TEST_OUTPUT); myClient.begin(); slaveFuzzer.begin(); task = myClient.multiply(matrix1, matrix2); //noinspection StatementWithEmptyBody while (!myClient.isPolite()) {} executor.submit(task); task.get(); executor.shutdown(); slaveFuzzer.stop(); } } private class SlaveFuzzer { private final String hostname; private final int portNum; final List<Slave> slaveList = Collections.synchronizedList(new ArrayList<>()); Thread randomSlaveSlayer; Thread randomSlaveCreator; SlaveFuzzer(String hostname, int portNum, int initNumSlaves) { this.hostname = hostname; this.portNum = portNum; for (int i = 0; i < initNumSlaves; i++) { slaveList.add(new Slave(hostname, portNum)); } randomSlaveSlayer = new Thread( () -> { while (true) { // If we've obviously overhunted, wait a while longer if (slaveList.size() < initNumSlaves / 2) { try { Thread.sleep(1000); } catch (InterruptedException ignored) { break; // we could get interrupted here. It's fine } } int index = randInt(1, slaveList.size()); Slave sacrificialLamb = slaveList.get(index); // if the slave to kill hasn't introduced itself yet // go looking somewhere else if (!sacrificialLamb.isPolite()) continue; try { synchronized (slaveList) { slaveList.remove(sacrificialLamb); sacrificialLamb.close(); } // Don't be constantly killing slaves or nothing will ever get done Thread.sleep(500); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ignored) { break; // we expect to be interrupted. Don't panic } } }); randomSlaveSlayer.setDaemon(true); randomSlaveSlayer.setName("Random slave slayer"); randomSlaveCreator = new Thread( () -> { while (true) { Slave newSlave = new Slave(this.hostname, this.portNum); slaveList.add(newSlave); try { newSlave.begin(); // don't expand the list infinitely Thread.sleep(500); } catch (IOException e) { System.out.println( "Encountered an error in SlaveFuzzer. " + "This could be expected behavior. " + "Message below:"); System.out.println(e.toString()); } catch (InterruptedException ignored) { break; // we expect to be interrupted. Don't panic } } }); randomSlaveCreator.setDaemon(true); randomSlaveCreator.setName("Random slave creator"); } void begin() throws IOException { for (Slave i : slaveList) { i.begin(); } randomSlaveCreator.start(); randomSlaveSlayer.start(); } void stop() throws IOException { randomSlaveCreator.interrupt(); randomSlaveSlayer.interrupt(); synchronized (slaveList) { for (Slave i : slaveList) { i.close(); } } } } }
0e7654ed6de3df539c30d68c5f229b62ecaa687e
55f8d4e2e65d60728f70f7e3f7245bda12120efa
/inclass/Week07/Loop03.java
d922103bfbe5ca6bfef87af4cc1a63337eac46ee
[]
no_license
mysstone/UCCSJava2017
c3984f746114f571a63d62ff7c0d8a2994af9f4a
4fec7bea543829940c046f02ebc28ba8fbbc6063
refs/heads/master
2021-06-27T09:01:00.995987
2020-09-24T07:09:48
2020-09-24T07:09:48
140,106,245
0
1
null
null
null
null
UTF-8
Java
false
false
1,270
java
public class Loop03 { public static void main (String[] args) { String[] nameArray = {"James", "Jack", "Jeff", "Jason", "Jane"}; for (int i = 0 ; i < nameArray.length ; i ++ ) { //nameArray[i]; // "Jason".equals(nameArray[i]) if ( nameArray[i].equals("Jason") ) { System.out.println("Jason's index is " + (i + 1) ); break; } else { ; } } int i = 0; while ( ! nameArray[i].equals("Jason")) { i ++; } System.out.println("Jason's index is " + (i+1)); // ! reverses boolean statements. thus, when the answer is true, // when i == Jason, then the code returns false, and the loop is stopped. i = -1; do { i++; } while (nameArray[i].equals("Jason")) ; System.out.println("Jason's index is " + (i + 1)); // i's value then will be the same one when the loop ended. // the do while loop will skip 0 if i starts at 0. // do-while loop executes at least once. it differs from while loop because it has a semicolon at the end. // while loop is an entry loop. If returns false, then it stops, and the loop is exited // a do-while loop first iterates, then looks for true and false statements. } }
6ebcaa3356ebc0b28c389cc39ece56ece694bbdc
b68f17b8b89eb844dfd6c9e61ca9d839a894a0e3
/Edu_system_v1.1/src/cn/nuist_bjxy/zhangzheng/bean/MysqlUser.java
fbdf5c5878bb228c0c2f455fcd67d471ce1cb92c
[]
no_license
user-zz/EduAS
75111f85966a214aa0adebbf4945ce3c5ae759ee
bf7af425187bd41640fb1bc568fa24506b3f8cc7
refs/heads/master
2020-05-20T03:01:25.071859
2019-05-20T02:02:47
2019-05-20T02:02:47
185,345,210
1
0
null
null
null
null
UTF-8
Java
false
false
678
java
package cn.nuist_bjxy.zhangzheng.bean; public class MysqlUser { private String uri="jdbc:mysql://localhost/eduas_db?serverTimezone=UTC&characterEncoding=UTF-8"; //数据库地址 private String username="root"; //数据库用户名 private String password="123456"; //数据库密码 public MysqlUser() { } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
36cd09b06f0cd7ba896681db258ee3fc49696f22
16336a110efa22b60dfb5972f9c217d7d68c1873
/src/main/java/com/demo/controller/EmployeeController.java
e967ce37d7921cc241819a52bef651e38ddc32e4
[]
no_license
1583229961/SpringMvc
fde6c62a98a1f384339a68865d2f233b8cf43368
60264a106b3468f6a1023fb17cd0695c1cd8be76
refs/heads/master
2022-12-21T12:37:38.118834
2019-12-13T07:30:07
2019-12-13T07:30:07
224,399,486
0
0
null
2022-12-16T04:24:16
2019-11-27T09:58:53
Java
UTF-8
Java
false
false
1,278
java
package com.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.demo.Model.Employee; import com.demo.Service.EmployeeService; import com.demo.Service.imp.EmployeeLogin; import ch.qos.logback.core.status.Status; @Controller public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping(value = "/hello.do") public String hello(){ System.out.println("接收到请求 ,Hello"); return "hi"; } @RequestMapping(value = "/login.do",method = RequestMethod.GET) public String login(){ return "Login"; } @ResponseBody @RequestMapping(value = "/login.do",method = RequestMethod.POST) public Employee login(@RequestBody Employee employee) { Employee employee1=employeeService.Login(employee.getId(),employee.getPassword()); System.out.println(employee1.getPassword()); return employee1; } }
9aab7dd4c434078dd81aa32881035f8e6fa5edd8
44aa08f6174cb485f42855d277122957cec2a595
/storage/src/test/java/com/sunland/rocketmq/AppendAndGetRocksdbTest.java
d5c43df66437e8eb8c78304fa1698e5df446e696
[ "Apache-2.0" ]
permissive
breezecoolyang/DLedger_rocksdb
17b71c0a190b8727b6d82592d8d9c883efef8f3f
78a404e30d95d0e9778d38f2edd4feb8081be83b
refs/heads/master
2020-05-14T12:52:04.818390
2019-05-10T08:27:16
2019-05-10T08:27:16
181,800,766
0
0
null
null
null
null
UTF-8
Java
false
false
7,335
java
package com.sunland.rocketmq; import com.sunland.rocketmq.entry.DLedgerEntry; import com.sunland.rocketmq.client.DLedgerClient; import com.sunland.rocketmq.protocol.AppendEntryResponse; import com.sunland.rocketmq.protocol.DLedgerResponseCode; import com.sunland.rocketmq.protocol.GetEntriesResponse; import com.sunland.rocketmq.protocol.GetListEntriesResponse; import com.sunland.rocketmq.protocol.AppendEntryRequest; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class AppendAndGetRocksdbTest extends ServerTestHarness{ @Test public void testSingleServerInRocksdb() throws Exception { String group = UUID.randomUUID().toString(); String selfId = "n0"; String peers = "n0-localhost:10005"; launchServer(group, peers, selfId, selfId, DLedgerConfig.ROCKSDB); DLedgerClient dLedgerClient = launchClient(group, peers); for (long i = 0; i < 10; i++) { AppendEntryResponse appendEntryResponse = dLedgerClient.append(1536811267, ("HelloSingleServerInRocksdb" + i).getBytes()); Assert.assertEquals(i, appendEntryResponse.getIndex()); } GetListEntriesResponse getEntriesResponse = dLedgerClient.getByTime(1536811267); Assert.assertEquals(10, getEntriesResponse.getEntries().size()); for (long i = 0; i < 10; i++) { Assert.assertEquals(i, getEntriesResponse.getEntries().get((int)i).getIndex()); Assert.assertArrayEquals(("HelloSingleServerInRocksdb" + i).getBytes(), getEntriesResponse.getEntries().get((int)i).getBody()); } } @Test public void testSingleServerInRocksdbGet() throws Exception { String group = UUID.randomUUID().toString(); String selfId = "n0"; String peers = String.format("n0-localhost:%d", nextPort()); launchServer(group, peers, selfId, selfId, DLedgerConfig.ROCKSDB); DLedgerClient dLedgerClient = launchClient(group, peers); for (long i = 0; i < 10; i++) { AppendEntryResponse appendEntryResponse = dLedgerClient.append(1536811267, ("HelloSingleServerInRocksdbGet" + i).getBytes()); Assert.assertEquals(i, appendEntryResponse.getIndex()); } for (long i = 0; i < 10; i++) { GetEntriesResponse getEntriesResponse = dLedgerClient.get(i); Assert.assertEquals(1, getEntriesResponse.getEntries().size()); Assert.assertEquals(i, getEntriesResponse.getEntries().get(0).getIndex()); Assert.assertArrayEquals(("HelloSingleServerInRocksdbGet" + i).getBytes(), getEntriesResponse.getEntries().get(0).getBody()); } } @Test public void testThreeServerInRocksdb() throws Exception { String group = UUID.randomUUID().toString(); String peers = "n0-localhost:10006;n1-localhost:10007;n2-localhost:10008"; DLedgerServer dLedgerServer0 = launchServer(group, peers, "n0", "n1", DLedgerConfig.ROCKSDB); DLedgerServer dLedgerServer1 = launchServer(group, peers, "n1", "n1", DLedgerConfig.ROCKSDB); DLedgerServer dLedgerServer2 = launchServer(group, peers, "n2", "n1", DLedgerConfig.ROCKSDB); DLedgerClient dLedgerClient = launchClient(group, peers); long timestamp = System.currentTimeMillis()/1000; for (int i = 0; i < 10; i++) { AppendEntryResponse appendEntryResponse = dLedgerClient.append(timestamp, ("HelloSingleServerInRocksdb" + i).getBytes()); Assert.assertEquals(appendEntryResponse.getCode(), DLedgerResponseCode.SUCCESS.getCode()); Assert.assertEquals(i, appendEntryResponse.getIndex()); } Thread.sleep(100); Assert.assertEquals(9, dLedgerServer0.getdLedgerStore().getLedgerEndIndex()); Assert.assertEquals(9, dLedgerServer1.getdLedgerStore().getLedgerEndIndex()); Assert.assertEquals(9, dLedgerServer2.getdLedgerStore().getLedgerEndIndex()); GetListEntriesResponse getEntriesResponse = dLedgerClient.getByTime(timestamp); Assert.assertEquals(10, getEntriesResponse.getEntries().size()); for (int i = 0; i < 10; i++) { Assert.assertEquals(i, getEntriesResponse.getEntries().get(i).getIndex()); Assert.assertArrayEquals(("HelloSingleServerInRocksdb" + i).getBytes(), getEntriesResponse.getEntries().get(i).getBody()); } } @Test public void testThreeServerInRocksdbWithAsyncRequests() throws Exception { String group = UUID.randomUUID().toString(); String peers = String.format("n0-localhost:%d;n1-localhost:%d;n2-localhost:%d", nextPort(), nextPort(), nextPort()); DLedgerServer dLedgerServer0 = launchServer(group, peers, "n0", "n1", DLedgerConfig.ROCKSDB); DLedgerServer dLedgerServer1 = launchServer(group, peers, "n1", "n1", DLedgerConfig.ROCKSDB); DLedgerServer dLedgerServer2 = launchServer(group, peers, "n2", "n1", DLedgerConfig.ROCKSDB); List<CompletableFuture<AppendEntryResponse>> futures = new ArrayList<>(); long timestamp = System.currentTimeMillis()/1000; for (int i = 0; i < 10; i++) { AppendEntryRequest request = new AppendEntryRequest(); request.setGroup(group); request.setRemoteId(dLedgerServer1.getMemberState().getSelfId()); request.setTimestamp(timestamp); request.setBody(("testThreeServerInRocksdbWithAsyncRequests" + i).getBytes()); futures.add(dLedgerServer1.handleAppend(request)); } Thread.sleep(500); Assert.assertEquals(9, dLedgerServer0.getdLedgerStore().getLedgerEndIndex()); Assert.assertEquals(9, dLedgerServer1.getdLedgerStore().getLedgerEndIndex()); Assert.assertEquals(9, dLedgerServer2.getdLedgerStore().getLedgerEndIndex()); DLedgerClient dLedgerClient = launchClient(group, peers); for (int i = 0; i < futures.size(); i++) { CompletableFuture<AppendEntryResponse> future = futures.get(i); Assert.assertTrue(future.isDone()); Assert.assertEquals(i, future.get().getIndex()); Assert.assertEquals(DLedgerResponseCode.SUCCESS.getCode(), future.get().getCode()); GetEntriesResponse getEntriesResponse = dLedgerClient.get(i); DLedgerEntry entry = getEntriesResponse.getEntries().get(0); Assert.assertEquals(1, getEntriesResponse.getEntries().size()); Assert.assertEquals(i, getEntriesResponse.getEntries().get(0).getIndex()); Assert.assertArrayEquals(("testThreeServerInRocksdbWithAsyncRequests" + i).getBytes(), entry.getBody()); } GetListEntriesResponse getEntriesResponse = dLedgerClient.getByTime(timestamp); Assert.assertEquals(10, getEntriesResponse.getEntries().size()); for (int i = 0; i < 10; i++) { Assert.assertEquals(i, getEntriesResponse.getEntries().get(i).getIndex()); Assert.assertArrayEquals(("testThreeServerInRocksdbWithAsyncRequests" + i).getBytes(), getEntriesResponse.getEntries().get(i).getBody()); } } }
4aabc31f3979005fa8c3bd9e34280b78da778078
c8c262e04f601cdfceaeee82f29701f3d9dbc720
/src/designpattern/combined/djview/BeatModelInterface.java
6168bb37e255409e7b63f362cc4d0b2b58ae611b
[]
no_license
ShashiUpadhyay/DesignPatterns
8db090d3ac9847abe5cf86bb649da57a1204ddeb
78bb84d23b9ae733da7359db2173ba9f9fe8f536
refs/heads/master
2021-01-12T06:44:31.208324
2016-12-27T05:54:01
2016-12-27T05:54:01
77,429,663
0
0
null
null
null
null
UTF-8
Java
false
false
346
java
package designpattern.combined.djview; public interface BeatModelInterface { void initialize(); void on(); void off(); void setBPM(int bpm); int getBPM(); void registerObserver(BeatObserver o); void removeObserver(BeatObserver o); void registerObserver(BPMObserver o); void removeObserver(BPMObserver o); }
a6617dc209a6b686821f4b1a99732b2e5732d2f7
93731a2f39afe1e2316fe98d137de4a8f6fdbc26
/Taller2ReverseEng/src/generated/Alt.java
beb6882a6de30c7ddc6fee4b77796dbdbb876637
[]
no_license
gzapataz/EclipseWS
21c12e9dd102daf7fcc59dc54b0c26edd7654283
3cb1c7ce7ff4792fd2d08fdcf649bb178e767b52
refs/heads/master
2021-01-21T16:14:50.204232
2016-09-20T14:38:44
2016-09-20T14:38:44
68,662,109
0
0
null
2016-09-20T14:38:44
2016-09-20T01:37:58
null
UTF-8
Java
false
false
1,768
java
// // Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.8-b130911.1802 // Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen. // Generado el: 2016.09.18 a las 11:10:44 AM COT // package generated; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para anonymous complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{}parent"> * &lt;attribute name="mandatory" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "alt") public class Alt extends Parent { @XmlAttribute(name = "mandatory") protected Boolean mandatory; /** * Obtiene el valor de la propiedad mandatory. * * @return * possible object is * {@link Boolean } * */ public Boolean isMandatory() { return mandatory; } /** * Define el valor de la propiedad mandatory. * * @param value * allowed object is * {@link Boolean } * */ public void setMandatory(Boolean value) { this.mandatory = value; } }
4774e546e7d24b944732ddb31eb8d00a710545c2
a6501f5f367664a54b9b98c4458d98c1d909ab44
/test.java
919d8d2270c788564cc17cf561b8291eb126e111
[]
no_license
mwsfr/test1
f8a37f30c1c4df9a4ab32a31a6702778078b0b48
c8d67ba86f363975caacc0aab9e7e20929dffc69
refs/heads/master
2021-09-09T15:59:50.294566
2018-03-17T16:35:34
2018-03-17T16:35:34
125,648,832
0
0
null
null
null
null
UTF-8
Java
false
false
2,253
java
import java.io.Console; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class test { public static void main(String[] args) throws IOException { SpaceShip falcon = new SpaceShip(); falcon.setName("Falcon"); SpaceShip falconEnemy = new SpaceShip(); falconEnemy.setName("Enemy"); SpaceShipRoom room1 = new SpaceShipRoom(); SpaceShipRoom room2 = new SpaceShipRoom(); SpaceShipRoom room3 = new SpaceShipRoom(); SpaceShipRoom room4 = new SpaceShipRoom(); SpaceShipRoom eRoom1 = new SpaceShipRoom(); SpaceShipRoom eRoom2 = new SpaceShipRoom(); SpaceShipRoom eRoom3 = new SpaceShipRoom(); SpaceShipRoom eRoom4 = new SpaceShipRoom(); OxygemSystem oxigemSystem = new OxygemSystem(falcon); LaserSystems laserSystem = new LaserSystems(falcon); MissileSystem missileSystem = new MissileSystem(falcon); ForceFieldSystem forceFieldSystem = new ForceFieldSystem(falcon); OxygemSystem eOxigemSystem = new OxygemSystem(falconEnemy); LaserSystems eLaserSystem = new LaserSystems(falconEnemy); MissileSystem eMissileSystem = new MissileSystem(falconEnemy); ForceFieldSystem eForceFieldSystem = new ForceFieldSystem(falconEnemy); room1.setSystem(oxigemSystem); room2.setSystem(laserSystem); room3.setSystem(missileSystem); room4.setSystem(forceFieldSystem); falcon.roomList.add(room1); falcon.roomList.add(room2); falcon.roomList.add(room3); falcon.roomList.add(room4); eRoom1.setSystem(eOxigemSystem); eRoom2.setSystem(eLaserSystem); eRoom3.setSystem(eMissileSystem); eRoom4.setSystem(eForceFieldSystem); falconEnemy.roomList.add(eRoom1); falconEnemy.roomList.add(eRoom2); falconEnemy.roomList.add(eRoom3); falconEnemy.roomList.add(eRoom4); falcon.setEnemy(falconEnemy); for (SpaceShipRoom r : falconEnemy.getRoomList()) { r.getSystem().startSystem(); } int turn=0; while(turn<10){ turn++; falcon.nextTurn(); falconEnemy.nextTurn(); System.out.println("Turn: "+turn); falcon.showOverallStatus(); falconEnemy.showOverallStatus(); falcon.showOptions(); } falcon.getScanner().close(); falconEnemy.getScanner().close(); } }
219a0d5eda396ca90d80dbb6bd56db760c0559b8
ee558e092d301acb7c56c9a7f91a31dacdd1d063
/editorcore/src/test/java/com/zarbosoft/merman/editorcore/display/MockFreeDisplayNode.java
8413063d4520a2fe1b3811d5b8a9bf0ada0a3de7
[ "BSD-2-Clause" ]
permissive
psh-baxter/alligatoroid
b17c5e3c91f63f1cab8a7543b6661c77a1b1a733
d777ee3a33a56897a1961719fdc97b07c869bf9b
refs/heads/master
2023-07-13T09:45:44.591547
2021-09-01T10:54:31
2021-09-01T10:54:31
402,027,039
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package com.zarbosoft.merman.editorcore.display; public abstract class MockFreeDisplayNode extends MockeryDisplayNode { public double transverse; @Override public double transverse() { return transverse; } }
[ "" ]
af1dfa54ed0e13a5ede653ce07ab0bc20dd52519
99fdff0158ad26dd3f0e2d5eda56ee5d76bb3beb
/mark/src/main/java/com/replay/limty/model/common/OrderInfo.java
43e58085c2fd2e5edf7f936edaf1fbebac2c562d
[]
no_license
tome34/Pay
e15abef62bfa50d73d6d540bc634615851f5f74e
f515101fcececfcfe8eacd8756f65c682181d701
refs/heads/master
2021-01-21T20:54:20.910300
2017-05-24T12:32:39
2017-05-24T12:32:39
92,289,081
0
0
null
null
null
null
UTF-8
Java
false
false
1,351
java
package com.replay.limty.model.common; /** * Created by Administrator on 2017/4/17 0017. */ public class OrderInfo { /** * 商品名 */ private String body; /** * 订单号 */ private String orderNumber; /** * 订单金额 */ private String money; /** * 支付类型 */ private String payType; /** * 自定义参数 */ private String attach; public static OrderInfo instance; private OrderInfo() { } public static OrderInfo getInstance(){ if(instance == null){ instance = new OrderInfo(); } return instance; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } @Override public String toString() { return "OrderInfo{" + "body='" + body + '\'' + ", orderNumber='" + orderNumber + '\'' + ", money='" + money + '\'' + '}'; } }
8e11d34abab13ca4cb47a751358bbdaec87fd12c
48cf60a24eb76a141620cde3870c056419ea8d92
/mplayer2/app/src/main/java/vip/jokor/im/model/stores_bean/MMGroup.java
b271cbb2c90e195cf1b756e7bf593301c7cff330
[]
no_license
culturer/jokor_android
6322e9e4d7a723852b5214568a140905491d39be
b24bc0a6cfeeebc368bac5778dfd7d34344ea8ad
refs/heads/master
2020-12-20T18:02:16.823472
2020-02-05T18:46:06
2020-02-05T18:46:06
236,161,750
0
0
null
null
null
null
UTF-8
Java
false
false
2,596
java
package vip.jokor.im.model.stores_bean; public class MMGroup { //群聊 /** * id : 3 * UserId : 29 * Icon : img_29groupIcon1552616428051 * Name : 测试群! * Count : 1 * MaxCount : 100 * Msg : 测试介绍 * CId : 6668436802967175170 * IsVIP : false * VIPStart : 0 * VIPEnd : 0 * IsHome : false * HomeUrl : * IsShop : false * ShopId : 0 * IsChange : false */ private long id; private long UserId; private String Icon; private String Name; private int Count; private int MaxCount; private String Msg; private long CId; private boolean IsVIP; private long VIPStart; private long VIPEnd; private boolean IsHome; private String HomeUrl; private boolean IsShop; private long ShopId; private boolean IsChange; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getUserId() { return UserId; } public void setUserId(long UserId) { this.UserId = UserId; } public String getIcon() { return Icon; } public void setIcon(String Icon) { this.Icon = Icon; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public int getCount() { return Count; } public void setCount(int Count) { this.Count = Count; } public int getMaxCount() { return MaxCount; } public void setMaxCount(int MaxCount) { this.MaxCount = MaxCount; } public String getMsg() { return Msg; } public void setMsg(String Msg) { this.Msg = Msg; } public long getCId() { return CId; } public void setCId(long CId) { this.CId = CId; } public boolean isIsVIP() { return IsVIP; } public void setIsVIP(boolean IsVIP) { this.IsVIP = IsVIP; } public long getVIPStart() { return VIPStart; } public void setVIPStart(long VIPStart) { this.VIPStart = VIPStart; } public long getVIPEnd() { return VIPEnd; } public void setVIPEnd(long VIPEnd) { this.VIPEnd = VIPEnd; } public boolean isIsHome() { return IsHome; } public void setIsHome(boolean IsHome) { this.IsHome = IsHome; } public String getHomeUrl() { return HomeUrl; } public void setHomeUrl(String HomeUrl) { this.HomeUrl = HomeUrl; } public boolean isIsShop() { return IsShop; } public void setIsShop(boolean IsShop) { this.IsShop = IsShop; } public long getShopId() { return ShopId; } public void setShopId(long ShopId) { this.ShopId = ShopId; } public boolean isIsChange() { return IsChange; } public void setIsChange(boolean IsChange) { this.IsChange = IsChange; } }
87d1dd44b0fe782c2ebc148d15f298c5df162090
95252e1c24e019b0658a46159d2374cc042640a1
/ARCC/2015_11_19_EngineeringPrinciples/java/src/com/rwb/restaurant/BananaItem.java
66f3e82462fed4161568b150c1d15600e4410c41
[]
no_license
donaldsawyer/Demos
4d89a5cf605b2ab2f05fc56f78ff1452567b7e20
cd897b5dd7b393076a3fdd6c9950bbeccd72b6e1
refs/heads/master
2021-06-21T17:59:10.278854
2021-06-16T14:51:21
2021-06-16T14:51:21
46,322,661
0
3
null
null
null
null
UTF-8
Java
false
false
256
java
package com.rwb.restaurant; import com.rwb.strategies.ExemptTaxMenuItem; /** * Created by Donald on 11/19/2015. */ public class BananaItem extends ExemptTaxMenuItem { public BananaItem() { name = "Banana"; price = 0.50; } }
0bd4f2dd8fe59b8cacdffde5aed926b5e97cafe1
aed778974ac3d88e634b98db318326d5bd8d96c9
/client/src/main/java/class139.java
042178fb9bb20b234b542a9b442184fb8da69cea
[]
no_license
kyleescobar/avernic
89bfe47cceb1286a64cb57bde31a17a39b8b8987
f8306ae0b45d681ab4082c35ddc152d41142b032
refs/heads/master
2023-07-14T04:32:50.785244
2021-09-03T06:18:42
2021-09-03T06:18:42
400,934,182
7
3
null
null
null
null
UTF-8
Java
false
false
4,647
java
import java.io.IOException; public class class139 extends class349 { static class223 field1522 = new class223(64); static class275 archive4; static class277 field1525; public int field1523 = 0; class139() { } public static void method2345(String var0, boolean var1, boolean var2) { class42.method766(var0, var1, "openjs", var2); } void method2336(Buffer var1) { while(true) { int var3 = var1.readUnsignedByte(); if (var3 == 0) { return; } this.method2344(var1, var3); } } void method2344(Buffer var1, int var2) { if (var2 == 2) { this.field1523 = var1.readUnsignedShort(); } } public static byte[] method2346() { byte[] var1 = new byte[24]; try { class131.field1471.method5795(0L); class131.field1471.method5797(var1); int var2; for(var2 = 0; var2 < 24 && 0 == var1[var2]; ++var2) { } if (var2 >= 24) { throw new IOException(); } } catch (Exception var4) { for(int var3 = 0; var3 < 24; ++var3) { var1[var3] = -1; } } return var1; } static int method2339(int var0, class59 var1, boolean var2) { Interface var4; if (var0 >= 2000) { var0 -= 1000; var4 = class87.getComponent(class51.field747[--class51.field746]); } else { var4 = var2 ? class286.field3660 : class51.field750; } String var5 = class51.field738[--class2.field4]; int[] var6 = null; if (var5.length() > 0 && var5.charAt(var5.length() - 1) == 'Y') { int var7 = class51.field747[--class51.field746]; if (var7 > 0) { for(var6 = new int[var7]; var7-- > 0; var6[var7] = class51.field747[--class51.field746]) { } } var5 = var5.substring(0, var5.length() - 1); } Object[] var9 = new Object[var5.length() + 1]; int var8; for(var8 = var9.length - 1; var8 >= 1; --var8) { if (var5.charAt(var8 - 1) == 's') { var9[var8] = class51.field738[--class2.field4]; } else { var9[var8] = new Integer(class51.field747[--class51.field746]); } } var8 = class51.field747[--class51.field746]; if (-1 != var8) { var9[0] = new Integer(var8); } else { var9 = null; } if (1400 == var0) { var4.field3046 = var9; } else if (1401 == var0) { var4.field3049 = var9; } else if (var0 == 1402) { var4.field2955 = var9; } else if (var0 == 1403) { var4.field3050 = var9; } else if (1404 == var0) { var4.field3052 = var9; } else if (1405 == var0) { var4.field2995 = var9; } else if (1406 == var0) { var4.field3056 = var9; } else if (var0 == 1407) { var4.field3057 = var9; var4.field3058 = var6; } else if (var0 == 1408) { var4.field3017 = var9; } else if (1409 == var0) { var4.field3055 = var9; } else if (var0 == 1410) { var4.field3081 = var9; } else if (var0 == 1411) { var4.field3047 = var9; } else if (1412 == var0) { var4.field3051 = var9; } else if (var0 == 1414) { var4.field3083 = var9; var4.field3060 = var6; } else if (var0 == 1415) { var4.field2996 = var9; var4.field3062 = var6; } else if (1416 == var0) { var4.field2974 = var9; } else if (1417 == var0) { var4.field3065 = var9; } else if (1418 == var0) { var4.field3066 = var9; } else if (var0 == 1419) { var4.field3067 = var9; } else if (1420 == var0) { var4.field3070 = var9; } else if (1421 == var0) { var4.field3059 = var9; } else if (var0 == 1422) { var4.field3074 = var9; } else if (var0 == 1423) { var4.field3008 = var9; } else if (var0 == 1424) { var4.field3076 = var9; } else if (1425 == var0) { var4.field2982 = var9; } else if (1426 == var0) { var4.field3079 = var9; } else if (var0 == 1427) { var4.field3072 = var9; } else if (var0 == 1428) { var4.field3075 = var9; } else if (var0 == 1429) { var4.field3073 = var9; } else if (var0 == 1430) { var4.field3068 = var9; } else { if (var0 != 1431) { return 2; } var4.field3069 = var9; } var4.field3044 = true; return 1; } }
098d00c56268cd85c36af1307c961c81ad033098
e2229b7966a7862237984f733a3316660dfde593
/siscogescorp/src/java/com/siscogescorp/servicios/DocumentosServicios.java
6132df8dc09c7ed9b11afc374f102f4711d18962
[ "Apache-2.0" ]
permissive
estalisto/siscgc
da636392e3e52b45147feab4f1c5fc3c65dd14d0
b8d9d0331fdc291ed539db2fd5b1a9faab3dfd8e
refs/heads/master
2020-03-10T20:00:29.394281
2018-07-11T11:08:22
2018-07-11T11:08:22
129,560,878
0
0
null
null
null
null
UTF-8
Java
false
false
8,180
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.siscogescorp.servicios; import com.siscogescorp.modelo.HibernateUtil; import com.siscogescorp.modelo.LcAgencia; import com.siscogescorp.modelo.LcClientes; import com.siscogescorp.modelo.LcDocumentos; import com.siscogescorp.utils.Conexion; import java.math.BigInteger; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author CIMA2015 */ public class DocumentosServicios { public List<LcDocumentos> getLcDocumentos(){ SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx= session.beginTransaction(); // hacemos la transaccion //ArrayList<LcDocumentos> arreglo = new ArrayList<LcEmpresa>(); Query q = session.createQuery("from LcDocumentos E WHERE E.estado = :estado"); q.setParameter("estado", "A"); List<LcDocumentos> lista=q.list(); for(LcDocumentos list:lista ) { System.out.print("datos: "+list.getIdDocumento()+list.getNombreDocumento()+list.getIdCliente()+list.getFechaRegistro()+list.getFechaActualizado()); } tx.commit(); session.close(); return lista; } public void addDocumentos(LcDocumentos documentos){ SessionFactory factory=HibernateUtil.getSessionFactory(); Session session= factory.openSession(); Transaction tx=session.beginTransaction(); session.save(documentos); tx.commit(); session.close(); } public Long getNext() { SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery("select nextval('lc_documentos_id_documento_seq')"); Long key = ((BigInteger) query.uniqueResult()).longValue(); tx.commit(); session.close(); return key; } public List<LcAgencia> getLcAgenciasxEmpresa(int empresa) { SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx = session.beginTransaction(); ArrayList<LcAgencia> arreglo = new ArrayList<LcAgencia>(); Query q = session.createQuery("from LcAgencia E WHERE E.lcEmpresa.idEmpresa= :idEmpresa and E.estado = :estado "); q.setParameter("idEmpresa", empresa); q.setParameter("estado", "A"); List<LcAgencia> lista = q.list(); for (LcAgencia mrol : lista) { System.out.println("ok: " + mrol.getIdAgencia()+mrol.getLcEmpresa().getIdEmpresa() + ", " + mrol.getLcEmpresa().getRazonSocial()+mrol.getIdAgencia()+mrol.getNombre()); } tx.commit(); session.close(); return lista; } public List<LcClientes> getClientesxempresa(int empresa){ SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx= session.beginTransaction(); Query q = session.createQuery("from LcClientes E WHERE E.lcEmpresa.idEmpresa= :idEmpresa and E.estado = :estado "); q.setParameter("idEmpresa",empresa); q.setParameter("estado","A"); List<LcClientes> lista=q.list(); for(LcClientes mrol:lista ) { System.out.println("ok: "+mrol.getIdCliente()+", "+mrol.getLcEmpresa().getRazonSocial()); } tx.commit(); session.close(); return lista; } public List<LcDocumentos> ConsultaDataDoc(int idDoc){ SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx= session.beginTransaction(); Query q = session.createQuery("from LcDocumentos E WHERE E.idDocumento= :idDocumento and E.estado = :estado "); q.setParameter("idDocumento",idDoc); q.setParameter("estado","A"); List<LcDocumentos> lista=q.list(); for(LcDocumentos mrol:lista ) { System.out.println("ok: "+mrol.getIdDocumento()); } tx.commit(); session.close(); return lista; } public void updateDocumento(int idDocumento, int empresa, int sucursal, int cartera, String nombre_doc, String saludo, String cuerpo, String despedida, String firma){ SessionFactory factory=HibernateUtil.getSessionFactory(); Session session= factory.openSession(); Transaction tx=session.beginTransaction(); LcDocumentos agen = (LcDocumentos)session.get(LcDocumentos.class, idDocumento); agen.setIdEmpresa(empresa); agen.setIdAgencia(sucursal); agen.setIdCliente(cartera); agen.setNombreDocumento(nombre_doc); agen.setSaludo(saludo); agen.setCuerpo(cuerpo); agen.setDespedida(despedida); agen.setFirma(firma); session.update(agen); tx.commit(); session.close(); } public Long getNextTicket() { SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery("select nextval('lc_ticket')"); Long key = ((BigInteger) query.uniqueResult()).longValue(); tx.commit(); session.close(); return key; // return ((BigInteger) query.uniqueResult()).longValue(); } public Integer getEjecutaSQL(String trama, int ticket) { int valor = 0; try{ Conexion conexion=new Conexion(); PreparedStatement pst; ResultSet rs; pst = conexion.getconexion().prepareStatement("select fnc_ejecuta_sentencia('"+trama+"',"+ticket+");"); rs = pst.executeQuery(); while(rs.next()) //Mientras haya una sig. tupla { valor=rs.getInt(1); } rs.close(); pst.close(); conexion.cierraConexion(); }catch (SQLException ex) { System.err.println( ex.getMessage() ); } return valor; } public void deleteDocumento(int id){ SessionFactory factory=HibernateUtil.getSessionFactory(); Session session= factory.openSession(); Transaction tx=session.beginTransaction(); LcDocumentos agen = (LcDocumentos)session.get(LcDocumentos.class, id); agen.setEstado("I"); session.update(agen); tx.commit(); session.close(); } public String getMisDocumentos(int id_empresa, int id_sucursal){ JSONObject json = new JSONObject(); JSONArray itemSelectedJson = new JSONArray(); SessionFactory sesion = HibernateUtil.getSessionFactory(); Session session; session = sesion.openSession(); Transaction tx= session.beginTransaction(); Query q = session.createQuery("from LcDocumentos E WHERE E.idEmpresa= :idEmpresa and E.idAgencia= :idAgencia and E.estado = :estado "); q.setParameter("idEmpresa",id_empresa); q.setParameter("idAgencia",id_sucursal); q.setParameter("estado","A"); List<LcDocumentos> lista=q.list(); for(LcDocumentos datos:lista ) { // json = new JSONObject(); json.put("idDocumento",datos.getIdDocumento()); json.put("nombreDocumento", datos.getNombreDocumento()); itemSelectedJson.add(json); } tx.commit(); session.close(); return itemSelectedJson.toString(); } }
a5c0667025b6809dbcf1bd7d95c649d526378382
9d6ca9d3d1c228ae42e5aa4c1821f66e6632d317
/app/src/main/java/com/dgcheshang/cheji/netty/init/ZdClientHandler.java
1bed732b60c88d81066e330d20df616abad3fbf5
[]
no_license
linzhibin66/lilunji-master4-wk_face
ff69f8924ddbbd3d7fc5cb3caebba480fd717262
9af6003de00a612acf2c4388dc7788895808ce33
refs/heads/master
2020-04-27T17:19:27.280497
2019-03-08T09:52:27
2019-03-08T09:52:27
174,511,371
0
0
null
null
null
null
UTF-8
Java
false
false
3,055
java
package com.dgcheshang.cheji.netty.init; import android.util.Log; import com.dgcheshang.cheji.netty.conf.NettyConf; import com.dgcheshang.cheji.netty.timer.ConTimer; import com.dgcheshang.cheji.netty.util.GatewayService; import com.dgcheshang.cheji.netty.util.MsgUtil; import com.dgcheshang.cheji.netty.util.ZdUtil; import org.apache.commons.lang3.StringUtils; import java.util.Timer; import java.util.TimerTask; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; public class ZdClientHandler extends SimpleChannelInboundHandler<String> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Log.e("TAG","连接异常!"); super.exceptionCaught(ctx, cause); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Log.e("TAG","终端连接服务器激活成功"); GatewayService.addGatewayChannel("serverChannel",ctx); NettyConf.constate=1; if(ZdClient.conTimer!=null){ ZdClient.conTimer.cancel(); ZdClient.conTimer=null; } if(NettyConf.zcstate==0){ //没注册过注册 ZdUtil.sendZdzc(); }else if(NettyConf.zcstate==1&NettyConf.jqstate==0){ //发送终端鉴权 ZdUtil.sendZdjqHex(); } super.channelActive(ctx); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.READER_IDLE){ System.out.println("read idle"); } else if (event.state() == IdleState.WRITER_IDLE){ String hexmsg= MsgUtil.getXthf(NettyConf.mobile); if(StringUtils.isNotEmpty(hexmsg)){ ctx.writeAndFlush(hexmsg); } } else if (event.state() == IdleState.ALL_IDLE){ System.out.println("all idle"); } } } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // 收到消息直接打印输出 if(NettyConf.debug) { Log.e("TAG", ctx.channel().remoteAddress() + " server say: " + msg); } if(StringUtils.isEmpty(msg)){ //消息为空直接丢弃 }else{ ZdHandleMsg zm=new ZdHandleMsg(msg); Thread th=new Thread(zm); th.start(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { GatewayService.removeGatewayChannel("serverChannel"); NettyConf.constate=0; NettyConf.jqstate=0; Log.e("TAG","断开连接重连!"); if(ZdClient.conTimer==null){ Timer timer=new Timer(); TimerTask timerTask=new ConTimer(); timer.schedule(timerTask,1000,35*1000); ZdClient.conTimer=timer;//记录下来 } /*final EventLoop eventLoop = ctx.channel().eventLoop(); eventLoop.schedule(new Runnable() { @Override public void run() { ZdClient.doConnect(); } }, 1L, TimeUnit.SECONDS);*/ super.channelInactive(ctx); } }
9205b505b60542ad159bf3b215d9ea5b40f298e1
1bf2492f45b32316ceb6bf39f3202237be44fa1a
/1.JavaSyntax/src/com/javarush/task/task06/task0614/Cat.java
fb4396f5224c6ea06bb4df72149ed3a3d4e5e4c4
[]
no_license
KiruhaZ/JavaRushTasks
49b3ad65a759a74d3968259ccf1092521f7922e6
6065fcf7a991108a74858d7d95bdff55032ba3bc
refs/heads/master
2021-04-15T15:33:37.299558
2018-03-30T17:03:45
2018-03-30T17:03:45
125,765,660
0
0
null
null
null
null
UTF-8
Java
false
false
632
java
package com.javarush.task.task06.task0614; import java.util.ArrayList; /* Статические коты */ public class Cat { //напишите тут ваш код public static ArrayList<Cat> cats = new ArrayList<>(); public Cat() { } public static void main(String[] args) { //напишите тут ваш код for (int i = 0; i < 10; i++) { cats.add(new Cat()); } printCats(); } public static void printCats() { //напишите тут ваш код for (Cat i : cats) { System.out.println(i); } } }
98163deb8762ae8d5bbdfd68b652acc4f358730b
a552aa8f554d5345a12c11a963f9cd3ffac48a12
/app/src/main/java/com/nayra/gowhite/model/Country.java
85b40cbd34db87d6fa8b3b4f780ebe03c393d51d
[]
no_license
nayra/testProj
f77d5edfdce70384e54371aafd1078254e4bda32
41ff52ada528cd67267ad520d3b8632afb77d33e
refs/heads/master
2021-04-29T03:23:53.061523
2018-04-26T05:43:58
2018-04-26T05:43:58
121,814,603
0
0
null
null
null
null
UTF-8
Java
false
false
785
java
package com.nayra.gowhite.model; import com.google.gson.annotations.SerializedName; /** * Created by nayrael-sayed on 2/17/18. */ public class Country { @SerializedName("Name") private String en_name; @SerializedName("NameAr") private String ar_name; @SerializedName("CountryID") private int countryID; public String getEn_name() { return en_name; } public void setEn_name(String en_name) { this.en_name = en_name; } public String getAr_name() { return ar_name; } public void setAr_name(String ar_name) { this.ar_name = ar_name; } public int getCountryID() { return countryID; } public void setCountryID(int countryID) { this.countryID = countryID; } }
[ "123nany" ]
123nany
ec258611e2dc2eea51984504d038fd1a90b31c1f
02d5244ce8854f3d1bc71e6de11838d065f3b394
/448_Find_All_Numbers_Disappeared_in_an_Array/derek.java
3245707622d88a6dbf55f43ed81cb087ac5d0a29
[]
no_license
wychi/The_LeetCode_Awakens
05f702cf0ba492872c11527ae6dc1f02f862d57c
f1a762f0f680fe23c6d370505adecb7349086446
refs/heads/master
2021-07-08T12:15:15.387044
2019-03-14T02:55:00
2019-03-14T02:55:00
105,601,347
4
1
null
2017-10-03T01:03:18
2017-10-03T01:03:18
null
UTF-8
Java
false
false
570
java
class Solution { //Key: //1. negative each number //Time: O(N) //Space:O(1) public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> result = new ArrayList<Integer>(); int idx = 0; for (int i = 0 ; i< nums.length; i++) { idx = Math.abs(nums[i]); if (nums[idx-1] > 0) nums[idx-1] = -nums[idx-1]; } for (int i = 0 ; i<nums.length; i++) { if (nums[i] > 0) { result.add(i+1); } } return result; } }
dd80cb6df6bd5fd50bba3b486b7a0735f3dadf46
0cd792f2415775d68ff2523e0cdca36fbbcf39f7
/generatorSqlmapCustom2/src/com/yxtk/po/base/PublishBase.java
46900b7c4d12f25b26dd9c68f08c09d5b846ab19
[]
no_license
redenna/mybatis-mapper-sql-
55e3b43e73e304179872d6fc341992febc1a3916
bd946291d94c3ebe51dd49d284461b502b8a2862
refs/heads/master
2021-01-19T23:09:02.473677
2017-03-04T01:03:19
2017-03-04T01:03:19
83,784,325
0
0
null
null
null
null
UTF-8
Java
false
false
1,483
java
package com.yxtk.po.base; public abstract class PublishBase extends BasePo{ private Integer userId; private String title; private String imgUrl1; private String imgUrl2; private String imgUrl3; private Integer publishTypeId; private Integer admCheck; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title == null ? null : title.trim(); } public String getImgUrl1() { return imgUrl1; } public void setImgUrl1(String imgUrl1) { this.imgUrl1 = imgUrl1 == null ? null : imgUrl1.trim(); } public String getImgUrl2() { return imgUrl2; } public void setImgUrl2(String imgUrl2) { this.imgUrl2 = imgUrl2 == null ? null : imgUrl2.trim(); } public String getImgUrl3() { return imgUrl3; } public void setImgUrl3(String imgUrl3) { this.imgUrl3 = imgUrl3 == null ? null : imgUrl3.trim(); } public Integer getPublishTypeId() { return publishTypeId; } public void setPublishTypeId(Integer publishTypeId) { this.publishTypeId = publishTypeId; } public Integer getAdmCheck() { return admCheck; } public void setAdmCheck(Integer admCheck) { this.admCheck = admCheck; } }
0ce01827804cdcbb8b89f07534dfe0a4fa7ac93a
47c2ba713fe1c5830c6e1a39621445da48a9b3fd
/src/patterns/patternsdemonstrator/StateDemonstrator.java
17529efee438ba97883151019ff3d9b9846be5ac
[]
no_license
Artemap98/Lab_patterns
55fc1c232a7d9ba8643dbfa4985327be9edbaa6a
75b13cca16e98783a8a9248d261cf919a208ff1a
refs/heads/master
2023-03-01T15:21:47.516684
2021-02-04T09:56:45
2021-02-04T09:56:45
333,013,330
0
0
null
null
null
null
UTF-8
Java
false
false
1,269
java
package patterns.patternsdemonstrator; import core.Examination; import core.ForeignStudent; import core.LanguageTest; import interfaces.SkillType; import patterns.delegate.punctuationSkill.GreatPunctuationSkill; import patterns.delegate.speakingSkill.GreatSpeakingSkill; import patterns.delegate.syntaxSkill.GreatSyntaxSkill; import patterns.state.MonoTestStudent; public class StateDemonstrator { public void Run(){ //create some student and add skills MonoTestStudent ada = new MonoTestStudent("England", "Ada Lovelace"); ada.AddLanguageSkill(new GreatPunctuationSkill()); ada.AddLanguageSkill(new GreatSpeakingSkill()); ada.AddLanguageSkill(new GreatSyntaxSkill()); //create test LanguageTest test = new LanguageTest(); test.AddSkillType(SkillType.PUNCTUATION); test.AddSkillType(SkillType.SPEAKING); LanguageTest test2 = new LanguageTest(); test2.AddSkillType(SkillType.SYNTAX); test2.AddSkillType(SkillType.SPEAKING); //create standard exam Examination exam = new Examination(); ada.EndTest(); ada.BeginTest(exam, test); ada.BeginTest(exam, test2); ada.EndTest(); System.out.println('\n'); } }
49eab9494620ca6d8220619af0777fedfeadfe71
20077acbb398e76fcefe39e56161d14a69b3fcdf
/app/src/main/java/lt/mm/weatherly/network/LoadResultListener.java
af2c81473a78f055a3cf78d705438e1cc7587664
[]
no_license
marius-m/android_openweather
60ac97dc3c1730e620d6492578acc02b12993f20
6d8df75c5c15f47aaa99eee805710c4ce11641ed
refs/heads/master
2021-01-01T20:17:49.392025
2015-08-23T13:00:27
2015-08-23T13:00:27
41,248,810
0
0
null
null
null
null
UTF-8
Java
false
false
399
java
package lt.mm.weatherly.network; /** * An interface that reports networking state changes */ public interface LoadResultListener<Type> { /** * Callback with a string response from the server * @param response */ void onLoadSuccess(Type response); /** * Callback with a fail message from the server * @param error */ void onLoadFail(String error); }
b4cf1086a9cc585e64b9f1a5ade0ff4081210071
8dfd77caab244debdf56f66b6465e06732364cd8
/projects/jasn1-compiler/src/test/java-gen/org/openmuc/jasn1/compiler/rspdefinitions/DpProprietaryData.java
535d195e7c5c3706a2541c19d3a71b393f48e245
[]
no_license
onderson/jasn1
d195c568b2bf62e9ef558d1caea6e228239ad848
6df87b86391360758fa559d55b9aa6fb98c7f507
refs/heads/master
2021-08-18T16:30:05.353553
2017-07-19T18:39:08
2017-07-19T18:39:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,513
java
/** * This class file was automatically generated by jASN1 v1.8.2-SNAPSHOT (http://www.openmuc.org) */ package org.openmuc.jasn1.compiler.rspdefinitions; import java.io.IOException; import java.io.EOFException; import java.io.InputStream; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.io.Serializable; import org.openmuc.jasn1.ber.*; import org.openmuc.jasn1.ber.types.*; import org.openmuc.jasn1.ber.types.string.*; import org.openmuc.jasn1.compiler.pkix1explicit88.Certificate; import org.openmuc.jasn1.compiler.pkix1explicit88.CertificateList; import org.openmuc.jasn1.compiler.pkix1explicit88.Time; import org.openmuc.jasn1.compiler.pkix1implicit88.SubjectKeyIdentifier; public class DpProprietaryData implements Serializable { private static final long serialVersionUID = 1L; public static final BerTag tag = new BerTag(BerTag.UNIVERSAL_CLASS, BerTag.CONSTRUCTED, 16); public byte[] code = null; public BerObjectIdentifier dpOid = null; public DpProprietaryData() { } public DpProprietaryData(byte[] code) { this.code = code; } public DpProprietaryData(BerObjectIdentifier dpOid) { this.dpOid = dpOid; } public int encode(BerByteArrayOutputStream os) throws IOException { return encode(os, true); } public int encode(BerByteArrayOutputStream os, boolean withTag) throws IOException { if (code != null) { for (int i = code.length - 1; i >= 0; i--) { os.write(code[i]); } if (withTag) { return tag.encode(os) + code.length; } return code.length; } int codeLength = 0; codeLength += dpOid.encode(os, false); // write tag: CONTEXT_CLASS, PRIMITIVE, 0 os.write(0x80); codeLength += 1; codeLength += BerLength.encodeLength(os, codeLength); if (withTag) { codeLength += tag.encode(os); } return codeLength; } public int decode(InputStream is) throws IOException { return decode(is, true); } public int decode(InputStream is, boolean withTag) throws IOException { int codeLength = 0; int subCodeLength = 0; BerTag berTag = new BerTag(); if (withTag) { codeLength += tag.decodeAndCheck(is); } BerLength length = new BerLength(); codeLength += length.decode(is); int totalLength = length.val; if (totalLength == -1) { subCodeLength += berTag.decode(is); if (berTag.tagNumber == 0 && berTag.tagClass == 0 && berTag.primitive == 0) { int nextByte = is.read(); if (nextByte != 0) { if (nextByte == -1) { throw new EOFException("Unexpected end of input stream."); } throw new IOException("Decoded sequence has wrong end of contents octets"); } codeLength += subCodeLength + 1; return codeLength; } if (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0)) { dpOid = new BerObjectIdentifier(); subCodeLength += dpOid.decode(is, false); subCodeLength += berTag.decode(is); } int nextByte = is.read(); if (berTag.tagNumber != 0 || berTag.tagClass != 0 || berTag.primitive != 0 || nextByte != 0) { if (nextByte == -1) { throw new EOFException("Unexpected end of input stream."); } throw new IOException("Decoded sequence has wrong end of contents octets"); } codeLength += subCodeLength + 1; return codeLength; } codeLength += totalLength; subCodeLength += berTag.decode(is); if (berTag.equals(BerTag.CONTEXT_CLASS, BerTag.PRIMITIVE, 0)) { dpOid = new BerObjectIdentifier(); subCodeLength += dpOid.decode(is, false); if (subCodeLength == totalLength) { return codeLength; } } throw new IOException("Unexpected end of sequence, length tag: " + totalLength + ", actual sequence length: " + subCodeLength); } public void encodeAndSave(int encodingSizeGuess) throws IOException { BerByteArrayOutputStream os = new BerByteArrayOutputStream(encodingSizeGuess); encode(os, false); code = os.getArray(); } public String toString() { StringBuilder sb = new StringBuilder(); appendAsString(sb, 0); return sb.toString(); } public void appendAsString(StringBuilder sb, int indentLevel) { sb.append("{"); sb.append("\n"); for (int i = 0; i < indentLevel + 1; i++) { sb.append("\t"); } if (dpOid != null) { sb.append("dpOid: ").append(dpOid); } else { sb.append("dpOid: <empty-required-field>"); } sb.append("\n"); for (int i = 0; i < indentLevel; i++) { sb.append("\t"); } sb.append("}"); } }
e0b1bbd913d1cc2e7cae287d3790e809a0533019
192fc75e245f8834861c2a8dbe9714daa2ec6c2e
/CWE80_XSS/CWE80_XSS__Servlet_PropertiesFile_17.java
bf5caf01efa887a8eda94af5b57df00fecba3ed5
[]
no_license
Carlosboie/Playtech
6f8bb72efc6769612a0cb967a9130f6db78d19fc
684ae94b9b0ff069c8561157227b5b43a7ca1320
refs/heads/master
2021-05-27T11:05:24.157218
2012-09-12T08:08:30
2012-09-12T08:08:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,876
java
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE80_XSS__Servlet_PropertiesFile_17.java Label Definition File: CWE80_XSS__Servlet.label.xml Template File: sources-sink-17.tmpl.java */ /* * @description * CWE: 80 Cross Site Scripting (XSS) * BadSource: PropertiesFile Read a value from a .properties file (in property named data) * GoodSource: A hardcoded string * BadSink: Servlet querystring parameter not sanitized * Flow Variant: 17 Control flow: for loops * * */ package testcases.CWE80_XSS; import testcasesupport.*; import javax.servlet.http.*; import java.util.Properties; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Logger; public class CWE80_XSS__Servlet_PropertiesFile_17 extends AbstractTestCaseServlet { /* uses badsource and badsink */ public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; /* We need to have one source outside of a for loop in order to prevent the Java compiler from generating an error because data is uninitialized */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); data = props.getProperty("data"); } catch( IOException ioe ) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if( finstr != null ) { finstr.close(); } } catch( IOException ioe ) { log_bad.warning("Error closing buffread"); } } for(int for_index_i = 0; for_index_i < 0; for_index_i++) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; } if (data != null) { /* POTENTIAL FLAW: data not validated */ response.getWriter().println("<br>bad() - Parameter name has value " + data); } } /* goodG2B() - use goodsource and badsink by reversing the block outside the for statement with the one in the for statement */ private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable { String data; java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger"); /* FIX: Use a hardcoded string */ data = "foo"; for(int for_index_i = 0; for_index_i < 0; for_index_i++) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ Logger log_bad = Logger.getLogger("local-logger"); data = ""; /* init data */ /* retrieve the property */ Properties props = new Properties(); FileInputStream finstr = null; try { finstr = new FileInputStream("../common/config.properties"); props.load(finstr); data = props.getProperty("data"); } catch( IOException ioe ) { log_bad.warning("Error with stream reading"); } finally { /* clean up stream reading objects */ try { if( finstr != null ) { finstr.close(); } } catch( IOException ioe ) { log_bad.warning("Error closing buffread"); } } } if (data != null) { /* POTENTIAL FLAW: data not validated */ response.getWriter().println("<br>bad() - Parameter name has value " + data); } } public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable { goodG2B(request, response); } /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
5cebaea30e8bcfb8069685e6a37493f705b5ad6d
7373b3165be7a858e852e14cc3b4d954bb27b591
/app/src/main/java/com/microsoft/band/sdk/sampleapp/BandStreamingAppActivity.java
aaec79908e4d4c0627835a31e7806bd27aa53c9c
[]
no_license
minjaes/BandStreamingApp-1
6a9b668b9f3fd6a2022997578dd7a82b928d1d1d
b474396e6668f4e440af1c84b017f78c59194246
refs/heads/master
2016-09-05T19:23:29.294307
2015-08-26T20:35:30
2015-08-26T20:35:30
41,448,661
0
0
null
null
null
null
UTF-8
Java
false
false
25,703
java
//Copyright (c) Microsoft Corporation All rights reserved. // //MIT License: // //Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated //documentation files (the "Software"), to deal in the Software without restriction, including without limitation //the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and //to permit persons to whom the Software is furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all copies or substantial portions of //the Software. // //THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED //TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF //CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS //IN THE SOFTWARE. package com.microsoft.band.sdk.sampleapp; import com.aware.utils.Https; import com.microsoft.band.BandClient; import com.microsoft.band.BandClientManager; import com.microsoft.band.BandException; import com.microsoft.band.BandInfo; import com.microsoft.band.BandIOException; import com.microsoft.band.ConnectionState; import com.microsoft.band.UserConsent; //import com.microsoft.band.sdk.sampleapp.streaming.R; import com.microsoft.band.sensors.BandAccelerometerEvent; import com.microsoft.band.sensors.BandAccelerometerEventListener; import com.microsoft.band.sensors.BandHeartRateEvent; import com.microsoft.band.sensors.BandHeartRateEventListener; import com.microsoft.band.sensors.HeartRateConsentListener; import com.microsoft.band.sensors.SampleRate; import com.microsoft.band.sensors.BandPedometerEvent; import com.microsoft.band.sensors.BandPedometerEventListener; import com.microsoft.band.sensors.BandCaloriesEvent; import com.microsoft.band.sensors.BandCaloriesEventListener; import com.microsoft.band.sensors.BandSkinTemperatureEvent; import com.microsoft.band.sensors.BandSkinTemperatureEventListener; import com.microsoft.band.sensors.BandDistanceEvent; import com.microsoft.band.sensors.BandDistanceEventListener; import com.microsoft.band.sensors.BandContactEvent; import com.microsoft.band.sensors.BandContactEventListener; import com.microsoft.band.sensors.BandContactState; import com.microsoft.band.sensors.BandUVEvent; import com.microsoft.band.sensors.BandUVEventListener; import com.microsoft.band.sensors.BandGyroscopeEvent; import com.microsoft.band.sensors.BandGyroscopeEventListener; import com.microsoft.band.sensors.UVIndexLevel; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.provider.CalendarContract; import android.provider.Settings; import android.util.Base64; import android.util.Log; import android.view.View; import android.app.Activity; import android.os.AsyncTask; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.StringBufferInputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Calendar; import java.io.File; import android.os.Environment; import java.util.Date; import java.sql.Timestamp; import java.util.TimeZone; import com.aware.Aware; import com.aware.Aware_Preferences; import com.aware.utils.Aware_Plugin; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; public class BandStreamingAppActivity extends Aware_Plugin { private BandClient client = null; private Button btnStart; private TextView txtStatus; private File sdCard; private File dir; private File file; private int heartRate; private float x; private float y; private float z; private long steps; private float skinTemp; private long calories; private float distance; private BandContactState contact; private UVIndexLevel UV; private int gyroscope; private String heartRateL = "Unix Timestamp,Local Timestamp,Heart Rate\n"; private String accelerometerL = "Unix Timestamp,Local Timestamp,x,y,z\n"; private String stepsL = "Unix Timestamp,Local Timestamp,steps\n"; private String skinTempL ="Unix Timestamp,Local Timestamp,Skin Temperature\n"; private String caloriesL = "Unix Timestamp,Local Timestamp,Calories\n"; private String distanceL = "Unix Timestamp,Local Timestamp,Distance\n"; private String UVL = "Unix Timestamp,Local Timestamp,UV\n"; private static class Params { String filename; String update; String firstLine; Params(String filename, String update, String firstLine) { this.filename = filename; this.update = update; this.firstLine = firstLine; } } @Override public void onCreate() { super.onCreate(); // ArrayList<NameValuePair> request = new ArrayList<NameValuePair>(); // request.add(new BasicNameValuePair("Time", "3333")); // request.add(new BasicNameValuePair("Value", "23")); // new Https(getApplicationContext()).dataPOST( "https://api.awareframework.com/index.php/webservice/index/421/31wEGFcTZDnY" + "/" + "band" + "/insert", request, true); new appTask().execute(); //runs receivers on background thread sdCard = Environment.getExternalStorageDirectory(); dir = new File (sdCard.getAbsolutePath() + "/band"); dir.mkdirs(); } @Override public int onStartCommand(Intent intent, int x, int y){ super.onStartCommand(intent,x,y); new appTask().execute(); //runs receivers on background thread sdCard = Environment.getExternalStorageDirectory(); dir = new File (sdCard.getAbsolutePath() + "/band"); dir.mkdirs(); return 1; } @Override public void onDestroy(){ super.onDestroy(); //TODO: unregister everything try { client.getSensorManager().unregisterAccelerometerEventListeners(); } catch (BandIOException e) { appendToUI(e.getMessage()); } } private class appTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { try { if (getConnectedBandClient()) { appendToUI("Band is connected.\n"); //register receivers client.getSensorManager().registerAccelerometerEventListener(mAccelerometerEventListener, SampleRate.MS16); client.getSensorManager().registerPedometerEventListener(mPedometerEventListener); client.getSensorManager().registerSkinTemperatureEventListener(mSkinTemperatureEventListener); client.getSensorManager().registerCaloriesEventListener(mCaloriesEventListener); client.getSensorManager().registerUVEventListener(mUVEventListener); client.getSensorManager().registerDistanceEventListener(mDistanceEventListener); if(client.getSensorManager().getCurrentHeartRateConsent() == UserConsent.GRANTED) { client.getSensorManager().registerHeartRateEventListener(mHeartRateEventListener); } else { //TODO: fill in ??? //client.getSensorManager().requestHeartRateConsent(MainActivity.this, mHeartRateConsentListener); } } else { appendToUI("Band isn't connected. Please make sure bluetooth is on and the band is in range.\n"); } } catch (BandException e) { String exceptionMessage=""; switch (e.getErrorType()) { case UNSUPPORTED_SDK_VERSION_ERROR: exceptionMessage = "Microsoft Health BandService doesn't support your SDK Version. Please update to latest SDK."; break; case SERVICE_ERROR: exceptionMessage = "Microsoft Health BandService is not available. Please make sure Microsoft Health is installed and that you have the correct permissions."; break; default: exceptionMessage = "Unknown error occured: " + e.getMessage(); break; } appendToUI(exceptionMessage); } catch (Exception e) { appendToUI(e.getMessage()); } return null; } } private void appendToUI(final String string) { /*this.runOnUiThread(new Runnable() { @Override public void run() { txtStatus.setText(string); } });*/ } private BandAccelerometerEventListener mAccelerometerEventListener = new BandAccelerometerEventListener() { @Override public void onBandAccelerometerChanged(final BandAccelerometerEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); x = event.getAccelerationX(); y = event.getAccelerationY(); z = event.getAccelerationZ(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + x + "," + y + "," + z + "\n"); Params params = new Params("accelerometer.csv",update,accelerometerL); //new writeOnFile().execute(params); //writeOnDB(time, 21); appendToUI(update); } } }; private BandHeartRateEventListener mHeartRateEventListener = new BandHeartRateEventListener() { @Override public void onBandHeartRateChanged(final BandHeartRateEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); heartRate = event.getHeartRate(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + heartRate + "\n"); Params params = new Params("heartRate.csv",update,heartRateL); //new writeOnFile().execute(params); //writeOnDB(time,heartRate); appendToUI(update); } } }; private HeartRateConsentListener mHeartRateConsentListener = new HeartRateConsentListener() { @Override public void userAccepted(boolean b) { // handle user's heart rate consent decision if (!b){ // Consent hasn't been given appendToUI(String.valueOf(b)); } } }; private BandSkinTemperatureEventListener mSkinTemperatureEventListener = new BandSkinTemperatureEventListener() { @Override public void onBandSkinTemperatureChanged(BandSkinTemperatureEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); skinTemp = event.getTemperature(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + skinTemp + "\n"); Params params = new Params("skinTemperature.csv",update,skinTempL); //new writeOnFile().execute(params); writeOnCalendar(time, skinTemp); //writeOnDB(time, skinTemp); /** try { // writeOnServer(time, skinTemp); // uploadUrl("http://epiwork.hcii.cs.cmu.edu/~afsaneh/connection.php", time, skinTemp); }catch(IOException e){ }**/ appendToUI(update); } } }; private BandPedometerEventListener mPedometerEventListener = new BandPedometerEventListener() { @Override public void onBandPedometerChanged(BandPedometerEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); steps = event.getTotalSteps(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + steps + "\n"); Params params = new Params("pedometer.csv",update,stepsL); //new writeOnFile().execute(params); appendToUI(update); } } }; private BandCaloriesEventListener mCaloriesEventListener = new BandCaloriesEventListener() { @Override public void onBandCaloriesChanged(BandCaloriesEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); calories = event.getCalories(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + calories + "\n"); Params params = new Params("calories.csv",update,caloriesL); //new writeOnFile().execute(params); appendToUI(update); } } }; private BandDistanceEventListener mDistanceEventListener = new BandDistanceEventListener() { @Override public void onBandDistanceChanged(BandDistanceEvent event) { if (event != null) { long time = event.getTimestamp(); Date date= new java.util.Date(); distance = event.getTotalDistance(); //can have motiontype, pace and speed as well String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + distance + "\n"); Params params = new Params("distance.csv",update,distanceL); //new writeOnFile().execute(params); appendToUI(update); } } }; private BandUVEventListener mUVEventListener = new BandUVEventListener() { @Override public void onBandUVChanged(BandUVEvent event) { if (event != null){ long time = event.getTimestamp(); Date date= new java.util.Date(); UV = event.getUVIndexLevel(); String update = Long.toString(time); update += "," + new Timestamp(date.getTime()); update += ("," + UV + "\n"); Params params = new Params("UV.csv",update,UVL); //new writeOnFile().execute(params); appendToUI(update); } } }; /* is this information needed? private BandGyroscopeEventListener mGyrosocopeEventListener = new BandGyroscopeEventListener() { @Override public void onBandGyroscopeChanged(BandGyroscopeEvent event) { if (event != null){ time = event.getTimestamp(); } } }; */ private BandContactEventListener mContactEventListener = new BandContactEventListener() { @Override public void onBandContactChanged(BandContactEvent event) { if (event != null) { long time = event.getTimestamp(); contact = event.getContactState(); } } }; private boolean getConnectedBandClient() throws InterruptedException, BandException { if (client == null) { BandInfo[] devices = BandClientManager.getInstance().getPairedBands(); if (devices.length == 0) { appendToUI("Band isn't paired with your phone.\n"); return false; } client = BandClientManager.getInstance().create(getBaseContext(), devices[0]); } else if (ConnectionState.CONNECTED == client.getConnectionState()) { return true; } appendToUI("Band is connecting...\n"); return ConnectionState.CONNECTED == client.connect().await(); } private class writeOnFile extends AsyncTask<Params, Void, Void>{ @Override protected Void doInBackground(Params...params) { String filename = params[0].filename; String update = params[0].update; String firstLine = params[0].firstLine; file = new File(dir, filename); if(!file.exists()) { try { file.createNewFile(); FileOutputStream nfos = null; try { nfos = new FileOutputStream(file,true); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputStreamWriter nosw = new OutputStreamWriter(nfos); try { nosw.write(firstLine); nosw.flush(); nosw.close(); } catch (Exception ex) { Log.e("DEBUG", "HERE"); ex.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos = null; try { fos = new FileOutputStream(file,true); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputStreamWriter osw = new OutputStreamWriter(fos); try { osw.write(update); osw.flush(); osw.close(); } catch (Exception ex) { Log.e("DEBUG", "HERE"); ex.printStackTrace(); } return null; } } private void writeOnDB (long timeStamp, float value){ //Intent aware = new Intent(this, Aware.class); // startService(aware); ContentValues new_data = new ContentValues(); new_data.put(bandProvider.Band_Data.DEVICE_ID, Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID)); new_data.put(bandProvider.Band_Data.TIMESTAMP, timeStamp); new_data.put(bandProvider.Band_Data._Value, value); getContentResolver().insert(bandProvider.Band_Data.CONTENT_URI, new_data); } /** private class UploadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { // params comes from the execute() call: params[0] is the url. try { final String result = uploadUrl(urls[0]); runOnUiThread(new Runnable() { @Override public void run() { resultText.setText(result); } }); return uploadUrl(urls[0]); } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } **/ private String uploadUrl(String myurl, long timestamp, float value) throws IOException { InputStream is = null; int len = 2500; URL url = new URL(myurl); String paramString = "time = " + Long.toString(timestamp) + " " + "value = " + Float.toString(value); String urlParameter = "param1="+paramString; byte[] postData = urlParameter.getBytes(StandardCharsets.UTF_8); String base64 = Base64.encodeToString(postData, Base64.DEFAULT); int postDataLength = postData.length; byte[] uploadData = myurl.getBytes(StandardCharsets.UTF_8); int uploadDataLength = uploadData.length; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); //conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setUseCaches(false); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } String offsetAmount = base64Encoder(timeZoneBuilder()); //DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); //wr.write(uploadData); conn.getInputStream(); String android_id = Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID); //String contentAsString = readIt(is, len); return "uploading data"; } private String timeZoneBuilder() { String timeZone = ""; Date now = new Date(); int offsetFromUTC = TimeZone.getDefault().getOffset(now.getTime())/3600000; String offsetAmount = Integer.toString(offsetFromUTC); if (offsetFromUTC>=0) { timeZone = timeZone + "+"; } else if (offsetFromUTC<0) { timeZone = timeZone + "-"; } if (Math.abs(offsetFromUTC)<10) { timeZone = timeZone + "0"; } timeZone = timeZone + Integer.toString(Math.abs(offsetFromUTC))+ ":00" ; return timeZone; } private String base64Encoder (String stringToEncode) { byte[] stringToByte = stringToEncode.getBytes(StandardCharsets.UTF_8); String base64 = Base64.encodeToString(stringToByte, Base64.DEFAULT); return base64; } // onPostExecute displays the results of the AsyncTask. //Given a URL, establishes an HTTPUrlConnection and uploads // the data given to it via HTTPPost public void writeOnServer(long timestamp, float value) throws IOException { String myURL = "http://epiwork.hcii.cs.cmu.edu/~afsaneh/connection.php"; InputStream is = null; int len = 2500; String myurl = "http://epiwork.hcii.cs.cmu.edu/~afsaneh/connection.php"; URL url = new URL("http://epiwork.hcii.cs.cmu.edu/~afsaneh/connection.php"); String paramString = "time = " + Long.toString(timestamp) + " " + "value = " + Float.toString(value); String urlParameter = "param1="+paramString; byte[] postData = urlParameter.getBytes(StandardCharsets.UTF_8); String base64 = Base64.encodeToString(postData, Base64.DEFAULT); //int postDataLength = postData.length; byte[] uploadData = myurl.getBytes(StandardCharsets.UTF_8); int uploadDataLength = uploadData.length; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); //conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setRequestProperty("Content-Length", Integer.toString(uploadDataLength)); conn.setUseCaches(false); /* try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); } */ //String offsetAmount = base64Encoder(timeZoneBuilder()); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.write(uploadData); //conn.getInputStream(); //String android_id = Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID); //String contentAsString = readIt(is, len); // return base64Encoder(android_id) + " " + offsetAmount + " " + base64 + " " + uploadData; } private void writeOnCalendar (long timeStamp, float value){ ContentValues event = new ContentValues(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(CalendarContract.Events.DTSTART, timeStamp); values.put(CalendarContract.Events.DTEND, timeStamp + 60*60*1000); values.put(CalendarContract.Events.TITLE, Float.toString(value)); values.put(CalendarContract.Events.CALENDAR_ID, 1); values.put(CalendarContract.Events.EVENT_TIMEZONE, "New_York"); Uri eventsUri = Uri.parse("content://com.android.calendar/events"); Uri insertedUri = getContentResolver().insert(eventsUri, values); } }
31f738be2244882b7d230a298a7f7cb865b3f379
42d789bc3ea5ac7c0e90a089863c98d6c54c8a3b
/app/src/main/java/com/example/celine/mymoviesapp/MoviesResponse.java
a8b15c63bfd65f9e5b4e911c8b3e1c3255655552
[]
no_license
ccarlier92/PROJECT_MOBILE
8fdfe1ba389e69b99f4735677b60b04de792ea20
4c72816b7bbdec5e5d1ba5c5d6526822d1c5dfc7
refs/heads/master
2020-04-30T22:59:06.244270
2019-03-22T12:05:39
2019-03-22T12:05:39
177,132,996
0
0
null
null
null
null
UTF-8
Java
false
false
1,090
java
package com.example.projectmobile; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class MoviesResponse { @SerializedName("page") @Expose private int page; @SerializedName("total_results") @Expose private int totalResults; @SerializedName("results") @Expose private List<Movie> movies; @SerializedName("total_pages") @Expose private int totalPages; public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getTotalResults() { return totalResults; } public void setTotalResults(int totalResults) { this.totalResults = totalResults; } public List<Movie> getMovies() { return movies; } public void setMovies(List<Movie> movies) { this.movies = movies; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } }
4a9e364dbece91b155fdc783325a97daee1643c6
b2002471733e3fd325bcbd178bdf70d73f907fc4
/test/KthSmallestPrimeFraction.java
841869a762f5ac492961cf061c6ce518488d2798
[]
no_license
kantrar/hacker-rank
c389563e72d885ada803dc464bbfee0b3d4ec161
bdeb71b8acfdbd011b735e68690d83a9ba697f6e
refs/heads/master
2022-10-15T03:46:26.781084
2019-11-07T14:49:02
2019-11-07T14:49:02
164,281,437
0
0
null
2022-10-04T23:47:26
2019-01-06T06:25:36
Java
UTF-8
Java
false
false
586
java
import java.util.PriorityQueue; public class KthSmallestPrimeFraction { public int[] kthSmallestPrimeFraction(int[] A, int K) { PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> A[a[0]] * A[b[1]] - A[b[0]] * A[a[1]]); for (int i = 0; i < A.length - 1; i++) { queue.offer(new int[] {i, A.length - 1}); } while (K > 1 && !queue.isEmpty()) { int[] cur = queue.poll(); if (cur[0] + 1 != cur[1]) { queue.offer(new int[] {cur[0], cur[1] - 1}); } K--; } return queue.isEmpty() ? new int[0] : new int[] {A[queue.peek()[0]], A[queue.peek()[1]]}; } }
95d96a46ac3313d02efd60594c0ca88594c24b78
df4eb7b3e3d53c85108d2d0d412aa85d6ffb2c76
/main/java/dtx/src/main/java/com/oodrive/nuage/dtx/SyncEventHandler.java
a2451da2dc7e2e53d13be155eb6401c02ccaa3f8
[]
no_license
cyrinux/eguan
8526c418480f30a3a3ccd5eca2237a68fd2bbc8f
9e20281655838c8c300f1aa97ad03448e16328c8
refs/heads/master
2021-01-17T20:21:35.000299
2015-02-19T15:22:46
2015-02-19T15:22:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,899
java
package com.oodrive.nuage.dtx; /* * #%L * Project eguan * %% * Copyright (C) 2012 - 2015 Oodrive * %% * 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. * #L% */ import static com.oodrive.nuage.dtx.DtxResourceManagerState.LATE; import static com.oodrive.nuage.dtx.DtxResourceManagerState.SYNCHRONIZING; import static com.oodrive.nuage.dtx.DtxResourceManagerState.UNDETERMINED; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.UUID; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; import com.oodrive.nuage.dtx.events.DtxResourceManagerEvent; /** * Event handler for triggering synchronization actions. * * @author oodrive * @author pwehrle * */ public final class SyncEventHandler { private static final Logger LOGGER = LoggerFactory.getLogger(SyncEventHandler.class); /** * Intercepts {@link DtxResourceManagerEvent}s for {@link DtxResourceManagerState#LATE} resource managers and * triggers synchronization. * * @param event * the posted {@link DtxResourceManagerEvent} */ @Subscribe @AllowConcurrentEvents public final void handleDtxResourceManagerEvent(@Nonnull final DtxResourceManagerEvent event) { final DtxResourceManagerState newState = event.getNewState(); if (LATE != newState) { // not late, i.e. do not trigger synchronization return; } final UUID resId = event.getResourceManagerId(); final DtxManager dtxManager = event.getSource(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Triggering synchronization; node=" + dtxManager.getNodeId() + ", resourceId=" + resId); } final TransactionManager txManager = dtxManager.getTxManager(); if (txManager == null) { LOGGER.warn("Transaction manager is null, abandoning synchronization"); return; } txManager.setResManagerSyncState(resId, SYNCHRONIZING); try { long lastLocalTxId = txManager.getLastCompleteTxIdForResMgr(resId); final Map<DtxNode, Long> updateMap = dtxManager.getClusterMapInfo(resId, Long.valueOf(lastLocalTxId)); if (updateMap.isEmpty()) { return; } final long maxTxId = Collections.max(updateMap.values()).longValue(); // TODO: choose update source more wisely final Iterator<DtxNode> nodeIter = updateMap.keySet().iterator(); while (nodeIter.hasNext() && (lastLocalTxId < maxTxId)) { final DtxNode targetNode = nodeIter.next(); final long targetNodeLastTxId = updateMap.get(targetNode).longValue(); if (targetNodeLastTxId > lastLocalTxId) { lastLocalTxId = dtxManager .synchronizeWithNode(resId, targetNode, lastLocalTxId, targetNodeLastTxId); } } } finally { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Synchronization finished; node=" + dtxManager.getNodeId() + ", resourceId=" + resId); } txManager.setResManagerSyncState(resId, UNDETERMINED); } } }
011569d3be4214e321b56abbf72c99825b4d5ae5
f56575a1e6c22fc83ff2bd381c9d6175c3aaeebf
/src/main/java/com/cxf/mblog/base/oauth/OauthOsc.java
dc43bba8c2ca44fe27da8946a2a28c0469649be0
[]
no_license
Mrchai521/chai-bolg
f3bed9865ba3ee7f390415152d081144655ea6e0
b227b7de7f00bc0cb3e8880bbe8f7b932a4f7afa
refs/heads/master
2023-08-05T08:33:01.617427
2021-09-24T02:44:36
2021-09-24T02:44:36
314,513,909
1
1
null
null
null
null
UTF-8
Java
false
false
3,988
java
package com.cxf.mblog.base.oauth; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.cxf.mblog.base.oauth.utils.OathConfig; import com.cxf.mblog.base.oauth.utils.TokenUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.HashMap; import java.util.Map; public class OauthOsc extends Oauth { private static final Logger LOGGER = LoggerFactory.getLogger(OauthOsc.class); private static final String AUTH_URL = "http://www.oschina.net/action/oauth2/authorize"; private static final String TOKEN_URL = "http://www.oschina.net/action/openapi/token"; private static final String USER_INFO_URL = "http://www.oschina.net/action/openapi/user"; private static final String TWEET_PUB = "http://www.oschina.net/action/openapi/tweet_pub"; public static OauthOsc me() { return new OauthOsc(); } public OauthOsc() { setClientId(OathConfig.getValue("openid_osc")); setClientSecret(OathConfig.getValue("openkey_osc")); setRedirectUri(OathConfig.getValue("redirect_osc")); } public String getAuthorizeUrl(String state) throws UnsupportedEncodingException { Map<String, String> params = new HashMap<>(); params.put("response_type", "code"); params.put("client_id", getClientId()); params.put("redirect_uri", getRedirectUri()); if (StringUtils.isNotBlank(state)) { params.put("state", state); } return super.getAuthorizeUrl("http://www.oschina.net/action/oauth2/authorize", params); } public String getTokenByCode(String code) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException { Map<String, String> params = new HashMap<>(); params.put("code", code); params.put("client_id", getClientId()); params.put("client_secret", getClientSecret()); params.put("grant_type", "authorization_code"); params.put("redirect_uri", getRedirectUri()); String token = TokenUtil.getAccessToken(super.doGet("http://www.oschina.net/action/openapi/token", params)); LOGGER.debug(token); return token; } public JSONObject getUserInfo(String accessToken) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException { Map<String, String> params = new HashMap<>(); params.put("access_token", accessToken); String userInfo = super.doGet("http://www.oschina.net/action/openapi/user", params); JSONObject dataMap = JSON.parseObject(userInfo); LOGGER.debug(dataMap.toJSONString()); return dataMap; } public JSONObject tweetPub(String accessToken, String msg) { Map<String, String> params = new HashMap<>(); params.put("access_token", accessToken); params.put("msg", msg); try { JSONObject dataMap = JSON.parseObject(super.doPost("http://www.oschina.net/action/openapi/tweet_pub", params)); LOGGER.debug(JSON.toJSONString(dataMap)); } catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException | IOException e) { LOGGER.error(e.getMessage(), e); } return null; } public JSONObject getUserInfoByCode(String code) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException { String accessToken = getTokenByCode(code); if (StringUtils.isBlank(accessToken)) { return null; } JSONObject dataMap = getUserInfo(accessToken); dataMap.put("access_token", accessToken); LOGGER.debug(JSON.toJSONString(dataMap)); return dataMap; } }
4ae8f3ec2ab08d415322d33b59de1fe896eec449
04c378bddc6b97385880fe69fa64ce8c474f3fc4
/JDBC Programs/JdbcAssignment/src/service/EmployeeService.java
078e74bf3b1ca3bc46ace3c8b72aef92fdc3538c
[]
no_license
Kaleakash/onmobilebangalorejavafullstack
c994ec0c51751e2493708e8867651d1adbabb396
4beb86734f1d346cc0fa7b2ddea388a501199ca8
refs/heads/master
2023-01-07T16:25:03.156914
2019-11-21T10:36:36
2019-11-21T10:36:36
206,296,478
0
1
null
2023-01-07T11:59:45
2019-09-04T10:46:52
JavaScript
UTF-8
Java
false
false
1,083
java
package service; import java.util.Iterator; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; import bean.Employee; import dao.EmployeeDao; public class EmployeeService { EmployeeDao ed; public EmployeeService() { ed = new EmployeeDao(); } public String addEmployee(Employee emp) { if(emp.getSalary()>12000) { if(ed.storeEmployeeInfo(emp)>0) { return "Record stored Successfully"; }else { return "Record not store"; } }else { return "Salary must be >12000"; } } public List<Employee> getEmployeeInfo() { /*List<Employee> listOfRec = ed.retrieveAllEmployeeInfo(); Iterator<Employee> li = listOfRec.iterator(); while(li.hasNext()) { Employee emp = li.next(); emp.setSalary(emp.getSalary()+500); } return listOfRec;*/ return ed.retrieveAllEmployeeInfo().stream().map(e->{e.setSalary(e.getSalary()+500);return e;}). collect(Collectors.toList()); //return ed.retrieveAllEmployeeInfo(); } }
7dfe3a8a95a3426afca1ed522586c792bb7acb34
c5cb0f0efdcac651e5b73db7121e934ef4bbe975
/src/commands/StudentsWishes.java
5e6371c3623533d019243e5dd085f5beef8279d5
[]
no_license
vchorbov/secretSanta
79994cec0d3b911d043d4e75140eb3f51cb7f2dc
172be3e270a2484913e0e4268ad89d902eeb56c6
refs/heads/main
2023-03-15T05:57:20.329254
2021-03-17T10:29:35
2021-03-17T10:29:35
344,422,826
0
0
null
null
null
null
UTF-8
Java
false
false
2,376
java
package commands; import storage.StudentsWishesStorage; import java.util.*; public class StudentsWishes { private StudentsWishesStorage storage; private final Map<String, ArrayList<String>> studentsWishes; private final Random RANDOM; private final Vault vault; public StudentsWishes(Vault vault, StudentsWishesStorage storage){ this.storage = storage; this.studentsWishes = storage.getMap(); this.RANDOM = new Random(); this.vault = vault; } public String postWish(String arguments) { String[] argumentsArray = arguments.split(" " ); String username = argumentsArray[0]; String gift = argumentsArray[1]; String client = argumentsArray[2]; if(!vault.userExists(client)){ return String.format("[ Student with username %s is not registered, so they have no permission to post wishes ] " ,client); } if (!vault.userIsLoggedIn(client)){ return String.format("[ Student with username %s is not logged in, so they have no permission to post wishes ] " ,client); } if(!vault.userExists(username)){ return String.format("[ Student with username %s is not registered ] " ,username); } if (!studentsWishes.containsKey(username)) { studentsWishes.put(username, new ArrayList<>()); } else if (studentsWishes.get(username).contains(gift)) { return "[ The same gift for student " + username + " was already submitted ]"; } studentsWishes.get(username).add(gift); return "[ Gift " + gift + " for student " + username + " submitted successfully ]"; } public String getWish(String arguments) { String name = arguments.trim(); List<String> students = new ArrayList<>(studentsWishes.keySet()); List<String> studentsCopy = new ArrayList<>(students); studentsCopy.remove(name); if (studentsCopy.isEmpty()) { return "[ There are no other students present in the wish list]"; } String randomStudent = studentsCopy.get(RANDOM.nextInt(studentsCopy.size())); String randomStudentWishes = studentsWishes.get(randomStudent).toString(); studentsWishes.remove(randomStudent); return "[ " + randomStudent + ": " + randomStudentWishes + " ]"; } }
014b9efd3f3d3fa89f971149c6f3dd8129e151db
a5c0483ae6b394b96dcce41165cc76e9dca7109f
/siif20130305/src/ar/com/siif/struts/actions/forms/FiscalizacionForm.java
743eb75d5e369056a7a0d97d4ee7e5f79bcf0112
[]
no_license
ticoerrecart/siif
8a11e22b1128a0e471b1104a2f4438ceff701c0e
aa4098058c2d16ab05f677a8e2e6b5124d89a816
refs/heads/master
2020-05-18T19:53:55.725951
2015-11-10T12:48:47
2015-11-10T12:48:47
35,677,847
0
0
null
null
null
null
UTF-8
Java
false
false
4,219
java
package ar.com.siif.struts.actions.forms; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.FactoryUtils; import org.apache.commons.collections.list.LazyList; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import ar.com.siif.dto.FiscalizacionDTO; import ar.com.siif.dto.MuestraDTO; import ar.com.siif.struts.utils.Validator; import ar.com.siif.utils.Constantes; public class FiscalizacionForm extends ActionForm { //-------------// private FiscalizacionDTO fiscalizacionDTO; private List<MuestraDTO> muestrasDTO; //-------------// public FiscalizacionForm() { //fiscalizacion = new Fiscalizacion(); /*muestras = (List<Muestra>) LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(Muestra.class));*/ fiscalizacionDTO = new FiscalizacionDTO(); muestrasDTO = (List<MuestraDTO>) LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(MuestraDTO.class)); } @Override public void reset(ActionMapping mapping, HttpServletRequest request) { /*Fiscalizacion f = (Fiscalizacion)request.getSession().getAttribute("fiscalizacion"); muestras = (List<Muestra>) LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(Muestra.class));*/ FiscalizacionDTO fDTO = (FiscalizacionDTO) request.getSession().getAttribute( "fiscalizacionDTO"); if (fDTO != null) { //fiscalizacion = f; fiscalizacionDTO = fDTO; } else { //fiscalizacion = new Fiscalizacion(); fiscalizacionDTO = new FiscalizacionDTO(); } muestrasDTO = (List<MuestraDTO>) LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(MuestraDTO.class)); } public boolean validar(StringBuffer error) { boolean ok2 = true; boolean ok3 = true; boolean ok4 = true; boolean ok5 = true; boolean ok6 = true; boolean ok7 = true; boolean ok8 = true; boolean ok9 = true; boolean ok10 = true; boolean ok11 = true; boolean ok12 = true; boolean ok13 = true; boolean ok14 = true; boolean ok15 = true; boolean ok16 = true; ok2 = Validator.validarComboRequerido("-1", Long.toString(fiscalizacionDTO.getProductorForestal().getId()), "Productor Forestal", error); ok5 = Validator.requerido(fiscalizacionDTO.getFecha(), "Fecha", error) && Validator.validarFechaValida(fiscalizacionDTO.getFecha(), "Fecha", error); ok3 = Validator.requerido(fiscalizacionDTO.getPeriodoForestal(), "Periodo Forestal", error); ok11 = Validator.validarComboRequerido("-1", Long.toString(fiscalizacionDTO.getTipoProducto().getId()), "Tipo de Producto", error); ok9 = Validator.validarDoubleMayorQue(0, Double.toString(fiscalizacionDTO.getCantidadMts()), "Cantidad Mts3", error); if (fiscalizacionDTO.getTipoProducto().getId().longValue() != Constantes.LENIA_ID) { ok8 = Validator.validarEnteroMayorQue(0, Integer.toString(fiscalizacionDTO.getCantidadUnidades()), "Cantidad Unidades", error); ok10 = Validator.validarEnteroMayorQue(0, Integer.toString(fiscalizacionDTO.getTamanioMuestra()), "Tamaño de la Muestra", error); ok16 = Validator.validarMuestras(this.getMuestrasDTO(), fiscalizacionDTO .getTipoProducto().getId(), error); } ok11 = Validator.validarComboRequerido("-1", Long.toString(fiscalizacionDTO.getOficinaAlta().getId()), "Oficina", error); ok15 = Validator.validarComboRequerido("-1", Long.toString(fiscalizacionDTO.getRodal().getId()), "Rodal", error); //VALIDACIONES FISCALIZACION return ok2 && ok3 && ok4 && ok5 && ok6 && ok7 && ok8 && ok9 && ok10 && ok11 && ok12 && ok13 && ok14 && ok15 && ok16; } public FiscalizacionDTO getFiscalizacionDTO() { return fiscalizacionDTO; } public void setFiscalizacionDTO(FiscalizacionDTO fiscalizacionDTO) { this.fiscalizacionDTO = fiscalizacionDTO; } public List<MuestraDTO> getMuestrasDTO() { return muestrasDTO; } public void setMuestrasDTO(List<MuestraDTO> muestrasDTO) { this.muestrasDTO = muestrasDTO; } }
[ "[email protected]@0f544f79-e0f4-099d-537f-5924260e9aa1" ]
[email protected]@0f544f79-e0f4-099d-537f-5924260e9aa1
81bb27e887fea125c27f09c6b71b7b43cf4337a3
1d59eb18c837a03adcfb79796ce935312df84f73
/src/main/java/lemon/day16/section01/All_Test_Case1.java
9b8684c155fa3b48cae19a40dbe6567392d25e2f
[]
no_license
Liyinglong1/LemonStudy_Maven
7f3c52603c162711a27a2c575fbc06b00aaa30f2
98ae415c75a80ac46a7f46d6dea47a93db972a75
refs/heads/master
2022-07-20T11:54:11.656996
2019-09-23T00:01:42
2019-09-23T00:01:42
204,883,557
0
0
null
2022-06-29T17:39:10
2019-08-28T08:24:39
Java
UTF-8
Java
false
false
1,362
java
package lemon.day16.section01; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; /** * code为2 msg是不存在-->描述成json * {"code":2,"msg":"账号已存在","msg":"xxxxx"}-->object * [{"jsonPath":"$.code","expected":2},"jsonPath":"$.msg","expected":"账号已存在"}] * @author happy * http://www.lemfix.com/topics/54 -->jsonpath * http://www.lemfix.com/topics/75 * */ public class All_Test_Case1 { /** * 数据提供者 * @return 二维数组 */ @DataProvider public Object[][] getData() { return ApiUtils.getData(); } /** * * @param apiCaseDetail */ @Test(dataProvider = "getData") public void test_case(ApiCaseDetail apiCaseDetail) { String result = HttpUtils.excute(apiCaseDetail); System.out.println(result); } public static void main(String[] args) { String jsonStr = "{\"code\":2,\"msg\":\"账号已存在\",\"data\":null,\"copyright\":\"Copyright 柠檬班 © 2017-2019 湖南省零檬信息技术有限公司 All Rights Reserved\"}\n" + ""; String jsonPath = "$.copyright"; Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonStr); Object code = JsonPath.read(document, jsonPath); System.out.println(code); } }
9c450f604e8732c3e7d138f4228fe4deee11b454
cfb0bb73ade43a47ba9c22d85109f978508c068e
/thesis-app-proxy/src/main/java/cz/ondrejsmetak/parser/CipherParser.java
9e78ad319bdfd55fb9f7638059bb9eefa38471dd
[ "Unlicense" ]
permissive
fredomgc/ssl-tls-client-scanner
d8e50b67eae1cd9c4b1b0b80e2bc15a4f2ae46f8
72c0557307314ec7835376be5dbb21f3841afcdb
refs/heads/master
2018-12-19T13:27:19.906716
2018-09-16T02:36:49
2018-09-16T02:36:49
110,525,491
0
0
null
null
null
null
UTF-8
Java
false
false
4,599
java
package cz.ondrejsmetak.parser; import cz.ondrejsmetak.CipherSuiteRegister; import cz.ondrejsmetak.entity.CipherSuite; import cz.ondrejsmetak.entity.Mode; import cz.ondrejsmetak.other.XmlParserException; import cz.ondrejsmetak.ResourceManager; import cz.ondrejsmetak.tool.Helper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author Ondřej Směták <[email protected]> */ public class CipherParser extends BaseParser { public static final String FILE = "ciphers.xml"; private static final String TAG_CIPHER_SUITES = "cipherSuites"; private static final String TAG_CIPHER_SUITE = "cipherSuite"; private static final String ATTRIBUTE_HEX_VALUE = "hexValue"; private static final String ATTRIBUTE_NAME = "name"; @Override public void createDefault() throws IOException { InputStream source = ResourceManager.getDefaultConfigurationXml(); Path destination = new File(FILE).toPath(); Files.copy(source, destination); } @Override public boolean hasDefaultFile() { return true; //always true, because file is part of resources } private void checkNode(Node node) throws XmlParserException { ArrayList supportedTags = new ArrayList<>(Arrays.asList(new String[]{ TAG_CIPHER_SUITES, TAG_CIPHER_SUITE})); if (!supportedTags.contains(node.getNodeName())) { throw new XmlParserException("Unknown tag [%s]. You must use only supported tags!", node.getNodeName()); } /** * Tag "cipherSuite" must have "name" and "hexValue" atribute */ if (node.getNodeName().equals(TAG_CIPHER_SUITE)) { checkAttributesOfNode(node, ATTRIBUTE_HEX_VALUE, ATTRIBUTE_NAME); } } public void parse() throws XmlParserException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(ResourceManager.getCiphersConfigurationXml()); doc.getDocumentElement().normalize(); NodeList tags = doc.getElementsByTagName("*"); NodeList cipherSuites = doc.getElementsByTagName(TAG_CIPHER_SUITES); if (cipherSuites.getLength() != 1 || !(cipherSuites.item(0) instanceof Element)) { throw new XmlParserException(String.format("Tag [%s] must be specified exatly once.", TAG_CIPHER_SUITES)); } /** * Parse cipher suites and store them */ for (int i = 0; i < tags.getLength(); i++) { Node node = tags.item(i); checkNode(node); if (node.getNodeType() == Node.ELEMENT_NODE) { /** * Cipher suite */ parseCipherSuite((Element) node); } } } catch (ParserConfigurationException | SAXException | IllegalArgumentException | IOException ex) { throw new XmlParserException(ex); } } private void parseCipherSuite(Node node) throws XmlParserException { if (!(node instanceof Element)) { return; } Element element = (Element) node; if (element.getTagName().equals(TAG_CIPHER_SUITE)) { String hexValue = element.getAttribute(ATTRIBUTE_HEX_VALUE); checkHexValue(hexValue, 4); String name = element.getAttribute(ATTRIBUTE_NAME); CipherSuite cipherSuite = new CipherSuite(hexValue, name, new Mode(Mode.Type.CAN_BE)); if (cipherSuite.getHex().equals(CipherSuiteRegister.TLS_FALLBACK_SCSV_HEX)) { throw new XmlParserException("Cipher suite TLS_FALLBACK_SCSV is supported by directive \"tlsFallbackScsv\". " + "Please, remove this cipher suite from \"cipherSuites\" section!", cipherSuite); } if (CipherSuiteRegister.getInstance().containsCipherSuite(cipherSuite)) { throw new XmlParserException("Cipher suite [%s] is already present!", cipherSuite); } CipherSuiteRegister.getInstance().addCipherSuite(cipherSuite); } } /** * Check if given value is in valid hexadecimal with expected digits count * * @param value * @param size * @throws XmlParserException */ private void checkHexValue(String value, int digits) throws XmlParserException { if (!Helper.isHex(value)) { throw new XmlParserException("Value [%s] isn't valid hexadecimal value!", value); } if (value.length() != digits) { throw new XmlParserException("Value [%s] must have exactly [%s] digit(s)!", value, digits); } } }
840d9b3021e1064c2b912ba51b0bbc6b4e2fef16
571fc48d53e6377d2fe266f84c35181aacc80202
/Fgcm/app/src/main/java/com/fanwang/fgcm/bean/SearchUserIdBean.java
98a211b21252964917e0231e9325cf6ed81218cf
[]
no_license
edcedc/Fg
618a381d4399664d3fac9e04dd7a11b62b752f7e
19fd32837347fd17f9b43e816e3cc9fd0c207eb4
refs/heads/master
2020-04-04T10:08:23.469555
2019-06-29T06:09:21
2019-06-29T06:09:21
155,843,816
0
0
null
null
null
null
UTF-8
Java
false
false
739
java
package com.fanwang.fgcm.bean; import org.litepal.crud.DataSupport; import java.util.ArrayList; import java.util.List; /** * Created by edison on 2018/4/25. */ public class SearchUserIdBean extends DataSupport{ private int id; private String userId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } private List<SearchListBean> list = new ArrayList<>(); public List<SearchListBean> getList() { return list; } public void setList(List<SearchListBean> list) { this.list = list; } }
f7ae8a1efd78f870b3695f97dc96513d63c94b15
f473682f61dbb73a8f340570dd6573e1af93cf4a
/recipe/.svn/pristine/f7/f7ae8a1efd78f870b3695f97dc96513d63c94b15.svn-base
74ee5008f2f02790314bebb37956176aee513231
[]
no_license
SkyKim1016/A.I-Admin
37e9ee5551024138c30e754942899fe9a1a51133
d4eb617c2dbf43e76bb3dcc0145477f6b0abb876
refs/heads/master
2021-06-11T00:31:00.755387
2017-01-29T23:46:17
2017-01-29T23:46:17
77,774,173
0
0
null
null
null
null
UTF-8
Java
false
false
2,037
package com.onethefull.recipe.mapper; import java.util.List; import org.springframework.stereotype.Repository; import com.onethefull.recipe.comm.auth.User; import com.onethefull.recipe.comm.auth.UserSimple; import com.onethefull.recipe.comm.vo.DeviceVO; import com.onethefull.recipe.comm.vo.PageInfoVO; import com.onethefull.recipe.req.AuthTokenReq; import com.onethefull.recipe.req.ModifyFavoriteStep1Req; import com.onethefull.recipe.req.UserDeviceReq; import com.onethefull.recipe.req.UserReq; import com.onethefull.recipe.req.UserServiceProviderInfoReq; import com.onethefull.recipe.vo.CheckActivityVO; import com.onethefull.recipe.vo.CheckHealthVO; import com.onethefull.recipe.vo.CheckJobVO; @Repository("userAuthMapper") public interface UserAuthMapper { public User getUserbyAuthToken(User user); public User findUserbyIdPassword(UserReq req); public User findUserbyLoginId(UserReq req); public User findUserbyId(UserReq req); public User findUserbyProviderUserId(UserServiceProviderInfoReq req); public User findUserbyDeviceInfo(UserServiceProviderInfoReq req); public int setAuthToken(AuthTokenReq req); public int setUserDeviceInfo(UserDeviceReq req); public DeviceVO getUserDeviceInfo(UserDeviceReq req); public int setUserServiceProviderInfo(UserServiceProviderInfoReq req); public int registerUserbyDeviceInfo(UserServiceProviderInfoReq req); public int modifyFavoriteStep1(ModifyFavoriteStep1Req req); public List<CheckHealthVO> getCheckHealthList(UserReq req); public List<CheckJobVO> getCheckJobList(UserReq req); public CheckActivityVO getCheckActivityLevel(UserReq req); public CheckActivityVO getAgeLevel(UserReq req); public void modifyCheckHealth(UserReq req); public void modifyCheckJob(UserReq req); public void modifyCheckActivityLevel(UserReq req); public void modifyAgeLevel(UserReq req); public PageInfoVO getUsersPageInfo(UserReq req); public List<UserSimple> getUsersList(UserReq req); public int updateUser(UserReq userReq); }
f4c442ba88febbaafc9c23428d5e44fcdce66e8c
11b657aa275c210b4513a30f99a33c597d00b63f
/ysf-core/src/main/java/com/xiujing/ysf/core/config/DefaultWebConfig.java
0ada977752a29f2b10e1acdfd3d088de9d943134
[ "Apache-2.0" ]
permissive
burningmyself/ysf
6b23cdbdade9b57f903ca9c9a0e23fc38972ce9f
939995ae4c703026ea1c92cbb420215bf773e41c
refs/heads/master
2022-10-20T19:15:36.536030
2020-03-24T05:49:33
2020-03-24T05:49:33
227,541,325
0
0
NOASSERTION
2022-10-12T20:34:59
2019-12-12T06:59:27
Java
UTF-8
Java
false
false
2,614
java
package com.xiujing.ysf.core.config; import com.xiujing.ysf.core.base.controller.YsfErrorView; import com.xiujing.ysf.core.exception.YsfException; import com.xiujing.ysf.core.exception.YsfExceptionEnum; import com.xiujing.ysf.core.util.DateUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import javax.annotation.PostConstruct; import java.util.Date; import java.util.regex.Pattern; @Configuration public class DefaultWebConfig extends WebMvcConfigurationSupport { @Autowired private RequestMappingHandlerAdapter handlerAdapter; @Bean("error") public YsfErrorView error() { return new YsfErrorView(); } @PostConstruct public void addConversionConfig() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer(); GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new StringToDateConverter()); } public class StringToDateConverter implements Converter<String, Date> { @Override public Date convert(String dateString) { String patternDate = "\\d{4}-\\d{1,2}-\\d{1,2}"; String patternTimeMinutes = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}"; String patternTimeSeconds = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}"; boolean dateFlag = Pattern.matches(patternDate, dateString); boolean timeMinutesFlag = Pattern.matches(patternTimeMinutes, dateString); boolean timeSecondsFlag = Pattern.matches(patternTimeSeconds, dateString); if (dateFlag) { return DateUtil.parseDate(dateString); } else if (timeMinutesFlag) { return DateUtil.parseTimeMinutes(dateString); } else if (timeSecondsFlag) { return DateUtil.parseTime(dateString); } else { throw new YsfException(YsfExceptionEnum.INVLIDE_DATE_STRING); } } } }
3a5c3da3da72e62099d4d26c17a8f9cd7d8c748c
d75cab8bd7630f69c6ff82315284f5c3c21b8cda
/hedera-mirror-importer/src/main/java/com/hedera/mirror/importer/domain/Schedule.java
7715162b4686f276af63bed952acaaf3070de9a1
[ "Apache-2.0" ]
permissive
AP19932404/hedera-mirror-node
038ae438c1f5c4411ee9cf234255fb467a1c9581
26df5ba2692fcc38a1d352edf904e7df6db5f40d
refs/heads/master
2023-05-29T22:24:43.768533
2021-06-09T15:35:00
2021-06-09T15:35:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,767
java
package com.hedera.mirror.importer.domain; /*- * ‌ * Hedera Mirror Node * ​ * Copyright (C) 2019 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.Id; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import com.hedera.mirror.importer.converter.AccountIdConverter; import com.hedera.mirror.importer.converter.EntityIdSerializer; import com.hedera.mirror.importer.converter.ScheduleIdConverter; @Data @Entity @NoArgsConstructor public class Schedule { @Id private Long consensusTimestamp; @Convert(converter = AccountIdConverter.class) @JsonSerialize(using = EntityIdSerializer.class) private EntityId creatorAccountId; private Long executedTimestamp; @Convert(converter = AccountIdConverter.class) @JsonSerialize(using = EntityIdSerializer.class) private EntityId payerAccountId; @Convert(converter = ScheduleIdConverter.class) @JsonSerialize(using = EntityIdSerializer.class) private EntityId scheduleId; @ToString.Exclude private byte[] transactionBody; }
c9554380586218431d2390fbc4dc38e7e20e5d3f
5328a351fb532065075eff48f8a8111f6659be45
/src/test/java/main/mainTest.java
753b429b3a0d1dcd09e3594a1ac6157b8533a2f9
[]
no_license
zhangxiaozhe8023/ZheInter
87a12c7d8ee91eceb619855ea7364f6199742d59
6c51663d4a85b4aa7fec2e0728b11b9e8534762d
refs/heads/master
2020-04-22T15:21:12.035765
2019-02-13T09:04:57
2019-02-13T09:04:57
170,474,751
0
0
null
null
null
null
UTF-8
Java
false
false
3,712
java
package main; import com.alibaba.fastjson.JSONObject; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.response.ResponseBody; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class mainTest{ private String Keywor22; private String response1; //参数1:接口传入参数 参数2:传入URL 参数3:请求方式 参数4:返回结果 public void sendPost( Map<String, Object> Mapdata, String PostUrl, String ResponType, String ReCode){ //发送post请求 Response response = RestAssured.given() .contentType("application/json") .body(Mapdata) .when().post(PostUrl); //获得body信息 String response1 = response.getBody().asString(); if(response1==null){ throw new RuntimeException("发送请求不正确"); }else{ } //获得JSONObject对象并打印 JSONObject obj = JSONObject.parseObject(response1); System.out.println(obj.toString()); //获取返回值ciphertext字段内容(密文) String responseText = obj.getString("ciphertext"); } //参数1:接口传入参数 参数2:传入URL 参数3:请求方式 参数4:返回结果 @Test public void sendPost2(){ Map<String, String> Mapcookie = new HashMap<String, String>(); //发送post请求 // Response response = RestAssured.given() //// .contentType("application/json") // .formParams("username","18310614641","password","123456a") // .when().post("http://support.ezhixin.com/a/userLogin"); Response response = RestAssured.given() // .contentType("application/json") .formParams("account","15168381330","password","123456") .when().post("https://wsc.wlo.wxfenxiao.com/wlapi/user/loginIndex"); //获得body信息 String response1 = response.getBody().asString(); Mapcookie = response.getCookies(); System.out.println(Mapcookie); if(response1==null){ throw new RuntimeException("发送请求不正确"); }else{ System.out.println(response1); } } public void sendPost3(Map<String, Object> Mapdata, String PostUrl, String loginCookie, String resultKeyword) { Keywor22 = resultKeyword; System.out.println(Keywor22); ResponseBody response = RestAssured.given().cookie("JSESSIONID", loginCookie) .contentType("application/json") .body(Mapdata) .when().post(PostUrl); //获得body信息 response1 = response.asString(); if(response1==null){ throw new RuntimeException("发送请求不正确"); }else{ System.out.println(response1); } //判断result返回值,是否包含关键字 Assert.assertThat(response1, isLinkinStr()); } public Matcher<String> isLinkinStr() { return new BaseMatcher<String>() { public boolean matches(Object item) { if (!(item instanceof String)) { return false; } return ((String) item).contains(Keywor22); } public void describeTo(Description description) { description.appendText("字符串必须包含"+Keywor22+"这个单词。。。"); } }; } }
8cdaecb18612f7512bdc8546d1f0b4104db02e8d
663b012c2a534afc64a9a08d19f25bdc7226d7fb
/library/common/src/main/java/com/yuepointbusiness/common/base/BaseFragment.java
efeac8ac8b94bddeffa50f76994e250acd9f654e
[]
no_license
lylandroid/hui_share
e562f78246b951b79dbaaa0d409581fd62e044cc
82423bcec33b06b0952e158f0384eeeb90827b36
refs/heads/master
2020-07-06T20:20:53.388333
2019-08-27T03:52:41
2019-08-27T03:52:41
203,129,280
1
0
null
null
null
null
UTF-8
Java
false
false
5,286
java
package com.yuepointbusiness.common.base; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.yuepointbusiness.common.R; import com.yuepointbusiness.common.baserx.RxManager; import com.yuepointbusiness.common.commonutils.TUtil; import com.yuepointbusiness.common.commonutils.ToastUitl; import com.yuepointbusiness.common.commonwidget.LoadingDialog; import butterknife.ButterKnife; import butterknife.Unbinder; /** * des:基类fragment * Created by xsf * on 2016.07.12:38 */ /***************使用例子*********************/ //1.mvp模式 //public class SampleFragment extends BaseFragment<NewsChanelPresenter, NewsChannelModel>implements NewsChannelContract.View { // @Override // public int getLayoutId() { // return R.layout.activity_news_channel; // } // // @Override // public void initPresenter() { // mPresenter.setVM(this, mModel); // } // // @Override // public void initView() { // } //} //2.普通模式 //public class SampleFragment extends BaseFragment { // @Override // public int getLayoutResource() { // return R.layout.activity_news_channel; // } // // @Override // public void initPresenter() { // } // // @Override // public void initView() { // } //} public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment { protected View rootView; public T mPresenter; public E mModel; public RxManager mRxManager; private Unbinder unbinder; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) rootView = inflater.inflate(getLayoutResource(), container, false); mRxManager=new RxManager(); unbinder = ButterKnife.bind(this, rootView); mPresenter = TUtil.getT(this, 0); mModel= TUtil.getT(this,1); if(mPresenter!=null){ mPresenter.mContext=this.getActivity(); } initPresenter(); initView(); return rootView; } //获取布局文件 protected abstract int getLayoutResource(); //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通 public abstract void initPresenter(); //初始化view protected abstract void initView(); /** * 通过Class跳转界面 **/ public void startActivity(Class<?> cls) { startActivity(cls, null); } /** * 通过Class跳转界面 **/ public void startActivityForResult(Class<?> cls, int requestCode) { startActivityForResult(cls, null, requestCode); } /** * 含有Bundle通过Class跳转界面 **/ public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) { Intent intent = new Intent(); intent.setClass(getActivity(), cls); if (bundle != null) { intent.putExtras(bundle); } startActivityForResult(intent, requestCode); } /** * 含有Bundle通过Class跳转界面 **/ public void startActivity(Class<?> cls, Bundle bundle) { Intent intent = new Intent(); intent.setClass(getActivity(), cls); if (bundle != null) { intent.putExtras(bundle); } startActivity(intent); } /** * 开启加载进度条 */ public void startProgressDialog() { LoadingDialog.showDialogForLoading(getActivity()); } /** * 开启加载进度条 * * @param msg */ public void startProgressDialog(String msg) { LoadingDialog.showDialogForLoading(getActivity(), msg, true); } /** * 停止加载进度条 */ public void stopProgressDialog() { LoadingDialog.cancelDialogForLoading(); } /** * 短暂显示Toast提示(来自String) **/ public void showShortToast(String text) { ToastUitl.showShort(text); } /** * 短暂显示Toast提示(id) **/ public void showShortToast(int resId) { ToastUitl.showShort(resId); } /** * 长时间显示Toast提示(来自res) **/ public void showLongToast(int resId) { ToastUitl.showLong(resId); } /** * 长时间显示Toast提示(来自String) **/ public void showLongToast(String text) { ToastUitl.showLong(text); } public void showToastWithImg(String text,int res) { ToastUitl.showToastWithImg(text,res); } /** * 网络访问错误提醒 */ public void showNetErrorTip() { ToastUitl.showToastWithImg(getText(R.string.net_error).toString(),R.drawable.ic_wifi_off); } public void showNetErrorTip(String error) { ToastUitl.showToastWithImg(error,R.drawable.ic_wifi_off); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); if (mPresenter != null) mPresenter.onDestroy(); mRxManager.clear(); } }
70d0ce9aacb1621128b40a56bc2254906a3c6ef6
19d34b44b6714b33984208435cd62dc67bac047a
/MineCraft2D/src/dev/project/game/gfx/Text.java
a468d3b549934cd1662941f6072a31d96088ec58
[ "Apache-2.0" ]
permissive
stressedtyagi/MineCraft2D
998755d609d88982b282d45e3bb68184348e921f
1e87c76de1c7a4dfd92cb457e12b94f36060178b
refs/heads/master
2022-02-20T09:01:45.630862
2018-06-07T15:53:13
2018-06-07T15:53:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
526
java
package dev.project.game.gfx; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; public class Text { public static void drawString(Graphics g, String text, int xPos, int yPos, boolean center, Color c, Font font){ g.setColor(c); g.setFont(font); int x = xPos; int y = yPos; if(center){ FontMetrics fm = g.getFontMetrics(font); x = xPos - fm.stringWidth(text) / 2; y = (yPos - fm.getHeight() / 2) + fm.getAscent(); } g.drawString(text, x, y); } }
cf515a3b13a038501b63b73ed5f21032f5bd9952
e93ad1115550ed80872a79e10f18176863c0c330
/conference-java/src/main/java/AppConfig2.java
dfe11411648eb2381bab7d4189c8ca2ba871887f
[]
no_license
jingchen01/SpringProjects
eaea48f5404b2092587aa809d71309cbc0acdb8d
cbe60d67ab07913c7e3b5b2f255319386dc9a2f2
refs/heads/master
2022-12-17T14:05:45.529110
2020-09-18T08:22:40
2020-09-18T08:22:40
296,051,247
0
0
null
null
null
null
UTF-8
Java
false
false
201
java
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan({"com.springdemo"}) public class AppConfig2 { }
efa7901660f53f49e7563e8271ab5a3b586f7bcd
d6cb44318d453eb2b2c13fe41048e22d19564117
/analyticandroid/src/main/java/com/example/analyticandroid/models/DeviceInfoModel.java
ee504dcbeb6fe28027ed3d0f4c437c3884ddcae5
[]
no_license
BashirAltereh/AnalyticSDk
f87b08a910d1eeaeddf0a2f7dc77bb76d6ac379d
7b5ce32f7563fd9aeb708e0e372fdac6039e5352
refs/heads/master
2020-09-22T11:09:08.852540
2019-12-16T09:42:33
2019-12-16T09:42:33
225,169,324
0
0
null
null
null
null
UTF-8
Java
false
false
130
java
package com.example.analyticandroid.models; /** * Created by BashirAltereh on 10/29/2019. */ public class DeviceInfoModel { }
937ebc057872c32d513718c9f1393e1054be1121
6a13bff310a0f81174eaa8eedf55017bbfe9aad1
/minecraft/cartasiane/spells/spells/SpellIndex.java
3db3aae8670c3df927a4e80acfdf08d6c9f71336
[]
no_license
theDoubi125/Client_server
05679152a140b8560e4cf22ecf5cd36991bb89b7
ede42769083ca88f72e5b14f238e443095e9dfe5
refs/heads/master
2020-05-18T11:43:25.268538
2012-08-06T00:47:19
2012-08-06T00:47:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
545
java
package cartasiane.spells.spells; import java.util.HashMap; import java.util.Map; import cartasiane.spells.SpellEffect; public class SpellIndex { private static SpellEffect[] registeredSpells; public static SpellEffect arrow; public static SpellEffect arrowRain; public static SpellEffect getSpell(int id) { return registeredSpells[id]; } static { arrow = new ArrowSpell(); arrowRain = new ArrowRainSpell(); registeredSpells = new SpellEffect[500]; registeredSpells[0] = arrow; registeredSpells[1] = arrowRain; } }
896bcf6421b5616268913e24a0228d41d3765787
11aaed5a9469ebeaaefc179fda02ba1e300e7988
/consumer/src/test/java/cn/boc/consumer/DemoApplicationTests.java
4a470631367117b106d867012dbce54780039647
[]
no_license
freesOcean/spring-cloud
a9a6caf14cc2594fe5938f48de71fdc04d18c61c
66a6831572c43d63e908d8e60f0bac40c13d3167
refs/heads/master
2021-02-10T04:16:03.327118
2020-03-02T11:21:38
2020-03-02T11:21:38
244,351,122
0
0
null
null
null
null
UTF-8
Java
false
false
205
java
package cn.boc.consumer; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DemoApplicationTests { @Test void contextLoads() { } }
be46c0a7c51c5ae07b35ef36242037a2c375a605
0c167564979866d6dbbb89d8d128575b98c5310f
/hadoop_hive/src/com/shengli/tools/Hive2Mysql.java
7c6d27353a3e9e1c65eef7c8bd15ac907e812d8e
[]
no_license
shengli2015/javaArithmetic
58267528f6f270cfbd7870228c71a32fa60d5e84
125cfac65354e60af18a03e2beee03f287be93bc
refs/heads/master
2021-01-17T19:18:25.425478
2016-07-04T12:10:59
2016-07-04T12:10:59
62,559,117
0
0
null
null
null
null
UTF-8
Java
false
false
2,226
java
package com.shengli.tools; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; public class Hive2Mysql { Properties prop = new Properties(); public Hive2Mysql(String propertyName) throws Exception { init(propertyName); } public void init(String propertyName) throws Exception { InputStream stream = new FileInputStream(propertyName); prop.load(stream); } public static void main(String [] args) { try { if(args.length < 1) { System.out.println("please set propertyName"); System.exit(1); } String propertyName = args[0]; Hive2Mysql h2 = new Hive2Mysql(propertyName); System.out.println(h2.prop.get("Hive_sql")); System.out.println(h2.prop.get("Mysql_table")); String Hive_sql = h2.prop.get("Hive_sql").toString(); String Mysql_table = h2.prop.get("Mysql_table").toString(); String mysql_columns = h2.prop.get("mysql_columns").toString(); String mysql_delete = h2.prop.get("mysql_delete").toString(); Connection mysqlCon = MyConnection.getMysqlInstance(); Connection hiveCon = MyConnection.getHiveInstance(); String mysql_sql = "insert into " + Mysql_table + " (" + mysql_columns + ") values ("; Statement stHive = hiveCon.createStatement(); Statement stMysql = mysqlCon.createStatement(); ResultSet rsHive = stHive.executeQuery(Hive_sql); int len = Hive_sql.split("from")[0].split("select")[1].trim().split(",").length; String value = ""; stMysql.execute(mysql_delete); while(rsHive.next()) { for(int i=1;i<=len;i++) { value += "'" + rsHive.getString(i) + "',"; } value = value.substring(0, value.length()-1); mysql_sql = mysql_sql + value + ")"; stMysql.execute(mysql_sql); System.out.println(value); value = ""; mysql_sql = "insert into " + Mysql_table + " (" + mysql_columns + ") values ("; } rsHive.close(); stHive.close(); stMysql.close(); mysqlCon.close(); hiveCon.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1d63ee770ebcb703fff666b5e004737c9d323237
bf3e8c43a4dec5478142e86109428ba315f34141
/demo3/src/main/java/com/Handler5.java
3c3c75b7500751574aa92da878b068da52ecd624
[]
no_license
sheldonfa/disruptor
22a1223331643a8b122681a9aec0498c6e17fa52
1feb5997053f99e5c819f60bbe276d9eecc3221a
refs/heads/master
2021-01-20T15:03:10.528434
2017-05-09T09:11:36
2017-05-09T09:11:36
90,707,781
0
0
null
null
null
null
UTF-8
Java
false
false
550
java
package com; import java.util.UUID; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.WorkHandler; public class Handler5 implements EventHandler<Trade>,WorkHandler<Trade> { @Override public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception { this.onEvent(event); } @Override public void onEvent(Trade event) throws Exception { System.out.println("handler5: get price : " + event.getPrice()); event.setPrice(event.getPrice() + 3.0); } }
ddea65bc0fd2fe08a04349614fc5f56e3a1c5178
6d51a2f5b54c005c022bcf5897d3490dd6c3a576
/src/main/java/gwt/material/design/demo/client/application/roadmap/RoadMapView.java
0cc3ade60b75392685b7d0fd2ef8385f9293bbce
[ "Apache-2.0" ]
permissive
GwtMaterialDesign/gwt-material-demo
9f95a90cb939f0897d7bcebed8dd27e581c0ddcf
ef9ede80abac6e5fed4cbe0ede772eb44f674c71
refs/heads/master
2021-01-24T10:40:22.310022
2019-02-03T00:15:26
2019-02-03T00:15:26
33,317,132
38
75
Apache-2.0
2020-05-26T19:13:43
2015-04-02T15:41:09
Java
UTF-8
Java
false
false
1,139
java
package gwt.material.design.demo.client.application.roadmap; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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. * #L% */ import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.gwtplatform.mvp.client.ViewImpl; import javax.inject.Inject; public class RoadMapView extends ViewImpl implements RoadMapPresenter.MyView { interface Binder extends UiBinder<Widget, RoadMapView> { } @Inject RoadMapView(Binder uiBinder) { initWidget(uiBinder.createAndBindUi(this)); } }
64e136e33757366b51847990611de145429581e1
ba035357514fb46132c781ee3379ccd5628fbc74
/src/TestBST.java
73c551df28df12c05154a7ab75c5db3ba97ff647
[]
no_license
AysenurKan/BinarySearchTreeCodes
e904d86ac460e3789898ec3ecd2675684b313e65
e9de2d7b7629a77f0178dafbaf067c95c6538f2f
refs/heads/master
2020-12-31T04:06:55.245399
2016-05-10T19:29:32
2016-05-10T19:29:32
58,528,966
0
0
null
2016-05-11T08:51:34
2016-05-11T08:51:33
null
UTF-8
Java
false
false
1,807
java
import java.util.Scanner; public class TestBST { public static void main(String[] args) { BST tree = new BST(); int option=0; int number; Scanner s=new Scanner(System.in); do{ System.out.print("\n\nMenu:\n1. Insert Number\n2. Search a number\n3. Delete a number\n4. Display tree as an ordered list" + "\n5. Display Tree (breadthFirstTravelsal)\n6. Display count of nodes\n7. Display height of tree\n8. Display count of leaf nodes\n"+ "9. Exit"); System.out.print("\n\nOption>> "); option=s.nextInt(); switch(option){ case 1: System.out.println("Enter numbers (0 is exit) >> "); number=s.nextInt(); while(number!=0){ tree.insert(number); number=s.nextInt(); } System.out.println(tree.getCount()+" numbers are added"); break; case 2: System.out.print("Enter a number to be seach: "); number=s.nextInt(); if(tree.search(number)) System.out.println("exist"); else System.out.println("not exist"); break; case 3: System.out.println("Enter a number to be deleted: "); number=s.nextInt(); tree.delete(number); System.out.println(number+" is deleted"); break; case 4: System.out.print("Ordered list: "); tree.inorder(); break; case 5: // tree.breadthFirstTravelsal(); break; case 6: System.out.print("# of nodes:"+tree.getCount()); break; case 7: System.out.println("Height: "+tree.getHeight()); break; case 8: System.out.println("# of leaf nodes: "+tree.getNumberofLeaves()); break; case 9: System.out.println("Goodbye my lover :-*"); break; default: System.out.println("Try again!!!"); } }while(option!=9); } }
32bd97e326c83b50ac073e65653a9170c8bd7d59
b38f37cf77e341d84733ea5f8e40a9891350ef2e
/eureka-server/src/test/java/com/xiaobai/eurekaserver/EurekaserverApplicationTests.java
7656b92e124e0d1486f3afc0d7f1b62fa3754319
[]
no_license
3ylh3/spring-cloud
1113cf52b3e75c1a908cfa0bafb4f8a99f14c5b4
9c615081d70326d907fec28877ac3f56040439a9
refs/heads/master
2020-04-25T21:30:06.784831
2019-02-28T09:24:01
2019-02-28T09:24:01
173,081,721
1
0
null
null
null
null
UTF-8
Java
false
false
356
java
package com.xiaobai.eurekaserver; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class EurekaserverApplicationTests { @Test public void contextLoads() { } }
5d97823fe57b7850fef447057b6a91a76c0859f8
e5204cafc0c26d7b46584342725d3867ac6f9684
/src/main/java/com/changyue/shiro/sys/shiro/ShiroRealm.java
b032f1dec08863d7ef6be1c0b0c166715a31e831
[]
no_license
yuanchangyue/ShiroDemo
d52503ac07467d35eb9a6747f5d5f2fe07aa0d6e
f279d1452518c7e5a3df24b05e6a74c8ade74563
refs/heads/master
2022-10-23T06:52:54.034416
2019-12-02T15:33:20
2019-12-02T15:33:20
222,095,942
0
0
null
2022-10-12T20:33:52
2019-11-16T12:27:55
Java
UTF-8
Java
false
false
3,157
java
package com.changyue.shiro.sys.shiro; import com.changyue.shiro.sys.model.User; import com.changyue.shiro.utils.MD5Utils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import java.util.HashSet; import java.util.Set; /** * @program: shirodemo * @description: 自定义realm * @author: 袁阊越 * @create: 2019-11-16 22:04 */ public class ShiroRealm extends AuthorizingRealm { /** * 授权 * 将认证的通过的用户信息和权限信息设置给认证的主体 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //用户的身份信息 String username = principals.getPrimaryPrincipal().toString(); //通过username从数据库获取当前用户的角色 Set<String> rolesNames = new HashSet<>(); rolesNames.add("系统管理员"); rolesNames.add("系统运维"); //从数据库获取当前用户的权限 Set<String> permissionName = new HashSet<>(); permissionName.add("sys:user:create"); permissionName.add("sys:user:update"); permissionName.add("sys:user:list"); permissionName.add("sys:user:delete"); permissionName.add("sys:user:info"); //简单授权的信息,对象的中包含用户的角色和权限信息 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.addRoles(rolesNames); info.addStringPermissions(permissionName); System.out.println("授权..."); return info; } /** * 认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; //1. 获取用户的用户名 String username = token.getUsername(); //2. 获取用户的密码 String password = new String(token.getPassword()); //3. 根据用户名去数据库中查询用户是否存在 //3. 模拟获得用户在数据库的信息 User user = new User("zhangsan", "6d58d495d0517b4e7205346a72e211bc", 0, "f4af64b5c211be990ec6f26feef0f1ff"); //3. 明文加密 password = MD5Utils.md5PrivateSalt(password, user.getPrivateSalt()); if (!user.getUsername().equals(username)) { throw new UnknownAccountException("用户不存在"); } if (!user.getPassword().equals(password)) { throw new CredentialsException("密码错误"); } if (user.getStatus() == 1) { throw new DisabledAccountException("账号被禁用"); } if (user.getStatus() == 2) { throw new LockedAccountException("账号被锁定"); } System.out.println("登录认证..."); return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName()); } }
9b9d567cf3fe243bb61a07e87c766def6cc520bb
043703eaf27a0d5e6f02bf7a9ac03c0ce4b38d04
/subject_systems/Struts2/src/struts-2.3.30/src/xwork-core/src/test/java/com/opensymphony/xwork2/config/providers/XmlConfigurationProviderResultsTest.java
cd3cde02c7d45a89c4470bc061e2dd0d544a1b6d
[]
no_license
MarceloLaser/arcade_console_test_resources
e4fb5ac4a7b2d873aa9d843403569d9260d380e0
31447aabd735514650e6b2d1a3fbaf86e78242fc
refs/heads/master
2020-09-22T08:00:42.216653
2019-12-01T21:51:05
2019-12-01T21:51:05
225,093,382
1
2
null
null
null
null
UTF-8
Java
false
false
129
java
version https://git-lfs.github.com/spec/v1 oid sha256:f850d76232efde234c57b1561bb45543b218cfb1e5008460a45ab7e277ab6e72 size 5375
04ef5a81975dfdbc82b6ea0c54acab5bf9ef0f19
c5e469d9fcd1bdaa897257c01834afbc3f4a9090
/src/main/java/complexpattern/interpreter/OperatorExpression.java
ddbd96af4c8335a911857a0f2efd1d9e03190ad7
[]
no_license
thanhnew2001/AllDesignPatterns
393dffebbb3d7d9ba3ae35947ad28dfef9755fa5
cee3e28c9e6707aba18eb78df3a82f12994b717c
refs/heads/master
2021-07-14T15:48:53.107244
2017-10-19T09:45:50
2017-10-19T09:45:50
107,353,120
0
1
null
null
null
null
UTF-8
Java
false
false
985
java
package complexpattern.interpreter; /** * Created by CoT on 10/17/17. */ public class OperatorExpression implements Expression { private OperatorExpression leftOperand; private OperatorExpression rightOperand; private char operator; public OperatorExpression(OperatorExpression leftOperand, OperatorExpression rightOperand, char operator) { this.leftOperand = leftOperand; this.rightOperand = rightOperand; this.operator = operator; } public int intepret() { switch (operator){ case '+': return leftOperand.intepret() + rightOperand.intepret(); case '-': return leftOperand.intepret() - rightOperand.intepret(); case '*': return leftOperand.intepret() * rightOperand.intepret(); case '/': return leftOperand.intepret() / rightOperand.intepret(); default: return 0; } } }
6112cf918c3f07637e49adfe9a8f6e13a81d7e0a
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/java/dbeaver/2015/4/IGridLabelProvider.java
e0a04ae1907467b76409c21bb79cf43edd30cdad
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
Java
false
false
1,434
java
/* * Copyright (C) 2010-2015 Serge Rieder * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jkiss.dbeaver.ui.controls.lightgrid; import org.eclipse.jface.viewers.IColorProvider; import org.eclipse.jface.viewers.IFontProvider; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.ext.ui.ITooltipProvider; public interface IGridLabelProvider extends IColorProvider, IFontProvider, ITooltipProvider { @NotNull public String getText(Object element); @Nullable public Image getImage(Object element); }
49f9c12368806a42ca8f11994988ab91b74dfc5d
7ef86525fbd9e71f4e5b5302d1ad89afb94f507e
/src/se/bryggmester/Program.java
828dd632bbcee57a24b34a3726e1d0e8bd9f0985
[]
no_license
smasseman/bryggmester
f1e81c529ad97027e0ab6a31a464a7d8691fd8e2
7d5cfbe7dd7e258d9ba9c95fb4cb07cffdcb9f9b
refs/heads/master
2016-09-02T18:59:44.025264
2013-09-16T07:21:14
2013-09-16T07:21:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,239
java
package se.bryggmester; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import se.bryggmester.instruction.Instruction; /** * @author [email protected] */ public class Program { private static class KeyAndValue { String key; String value; private KeyAndValue(String key, String value) { super(); this.key = key; this.value = value; } } public static final Comparator<? super Program> NAME_COMPARATOR = new Comparator<Program>() { @Override public int compare(Program o1, Program o2) { return o1.name.compareTo(o2.name); } }; private List<Instruction> instructions = new ArrayList<>(); private String name; private Long id; public List<Instruction> getInstructions() { return instructions; } public void setInstructions(List<Instruction> instructions) { this.instructions = instructions; } public static Program parse(File f) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(f)); Program p = new Program(); parseProperties(p, reader); parseInstructions(p, reader); reader.close(); return p; } private static void parseProperties(Program p, BufferedReader reader) throws IOException { String line; String name = null; Long id = null; while ((line = reader.readLine()) != null) { line = trim(line); if (line == null) { // Ignore } else if ("-".equals(line)) { if (name == null) throw new IllegalArgumentException( "Missing name in program properties."); p.setName(name); if (id == null) throw new IllegalArgumentException( "Missing id in program properties."); p.setId(id); return; } else { KeyAndValue kv = createKeyAndValue(line); if (kv.key.equals("name")) { name = kv.value; } else if (kv.key.equals("id")) { try { id = new Long(kv.value); } catch (Exception e) { throw new IllegalArgumentException("Invalid id (" + kv.value + ") in program properties. " + e.getMessage()); } } } } } private static KeyAndValue createKeyAndValue(String line) { int index = line.indexOf('='); if (index < 0) throw new IllegalArgumentException("Line " + line + " does not contain a = char."); return new KeyAndValue(line.substring(0, index), line.substring(index + 1)); } private static void parseInstructions(Program p, BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = trim(line); if (line != null) { p.getInstructions().add(Instruction.parse(line)); } } } private static String trim(String line) { line = line.trim(); if (line.length() == 0) { // Ignore empy lines. return null; } else if (line.startsWith("#")) { // Ignore comments return null; } else { return line; } } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Program other = (Program) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "[id=" + id + ", name=" + name + "]"; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String export() { StringBuilder s = new StringBuilder(); writeKeyAndValue(s, "id", id.toString()); writeKeyAndValue(s, "name", name); s.append("-\n"); for (Instruction i : instructions) { s.append(i.getType().name() + " " + i.getType().export(i)).append( "\n"); } return s.toString(); } private void writeKeyAndValue(StringBuilder s, String name, String value) { s.append(name).append("=").append(value).append("\n"); } }
e92841b5ef67a27aab557b2ea10b7b6c7d5c5344
4b756398e4a884714feeab8a6926df8880475e31
/CalculatriceAOO/src/calculatriceaoo/App.java
fff8a2691164ea237e633d6ef6b59ba113bb12c6
[]
no_license
ThomatoKetchup/NetBeansProjects
035f4b07863b2c3310147f2e9a5c0de7d1ead189
b51e801add69090f8f13f6fce1f59c6d38d32cc0
refs/heads/master
2021-04-06T08:49:02.059510
2018-03-11T15:22:42
2018-03-11T15:22:42
124,767,382
0
0
null
null
null
null
UTF-8
Java
false
false
1,301
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package calculatriceaoo; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class App extends Application { private Calculatrice c; public App() { c = new Calculatrice(); try { c.addOperation("+", new Addition()); c.addOperation("-", new Soustraction()); c.addOperation("/", new Division()); //Il faut necessairement que Division implément opération, sinon il ne peut pas $etre de type operation c.addOperation("*", new Multiplication()); } catch (ExceptionOperationExistante e) { } } @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("UI.fxml")); //"la vue est dans le UI Fxml, on la charge avec get resource primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
f84b6a6e1cab0e67a69c3e4437178a9c345a74b9
22d50fc24864b6a08bf96ad259fd143982505007
/app/src/main/java/com/snail/iweibo/util/Configuration.java
3bebd8393d9b8e9dc7ae2cfe8bf372aebc2f08ed
[]
no_license
wangwei1121/iweibo
75992091743ba8ed7c7aae2cc33cc657316847c8
ee3c51b739ca1b9c0a8fd8ddf3b8ea3caa9ce673
refs/heads/master
2021-01-21T04:59:24.909007
2016-05-16T15:39:09
2016-05-16T15:39:09
50,438,301
1
2
null
2016-01-29T01:38:51
2016-01-26T15:33:22
Java
UTF-8
Java
false
false
257
java
package com.snail.iweibo.util; /** * Configuration App环境配置 * Created by alexwan on 16/1/30. */ public class Configuration { public static final boolean DEBUG = true; public static final String WEIBO_BASE_URL = "https://api.weibo.com/"; }
6c466df36e53fafadab3ec4af9d3521ce25a3c15
538bba9b8c621993a5d45636ecc2b3860a5e9b2d
/src/main/java/com/zhk/controller/ResourceController.java
3c142da34cfeb6909775ff634e0da393f5ad2a62
[]
no_license
EHENJOOM/online-course-server
13235edc450a751253f38735f2c027a5f4f48fc5
b8df3d4f2aa37d842ebb161d02715f40b4ff400b
refs/heads/master
2022-12-12T06:12:44.875194
2020-08-27T06:52:04
2020-08-27T06:52:04
284,223,317
0
0
null
null
null
null
UTF-8
Java
false
false
1,174
java
package com.zhk.controller; import com.zhk.entity.vo.CommonResultVo; import com.zhk.service.ResourceService; import com.zhk.util.ResultUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.Map; /** * @author 赵洪苛 * @date 2020/8/22 16:25 * @description 资源控制层 */ @Slf4j @RestController public class ResourceController { @Resource private ResourceService resourceService; @GetMapping("/resource/{courseId}") public CommonResultVo getResource(@PathVariable("courseId") Integer courseId) { LinkedHashMap resource = resourceService.getResource(courseId); log.info("根据courseId和teacherId查询资源列表:{}", resource); return ResultUtil.success(resource); } @PostMapping("/resource") public CommonResultVo addResource(@RequestBody Map map) { log.info("添加资源:{}", map.get("resourceVo")); resourceService.saveResource((Map) map.get("resourceVo"), Integer.valueOf((String) map.get("courseId"))); return ResultUtil.success("成功!"); } }
6e9c73c4035f5d3c7edbbdcedee4b1cabdc15604
8a3061ef1d175ac0a8bce621186c3258e9dd6eca
/src/main/java/algorithm/chapter_2_listproblem/Problem_03_RemoveNodeByRatio.java
96657ee7b4b32364dc627273a821558c03acdaeb
[]
no_license
hugo980521/Algorithm
cc0c2a5bc730922713192104ca23dcb9407f42f7
767903fa25c106b0b9c32862a30638e820f869e1
refs/heads/master
2022-12-27T22:44:58.263668
2019-09-03T10:04:59
2019-09-03T10:04:59
203,977,881
0
0
null
2022-12-16T00:47:32
2019-08-23T10:30:59
Java
UTF-8
Java
false
false
1,660
java
package algorithm.chapter_2_listproblem; public class Problem_03_RemoveNodeByRatio { public static class Node { public int value; public Node next; public Node(int data) { this.value = data; } } public static Node removeMidNode(Node head) { if (head == null || head.next == null) { return head; } if (head.next.next == null) { return head.next; } Node pre = head; Node cur = head.next.next; while (cur.next != null && cur.next.next != null) { pre = pre.next; cur = cur.next.next; } pre.next = pre.next.next; return head; } public static Node removeByRatio(Node head, int a, int b) { if (a < 1 || a > b) { return head; } int n = 0; Node cur = head; while (cur != null) { n++; cur = cur.next; } n = (int) Math.ceil(((double) (a * n)) / (double) b); if (n == 1) { head = head.next; } if (n > 1) { cur = head; while (--n != 1) { cur = cur.next; } cur.next = cur.next.next; } return head; } public static void printLinkedList(Node head) { System.out.print("Linked List: "); while (head != null) { System.out.print(head.value + " "); head = head.next; } System.out.println(); } public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); head.next.next.next.next.next = new Node(6); printLinkedList(head); head = removeMidNode(head); printLinkedList(head); head = removeByRatio(head, 2, 5); printLinkedList(head); head = removeByRatio(head, 1, 3); printLinkedList(head); } }
a0cf13b1d6559b607baf703422022c7d222e9ffd
4379ab0e4c4590c1b7044f713e633354bbe6de44
/spring-ssm/src/main/java/com/shy/ssm/bean/User.java
e1da596dfd4be7a0abfbba95b191caafc3317ecd
[ "Apache-2.0" ]
permissive
shihaoyan/spring5.0.x
7f85a56114b09b02ed627eb4cbebd8dc207c6011
cb545787e97364295ae5f6bae40f3c9b3e653d0f
refs/heads/master
2022-04-24T14:35:51.766345
2020-04-20T11:31:51
2020-04-20T11:31:51
257,198,593
1
0
null
null
null
null
UTF-8
Java
false
false
707
java
package com.shy.ssm.bean; /** * @author 石皓岩 * @create 2020-03-01 19:43 * 描述: */ public class User { private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(Integer id, String username, String password) { this.id = id; this.username = username; this.password = password; } public User() { } }
490d5c785d73039cbc1b8df18e98b84e65fe7baa
43890d58dd7790f9a3cda48964cf0af554a58d19
/src/br/com/softblue/loucademia/domain/aluno/EstadoRepository.java
f6a61886a7f663ecb592a2e09ea253815687cbac
[]
no_license
wsnino/Locademia
113a020f1fd5fdaea9577806fd16e06d071c3172
b50d5b4eb9ef458cd06dd25220ac94485b8bf062
refs/heads/master
2023-03-21T23:53:58.132259
2021-03-21T16:32:10
2021-03-21T16:32:10
347,661,085
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
package br.com.softblue.loucademia.domain.aluno; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class EstadoRepository { @PersistenceContext private EntityManager em; public List<Estado> listEstados() { return em.createQuery("SELECT e FROM Estado e ORDER BY e.nome", Estado.class).getResultList(); } }
fa8b800ebb9506dd2886fad7926963d7b7d2a504
99d41187e30161c81eeece70f8fb43ff1071d0ab
/src/test/java/logic/ItemLogicTest.java
c7db0bf854b759e2e639721609c0dc2886747925
[]
no_license
li000611/Kijiji_Project
9bfe514856417814ffba34981224281b2ded17aa
5c8ac0edab1644cc8dc2bc379b2593d1c463c268
refs/heads/master
2022-11-03T10:59:10.421397
2020-05-18T01:41:56
2020-05-18T01:41:56
243,583,012
0
0
null
2022-09-01T23:23:10
2020-02-27T18:03:30
Java
UTF-8
Java
false
false
10,513
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package logic; import common.TomcatStartUp; import entity.Item; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * * @author Min Li */ public class ItemLogicTest { private ItemLogic logic; private Map<String, String[]> sampleMap; @BeforeAll final static void setUpBeforeClass() throws Exception { TomcatStartUp.createTomcat(); } @AfterAll final static void tearDownAfterClass() throws Exception { TomcatStartUp.stopAndDestroyTomcat(); } @BeforeEach final void setUp() throws Exception { logic = new ItemLogic(); /*HashMap implements interface Map. Map is generic, it has two parameters, first is the Key (in our case String) and second is Value (in our case String[])*/ sampleMap = new HashMap<>(); /*Map stores date based on the idea of dictionaries. Each value is associated with a key. Key can be used to get a value very quickly*/ sampleMap.put(ItemLogic.PRICE, new String[]{"5"}); /*Map::put is used to store a key and a value inside of a map and Map::get is used to retrieve a value using a key.*/ sampleMap.put(ItemLogic.TITLE, new String[]{"junit"}); /*In this case we are using static values stored in ItemLogic which represent general names for Item Columns in DB to store values in Map*/ sampleMap.put(ItemLogic.DATE, new String[]{"02/02/2020"}); sampleMap.put(ItemLogic.URL, new String[]{"www.junit5.com"}); sampleMap.put(ItemLogic.LOCATION, new String[]{"Ottawa"}); sampleMap.put(ItemLogic.DESCRIPTION, new String[]{"large, square"}); sampleMap.put(ItemLogic.CATEGORY_ID, new String[]{"3"}); sampleMap.put(ItemLogic.IMAGE_ID, new String[]{"3"}); sampleMap.put(ItemLogic.ID, new String[]{"4"}); /*This item has Price: " 5", Title: "junit", Date: "2020,02,02", Location:"Ottawa", Description:"large, square", Category:"furniture"*/ } @AfterEach final void tearDown() throws Exception { } @Test final void testGetAll() { //get all the items from the DB List<Item> list = logic.getAll(); //store the size of list/ this way we know how many items exits in DB int originalSize = list.size(); //create a new Item and save it so we can delete later Item testItem = logic.createEntity(sampleMap); testItem.setCategory(new CategoryLogic().getWithId(1)); testItem.setImage(new ImageLogic().getWithId(1)); //add the newly created item to DB logic.add(testItem); //get all the items again list = logic.getAll(); //the new size of items must be 1 larger than original size assertEquals(originalSize + 1, list.size()); //delete the new item, so DB is reverted back to it original form logic.delete(testItem); //get all items again list = logic.getAll(); //the new size of items must be same as original size assertEquals(originalSize, list.size()); } @Test final void testGetWithId() { //get all items List<Item> list = logic.getAll(); //use the first item in the list as test item Item testItem = list.get(0); //using the id of test item get another item from logic Item returnedItem = logic.getWithId(testItem.getId()); //the two items (testItem and returnedItem) must be the same //assert all field to guarantee they are the same assertEquals(testItem.getId(), returnedItem.getId()); assertEquals(testItem.getUrl(), returnedItem.getUrl()); assertEquals(testItem.getPrice(), returnedItem.getPrice()); assertEquals(testItem.getTitle(), returnedItem.getTitle()); assertEquals(testItem.getLocation(), returnedItem.getLocation()); assertEquals(testItem.getDescription(), returnedItem.getDescription()); } @Test final void testGetWithPrice() { List<Item> list = logic.getAll(); Item testItem = list.get(0); List<Item> returnedItems = logic.getWithPrice(testItem.getPrice()); for (Item item : returnedItems) { assertEquals(testItem.getId(), item.getId()); assertEquals(testItem.getUrl(), item.getUrl()); assertEquals(testItem.getPrice(), item.getPrice()); assertEquals(testItem.getTitle(), item.getTitle()); assertEquals(testItem.getLocation(), item.getLocation()); assertEquals(testItem.getDescription(), item.getDescription()); } } @Test final void testGetWithTitle() { List<Item> list = logic.getAll(); Item testItem = list.get(0); List<Item> returnedItems = logic.getWithTitle(testItem.getTitle()); for (Item item : returnedItems) { assertEquals(testItem.getId(), item.getId()); assertEquals(testItem.getUrl(), item.getUrl()); assertEquals(testItem.getPrice(), item.getPrice()); assertEquals(testItem.getTitle(), item.getTitle()); assertEquals(testItem.getLocation(), item.getLocation()); assertEquals(testItem.getDescription(), item.getDescription()); } } @Test final void testGetWithLocation() { List<Item> list = logic.getAll(); Item testItem = list.get(0); List<Item> returnedItems = logic.getWithLocation(testItem.getLocation()); for (Item item : returnedItems) { assertEquals(testItem.getId(), item.getId()); assertEquals(testItem.getUrl(), item.getUrl()); assertEquals(testItem.getPrice(), item.getPrice()); assertEquals(testItem.getTitle(), item.getTitle()); assertEquals(testItem.getLocation(), item.getLocation()); assertEquals(testItem.getDescription(), item.getDescription()); } } @Test final void testGetWithDescription() { List<Item> list = logic.getAll(); Item testItem = list.get(0); List<Item> returnedItems = logic.getWithDescription(testItem.getDescription()); for (Item item : returnedItems) { assertEquals(testItem.getId(), item.getId()); assertEquals(testItem.getUrl(), item.getUrl()); assertEquals(testItem.getPrice(), item.getPrice()); assertEquals(testItem.getTitle(), item.getTitle()); assertEquals(testItem.getLocation(), item.getLocation()); assertEquals(testItem.getDescription(), item.getDescription()); } } @Test final void testGetWithUrl() { List<Item> list = logic.getAll(); Item testItem = list.get(0); Item returnedItem = logic.getWithUrl(testItem.getUrl()); assertEquals(testItem.getId(), returnedItem.getId()); assertEquals(testItem.getUrl(), returnedItem.getUrl()); assertEquals(testItem.getPrice(), returnedItem.getPrice()); assertEquals(testItem.getTitle(), returnedItem.getTitle()); assertEquals(testItem.getLocation(), returnedItem.getLocation()); assertEquals(testItem.getDescription(), returnedItem.getDescription()); } @Test final void testGetWithCategory() { List<Item> list = logic.getAll(); Item testItem = list.get(0); List<Item> returnedItems = logic.getWithCategory(testItem.getCategory().getId()); for(Item items: returnedItems){ assertEquals(testItem.getCategory(), items.getCategory()); } } @Test final void testCreateEntity() { Item testItem = logic.createEntity(sampleMap); testItem.setCategory(new CategoryLogic().getWithId(1)); testItem.setImage(new ImageLogic().getWithId(1)); logic.add(testItem); Item item = logic.getWithId(testItem.getId()); assertEquals(testItem.getId(), item.getId()); assertEquals(testItem.getUrl(), item.getUrl()); assertEquals(testItem.getPrice().compareTo( item.getPrice()),0); assertEquals(testItem.getTitle(), item.getTitle()); assertEquals(testItem.getLocation(), item.getLocation()); assertEquals(testItem.getDescription(), item.getDescription()); assertEquals(testItem.getCategory(), item.getCategory()); assertEquals(testItem.getImage(), item.getImage()); logic.delete(testItem); } @Test final void testSearch() { List<Item> list = logic.getAll(); Item testItem = list.get(0); String search = testItem.getTitle(); List<Item> returned = logic.search(search); returned.forEach((item) -> { Assertions.assertTrue(item.getUrl().contains(search) || item.getTitle().contains(search) || item.getLocation().contains(search) || item.getDescription().contains(search)); }); } @Test final void testGetColumnNames() { List<String> list = logic.getColumnNames(); List<?> hardCodedList = Arrays.asList("ID", "URL", "DATE", "TITLE", "PRICE", "LOCATION", "IMAGE_ID", "CATEGORY_ID", "DESCRIPTION"); assertIterableEquals(list, hardCodedList); } @Test final void testGetColumnCodes() { List<String> list = logic.getColumnCodes(); List<?> hardCodedList = Arrays.asList(ItemLogic.ID, ItemLogic.URL, ItemLogic.DATE, ItemLogic.TITLE, ItemLogic.PRICE, ItemLogic.LOCATION, ItemLogic.IMAGE_ID, ItemLogic.CATEGORY_ID, ItemLogic.DESCRIPTION); assertIterableEquals(list, hardCodedList); } @Test final void testExtraDataAsList() { List<Item> items = logic.getAll(); Item testIt = items.get(0); Item returnedIt = logic.getWithId(testIt.getId()); List<?> testItData = logic.extractDataAsList(testIt); List<?> returnedItData = logic.extractDataAsList(returnedIt); assertIterableEquals(testItData, returnedItData); } }
2bfec0fc21f20e499284031db6b3b4d4dd9c51ac
7b808da40d2ca0e7b410072e21b8bd8f4667daef
/q/c/submissions/Pheonix/problem2.java
4a347c3efdaf332272a85c4943976139a49a4f8e
[]
no_license
nishant1408/Code-Judge
29bf3a1a2b8684d784c613866f27ad9a3d665911
c4da0ad83b5ddf79388369f80739735087f4d884
refs/heads/master
2020-04-13T04:57:42.993969
2018-12-25T10:32:23
2018-12-25T10:32:23
162,976,535
0
0
null
null
null
null
UTF-8
Java
false
false
287
java
import java.util.Scanner; public class problem2{ public static void main(String args[]) { Scanner sc=new Scanner(System.in); String s=sc.nextLine(); int l,i,j,c=0; String rev=""; l=s.length(); j=s.indexOf(" "); System.out.println(s.charAt(0)+"."+" "+s.substring(j+1,l)); } }
f4c582981c648a2dd10c452227c3acce08bfa319
c3b50309325790c2048938dc89b6a85b347a58f3
/src/com/smlib/activity/ShellSplashActivity.java
0785e8ac925164de9679854c3d02e64f378f228a
[]
no_license
audacelin/SMLib
76e0e5e2d95896c1efb9cad9d6b06c6e0ac7d93a
9827e0c36a21288825cc9c68c5901462c25085cf
refs/heads/master
2021-01-01T19:04:44.726138
2017-07-27T06:32:14
2017-07-27T06:32:14
98,501,687
0
0
null
null
null
null
GB18030
Java
false
false
3,216
java
package com.smlib.activity; import com.smlib.R; import com.smlib.bussiness.ShellContextParamsModule; import com.smlib.bussiness.ShellSPConfigModule; import com.smlib.bussiness.ShellSPConfigModule.CustSP; import com.smlib.utils.AndroidUtils; import com.smlib.utils.StringUtils; import com.smlib.utils.SystemBarTintManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; public class ShellSplashActivity extends TraceActivity{ private TextView tv_indicator,tv_appVersion,tv_appName; private final long SPLASH_WAITING=1000; private ShellContextParamsModule shellContextParamsModule=ShellContextParamsModule.getInstance(); private ShellSPConfigModule spConfigModule=ShellSPConfigModule.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub Log.e("ShellSplashActivity", "test"); super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // setTranslucentStatus(true); // SystemBarTintManager tintManager = new SystemBarTintManager(this); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintResource(R.color.barcolor);//通知栏所需颜色 // } setContentView(R.layout.shell_splash_activity); init(); } private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } public void init(){ initUI(); //检查是否存在登录的用户 tryLogin(); } public void initUI(){ tv_indicator=(TextView)this.findViewById(R.id.idStartIndicator); tv_appVersion=(TextView)this.findViewById(R.id.app_version_tv); tv_appName=(TextView)this.findViewById(R.id.app_name_tv); tv_appName.setText(AndroidUtils.s(R.string.app_name)); tv_appVersion.setText("V"+AndroidUtils.System.getVersionName()); } private void tryLogin(){ if(canAutoLogin()){ //满足自动登录条件 Login(); return; } new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try{ Thread.sleep(SPLASH_WAITING); }catch(InterruptedException ex){ ex.printStackTrace(); } goToLogin(); } }).start();; } private boolean canAutoLogin(){ if(!spConfigModule.isAutoLogin(shellContextParamsModule.getCurCustNo())) return false; CustSP custSP=spConfigModule.getLastestCustSP(); if(custSP==null) return false; if(StringUtils.isBlank(custSP.custNo)) return false; return true; } //跳转登录界面 protected void goToLogin(){ } //自动登录 protected void Login(){ // } }
4bcdc0cdbe50df2806ac0b00f82666d4e7bde165
0ac11d1079c4e9d4e8fe4aefd8dfd8c9050851af
/src/PhoneTicket/PhoneTicket.Android/test/activities/DetailMovieTest.java
0e9c553b0433ac7c4be0e5fa750af6693c9abf01
[]
no_license
dschenkelman/a-malazan-wolvering
7018ef15f9760e2e46b322c5aeb43663855cb8e7
6a0d61ca30acdf230d62c938cae2230d6aea3a98
refs/heads/master
2020-06-08T15:14:29.052607
2013-11-26T13:08:57
2013-11-26T13:08:57
32,240,297
0
0
null
null
null
null
UTF-8
Java
false
false
6,331
java
package activities; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import junit.framework.Assert; import module.TestModule; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.shadows.ShadowActivity; import org.robolectric.shadows.ShadowIntent; import org.robolectric.shadows.ShadowPreferenceManager; import phoneticket.android.R; import phoneticket.android.activities.LoginActivity; import phoneticket.android.activities.MasterActivity; import phoneticket.android.activities.fragments.DetailCinemaFragment; import phoneticket.android.activities.fragments.DetailMovieFragment; import phoneticket.android.activities.fragments.RoomFragment; import phoneticket.android.services.get.IRetrieveCinemaInfoService; import phoneticket.android.services.get.IRetrieveMovieFunctionsService; import phoneticket.android.services.get.IRetrieveMovieInfoService; import phoneticket.android.services.get.IRetrieveMovieListService; import phoneticket.android.services.get.IRetrieveRoomInfoService; import phoneticket.android.services.get.mock.MockRetrieveMovieFunctionsService; import phoneticket.android.services.get.mock.MockRetrieveMovieInfoService; import phoneticket.android.utils.UserManager; import android.content.ComponentName; import android.content.Intent; import android.content.SharedPreferences; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; @RunWith(RobolectricTestRunner.class) public class DetailMovieTest { @Mock private IRetrieveMovieInfoService retrieveMovieInfoService; @Mock private IRetrieveMovieFunctionsService movieFunctionsService; @Mock private IRetrieveMovieListService iRetrieveMovieListService; @Mock private IRetrieveCinemaInfoService iRetrieveCinemaInfoService; @Mock private IRetrieveRoomInfoService roomInfoService; private DetailMovieFragment fragment; private MasterActivity activity; private int movieId; private Button watchTrailerButton; @Before public void setUp() { MockitoAnnotations.initMocks(this); TestModule module = new TestModule(); module.addBinding(IRetrieveMovieInfoService.class, retrieveMovieInfoService); module.addBinding(IRetrieveMovieFunctionsService.class, movieFunctionsService); module.addBinding(IRetrieveMovieListService.class, iRetrieveMovieListService); module.addBinding(IRetrieveCinemaInfoService.class, iRetrieveCinemaInfoService); module.addBinding(IRetrieveRoomInfoService.class, roomInfoService); TestModule.setUp(this, module); activity = Robolectric.buildActivity(MasterActivity.class).create() .resume().get(); movieId = 0; activity.onMovielistItemSelected(movieId, "Titulo"); fragment = (DetailMovieFragment) activity.getSupportFragmentManager() .findFragmentById(R.id.fragment_container); watchTrailerButton = (Button) fragment.getView().findViewById( R.id.watchTrailerButton); SharedPreferences sharedPreferences = ShadowPreferenceManager .getDefaultSharedPreferences(Robolectric.application .getApplicationContext()); UserManager.initialize(sharedPreferences); } @Test public void detailMovieActivityCallRetrieveMovieFunctionsServiceOnCreate() { Mockito.verify(movieFunctionsService, Mockito.times(1)) .retrieveMovieFunctions(fragment, movieId); } @Test public void detailMovieActivityCallRetrieveMovieInfoServiceOnCreate() { Mockito.verify(retrieveMovieInfoService, Mockito.times(1)) .retrieveMovieInfo(fragment, movieId); } @Test public void actionViewIntentOnWatchTrailer() { new MockRetrieveMovieInfoService().retrieveMovieInfo(fragment, 0); watchTrailerButton.performClick(); ShadowActivity shadowActivity = Robolectric.shadowOf(activity); Intent intent = shadowActivity.getNextStartedActivity(); assertNotNull(intent); ShadowIntent shadowIntent = Robolectric.shadowOf(intent); assertThat(shadowIntent.getAction(), equalTo(Intent.ACTION_VIEW)); } @Test public void detailMovieChangeToDetailCinemaFragmentOnItemClick() { new MockRetrieveMovieFunctionsService().retrieveMovieFunctions( fragment, movieId); ImageButton button = (ImageButton) fragment.getView().findViewById( R.id.goToCinema); button.performClick(); Assert.assertEquals( DetailCinemaFragment.class.getCanonicalName(), activity.getSupportFragmentManager() .findFragmentById(R.id.fragment_container).getClass() .getCanonicalName()); } @Test public void detailMovieChangeCallLoginActivityWhenNotLogIn() { new MockRetrieveMovieInfoService().retrieveMovieInfo(fragment, 0); new MockRetrieveMovieFunctionsService().retrieveMovieFunctions( fragment, movieId); LinearLayout button = (LinearLayout) fragment.getView().findViewById( R.id.timeLinearLayout); TextView v = (TextView) button.getChildAt(0); v.performClick(); ShadowActivity shadowActivity = Robolectric.shadowOf(activity); Intent intent = shadowActivity.getNextStartedActivity(); ComponentName c = intent.getComponent(); String call = c.getClassName(); assertNotNull(intent); Assert.assertEquals(LoginActivity.class.getName(), call); } @Test public void detailMovieChangeChangeFragmentOnLoginIn() { new MockRetrieveMovieInfoService().retrieveMovieInfo(fragment, 0); new MockRetrieveMovieFunctionsService().retrieveMovieFunctions( fragment, movieId); LinearLayout button = (LinearLayout) fragment.getView().findViewById( R.id.timeLinearLayout); UserManager.getInstance().setCredentials("pepe", "pepe"); UserManager.getInstance().loginUserWithId(0, true); TextView v = (TextView) button.getChildAt(0); v.performClick(); Assert.assertEquals( RoomFragment.class.getCanonicalName(), activity.getSupportFragmentManager() .findFragmentById(R.id.fragment_container).getClass() .getCanonicalName()); } }
[ "gdfesta@2a5ade1e-0ce3-53c1-387a-2b2623bf7fdd" ]
gdfesta@2a5ade1e-0ce3-53c1-387a-2b2623bf7fdd
30d30245c89617137dc64e782d60f4d1816e1f3e
0bf55802ab1869ad0798d7d5851e1fa31be2ae54
/src/Strategy/Use_a_cabeca_Livro/DUCK/comportamentos/FlyWithWings.java
b57d0a7324467152e96f724b8da4f74348d72b02
[]
no_license
loressl/Padroes_de_Projeto
8159105c3a6132f2f541a6874b96b96b792c3a24
72644a731436699c309f82cacf74f35f15da5276
refs/heads/master
2020-05-18T14:56:01.731636
2019-10-17T05:10:53
2019-10-17T05:10:53
184,483,652
4
0
null
null
null
null
UTF-8
Java
false
false
251
java
package Strategy.Use_a_cabeca_Livro.DUCK.comportamentos; import Strategy.Use_a_cabeca_Livro.DUCK.Interface.FlyBehavior; public class FlyWithWings implements FlyBehavior{ @Override public void fly() { System.out.println("I'm flying!!"); } }
e9b188f19fcac02f99650184be91cc8de6e056c0
ada50c9a1da83bb480124c2f23504f7c3f8d59ca
/src/main/java/com/example/SmartHouseLite/RequestController.java
957ab28fc464ed357f148813550095ddc554f26c
[]
no_license
ffSaschaGff/SmartHouseLite
5a210712fbae4b006e36f926b15ff9126e84130b
1b81a536b22dc6c4257761642517cdbbedeb5e6a
refs/heads/master
2020-03-27T20:57:59.348150
2018-09-30T06:10:44
2018-09-30T06:10:44
147,106,407
0
0
null
null
null
null
UTF-8
Java
false
false
9,711
java
package com.example.SmartHouseLite; import com.example.SmartHouseLite.domain.Alarm; import com.example.SmartHouseLite.domain.RemoteArduino; import com.example.SmartHouseLite.domain.RemoteSonoff; import com.example.SmartHouseLite.domain.TempSensorValue; import com.example.SmartHouseLite.repossitory.AlarmRepository; import com.example.SmartHouseLite.repossitory.RemoteArduinoRepository; import com.example.SmartHouseLite.repossitory.RemoteSonoffRepository; import com.example.SmartHouseLite.repossitory.TempSensorValueRepository; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.util.JSONPObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Optional; @Controller public class RequestController { @Autowired private RemoteArduinoRepository remoteArduinoRepository; @Autowired private RemoteSonoffRepository remoteSonoffRepository; @Autowired private AlarmRepository alarmRepository; @Autowired private TempSensorValueRepository tempSensorValueRepository; @GetMapping("index") public String index(Map<String, Object> model) { Iterable<Alarm> alarms = alarmRepository.findAll(); model.put("hour", ""); model.put("minute", ""); model.put("alarmIsCheced",""); for (Alarm alarm: alarms) { model.put("hour", alarm.getHour()); model.put("minute", alarm.getMinute()); model.put("alarmIsCheced", alarm.getEnabled() ? "checked": ""); } Iterable<TempSensorValue> temps = tempSensorValueRepository.getFirstByDate(); model.put("tempeture", ""); model.put("pressure", ""); model.put("humidity", ""); for (TempSensorValue tempSensorValue: temps) { model.put("tempeture", tempSensorValue.getTempeture()); model.put("pressure", tempSensorValue.getPressure()); model.put("humidity", tempSensorValue.getHumidity()); } Iterable<RemoteArduino> arduinos = remoteArduinoRepository.findAll(); model.put("arduinos", arduinos); Iterable<RemoteSonoff> sonoffs = remoteSonoffRepository.findAll(); model.put("sonoffs", sonoffs); Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); model.put("currentTime",format.format(date)); return "index"; } @GetMapping("editSwitch") public String editRemoteGet(Map<String, Object> model) { model.put("name", ""); model.put("address", ""); model.put("id", "null"); Iterable<RemoteArduino> arduinos = remoteArduinoRepository.findAll(); model.put("arduinos", arduinos); return "editSwitch"; } @PostMapping("editSwitch") public String editRemotePost(@RequestParam(value = "id", defaultValue = "null") String id, Map<String, Object> model) { if (!id.equals("null")) { Optional<RemoteArduino> arduinos = remoteArduinoRepository.findById(Integer.parseInt(id)); if (arduinos.isPresent()) { model.put("name", arduinos.get().getName()); model.put("address", arduinos.get().getAdress()); } } if (!model.containsKey("name") || !model.containsKey("address")) { model.put("name", ""); model.put("address", ""); } model.put("id", id); Iterable<RemoteArduino> arduinos = remoteArduinoRepository.findAll(); model.put("arduinos", arduinos); return "editSwitch"; } @PostMapping("editSwitchSave") public ModelAndView editRemoteSave(@RequestParam(value = "id") String id, @RequestParam(value = "name") String name, @RequestParam(value = "address") String address, ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); if (!id.equals("null")) { RemoteArduino arduino = new RemoteArduino(Integer.parseInt(id), name, address); remoteArduinoRepository.save(arduino); } return new ModelAndView("redirect:/index", model); } @GetMapping("addNew") public String addNewGet(Map<String, Object> model) { return "addNew"; } @PostMapping("addNew") public ModelAndView addNewPost(@RequestParam(value = "name") String name, @RequestParam(value = "address") String address, ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); RemoteArduino arduino = new RemoteArduino(name, address); remoteArduinoRepository.save(arduino); return new ModelAndView("redirect:/index", model); } @PostMapping("deleteSwitch") public ModelAndView deleteSwitch(@RequestParam(value = "id") String id, ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); if (!id.equals("null")) { remoteArduinoRepository.deleteById(Integer.parseInt(id)); } return new ModelAndView("redirect:/index", model); } @PostMapping("turnSwitchArduino") @ResponseBody public String turnSwitchArduino(@RequestParam(value = "id") String id, ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); if (!id.equals("null")) { Optional<RemoteArduino> arduino = remoteArduinoRepository.findById(Integer.parseInt(id)); arduino.ifPresent(RemoteArduino::turnSwitch); } return "{\"status\":\"ok\"}"; } @PostMapping("turnSwitchSonoff") @ResponseBody public String turnSwitchSonoff(@RequestParam(value = "id") String id, ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); if (!id.equals("null")) { Optional<RemoteSonoff> sonoff = remoteSonoffRepository.findById(Integer.parseInt(id)); sonoff.ifPresent(RemoteSonoff::turnSwitch); } return "{\"status\":\"ok\"}"; } @PostMapping("setAlarm") public ModelAndView setAlarm(@RequestParam(value = "hour") String sHour, @RequestParam(value = "minute") String sMinute, @RequestParam(value = "isOn", defaultValue = "off") String sIsOn, ModelMap model) { synchronized (Application.class) { Alarm alarm = new Alarm(Integer.parseInt(sMinute), Integer.parseInt(sHour), sIsOn.equals("on")); alarm.setLastDay(""); alarmRepository.save(alarm); } return new ModelAndView("redirect:/index", model); } @GetMapping("turnAlarmsOff") @ResponseBody public String turnAlarmsOff() { Iterable<Alarm> alarms = alarmRepository.getAllActive(); for (Alarm alarm: alarms) { alarm.setActive(false); alarmRepository.save(alarm); WebResouces webResouces = new WebResouces(); webResouces.turnAlarmOff(); } return "{\"status\":\"ok\"}"; } @GetMapping("getTempetureJSON") @ResponseBody public String getTempetureJSON() { StringBuilder response = new StringBuilder(); ObjectMapper jsonMapper = new ObjectMapper(); ObjectNode rootNode = jsonMapper.createObjectNode(); ArrayNode rootArray = rootNode.putArray("tempetureValues"); Iterable<TempSensorValue> tempDates = tempSensorValueRepository.get500FirstByDate(); double tMax = 0, tMin = 300, hMin = 100, hMax = 0, pMin = 1000, pMax = 0; for(TempSensorValue tempDate: tempDates) { ObjectNode tempElement = rootArray.addObject(); tempElement.put("temp", tempDate.getTempeture()); tempElement.put("press", tempDate.getPressure()); tempElement.put("hum", tempDate.getHumidity()); if (tempDate.getTempeture() > tMax) { tMax = tempDate.getTempeture(); } if (tempDate.getTempeture() < tMin) { tMin = tempDate.getTempeture(); } if (tempDate.getPressure() > pMax) { pMax = tempDate.getPressure(); } if (tempDate.getPressure() < pMin) { pMin = tempDate.getPressure(); } if (tempDate.getHumidity() > hMax) { hMax = tempDate.getHumidity(); } if (tempDate.getHumidity() < hMin) { hMin = tempDate.getHumidity(); } } ObjectNode rangeNode = rootNode.putObject("range"); rangeNode.put("tMax", tMax); rangeNode.put("tMin", tMin); rangeNode.put("pMax", pMax); rangeNode.put("pMin", pMin); rangeNode.put("hMax", hMax); rangeNode.put("hMin", hMin); try { return jsonMapper.writeValueAsString(rootNode); } catch (JsonProcessingException e) { return "{\"error\": \"ok\"}"; } } }
7246a17f70b9c53ab10a753e21fc71492c6e24da
d7cb8f49de3dc52438bae4c926824c2ca24f0e84
/src/examples/RequestRelatedItems.java
9794a14aead1f63594ff4fc88b5df863c62fd5d5
[]
no_license
showaid/SerenaAPI
a8e15296fee428d1c485dcf302c277907023944b
a5a0f00fd56bd913d148bf06e957d51cc3c2cc25
refs/heads/master
2021-01-10T03:17:07.381505
2015-09-30T05:07:56
2015-09-30T05:07:56
43,412,233
0
0
null
null
null
null
UTF-8
Java
false
false
9,638
java
/* =========================================================================== * Copyright (c) 2007 Serena Software. All rights reserved. * * Use of the Sample Code provided by Serena is governed by the following * terms and conditions. By using the Sample Code, you agree to be bound by * the terms contained herein. If you do not agree to the terms herein, do * not install, copy, or use the Sample Code. * * 1. GRANT OF LICENSE. Subject to the terms and conditions herein, you * shall have the nonexclusive, nontransferable right to use the Sample Code * for the sole purpose of developing applications for use solely with the * Serena software product(s) that you have licensed separately from Serena. * Such applications shall be for your internal use only. You further agree * that you will not: (a) sell, market, or distribute any copies of the * Sample Code or any derivatives or components thereof; (b) use the Sample * Code or any derivatives thereof for any commercial purpose; or (c) assign * or transfer rights to the Sample Code or any derivatives thereof. * * 2. DISCLAIMER OF WARRANTIES. TO THE MAXIMUM EXTENT PERMITTED BY * APPLICABLE LAW, SERENA PROVIDES THE SAMPLE CODE AS IS AND WITH ALL * FAULTS, AND HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EITHER * EXPRESSED, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY * IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A * PARTICULAR PURPOSE, OF LACK OF VIRUSES, OF RESULTS, AND OF LACK OF * NEGLIGENCE OR LACK OF WORKMANLIKE EFFORT, CONDITION OF TITLE, QUIET * ENJOYMENT, OR NON-INFRINGEMENT. THE ENTIRE RISK AS TO THE QUALITY OF * OR ARISING OUT OF USE OR PERFORMANCE OF THE SAMPLE CODE, IF ANY, * REMAINS WITH YOU. * * 3. EXCLUSION OF DAMAGES. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE * LAW, YOU AGREE THAT IN CONSIDERATION FOR RECEIVING THE SAMPLE CODE AT NO * CHARGE TO YOU, SERENA SHALL NOT BE LIABLE FOR ANY DAMAGES WHATSOEVER, * INCLUDING BUT NOT LIMITED TO DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF * PROFITS OR CONFIDENTIAL OR OTHER INFORMATION, FOR BUSINESS INTERRUPTION, * FOR PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR NEGLIGENCE, AND FOR ANY * OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY RELATED TO THE USE * OF OR INABILITY TO USE THE SAMPLE CODE, EVEN IN THE EVENT OF THE FAULT, * TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR BREACH OF CONTRACT, * EVEN IF SERENA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE * FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY TO THE * MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW. NOTWITHSTANDING THE ABOVE, * IN NO EVENT SHALL SERENA'S LIABILITY UNDER THIS AGREEMENT OR WITH RESPECT * TO YOUR USE OF THE SAMPLE CODE AND DERIVATIVES THEREOF EXCEED US$10.00. * * 4. INDEMNIFICATION. You hereby agree to defend, indemnify and hold * harmless Serena from and against any and all liability, loss or claim * arising from this agreement or from (i) your license of, use of or * reliance upon the Sample Code or any related documentation or materials, * or (ii) your development, use or reliance upon any application or * derivative work created from the Sample Code. * * 5. TERMINATION OF THE LICENSE. This agreement and the underlying * license granted hereby shall terminate if and when your license to the * applicable Serena software product terminates or if you breach any terms * and conditions of this agreement. * * 6. CONFIDENTIALITY. The Sample Code and all information relating to the * Sample Code (collectively "Confidential Information") are the * confidential information of Serena. You agree to maintain the * Confidential Information in strict confidence for Serena. You agree not * to disclose or duplicate, nor allow to be disclosed or duplicated, any * Confidential Information, in whole or in part, except as permitted in * this Agreement. You shall take all reasonable steps necessary to ensure * that the Confidential Information is not made available or disclosed by * you or by your employees to any other person, firm, or corporation. You * agree that all authorized persons having access to the Confidential * Information shall observe and perform under this nondisclosure covenant. * You agree to immediately notify Serena of any unauthorized access to or * possession of the Confidential Information. * * 7. AFFILIATES. Serena as used herein shall refer to Serena Software, * Inc. and its affiliates. An entity shall be considered to be an * affiliate of Serena if it is an entity that controls, is controlled by, * or is under common control with Serena. * * 8. GENERAL. Title and full ownership rights to the Sample Code, * including any derivative works shall remain with Serena. If a court of * competent jurisdiction holds any provision of this agreement illegal or * otherwise unenforceable, that provision shall be severed and the * remainder of the agreement shall remain in full force and effect. * =========================================================================== */ package examples; import java.util.ArrayList; import java.util.List; import com.clt.serena.resources.PropertyReader; import com.serena.dmclient.api.BulkOperator; import com.serena.dmclient.api.DimensionsConnection; import com.serena.dmclient.api.DimensionsConnectionDetails; import com.serena.dmclient.api.DimensionsConnectionManager; import com.serena.dmclient.api.DimensionsRelatedObject; import com.serena.dmclient.api.ItemRevision; import com.serena.dmclient.api.Project; import com.serena.dmclient.api.Request; import com.serena.dmclient.api.SystemAttributes; /** * Example showing how to find all of the item revisions (regardless of which * project those revisions are contained within) related to a Request object. * Note that, because we are not specifying a project, it is not possible to * retrieve filenames for the item revisions, only their specifications. */ public final class RequestRelatedItems { public static void main(final String[] args) { // if (args.length != 5) { // usage(); // } // connect using the command-line arguments. DimensionsConnectionDetails details = new DimensionsConnectionDetails(); PropertyReader prop = PropertyReader.getInstance(); details.setUsername(prop.getUsername()); details.setPassword(prop.getPassword()); details.setDbName(prop.getDbName()); details.setDbConn(prop.getDbConn()); details.setServer(prop.getServer()); DimensionsConnection connection = DimensionsConnectionManager .getConnection(details); try { listRequestRelatedItems(connection); } finally { // disconnect. connection.close(); } } static void listRequestRelatedItems(final DimensionsConnection connection) { // find the request QLARIUS_CR_1 - note that normally you would have // obtained a Request instance through some other means than this. Request requestObj = connection.getObjectFactory().findRequest( "TERMINAL_P3_0_0_344"); // all items live in the "global" project, however because filenames // of items can differ from project to project, the filename from the // global project may not be the same as it is in the project you are // interested in. Project globalProjectObj = connection.getObjectFactory() .getGlobalProject(); // getChildItems from the global project will return all items that // may be in any project. However, the resulting ItemRevision instances // are scoped to the global project, not the current project. // the flushRelatedObjects calls may or may not be necessary depending // how up-to-date your version of the API JAR files is (it is safer // to do it). requestObj.flushRelatedObjects(ItemRevision.class, true); List relObjs = requestObj.getChildItems(null, globalProjectObj); requestObj.flushRelatedObjects(ItemRevision.class, true); // note that some items may appear more than once (for the // Affected revisions and the In Response To revision). List revObjs = new ArrayList(relObjs.size()); for (int i = 0; i < relObjs.size(); ++i) { DimensionsRelatedObject relObj = (DimensionsRelatedObject) relObjs .get(i); ItemRevision revObj = (ItemRevision) relObj.getObject(); revObjs.add(revObj); } // Because the ItemRevision objects are in the scope of the global // project, if we query filename then we'll get the filename in the // global project. int[] attrs = { SystemAttributes.OBJECT_ID, SystemAttributes.OBJECT_SPEC, SystemAttributes.REVISION, SystemAttributes.FULL_PATH_NAME }; BulkOperator bulk = connection.getObjectFactory().getBulkOperator( revObjs); bulk.queryAttribute(attrs); // now display them. for (int i = 0; i < revObjs.size(); ++i) { ItemRevision revObj = (ItemRevision) revObjs.get(i); String itemSpec = (String) revObj .getAttribute(SystemAttributes.FULL_PATH_NAME); String revision = (String) revObj .getAttribute(SystemAttributes.REVISION); System.out.println((i + 1) + ". " + itemSpec + " " + revision); } } private static void usage() { System.err.println("java " + RequestRelatedItems.class.getName() + " \\"); System.err.println(" {userID} {password} {dbName} {dbConn} {server}"); System.exit(1); } }
a94399ad5b6153d42c76ec5b03eb4a417d83fa23
7fcf73e834eaa6f53fd2db1da5ffeacbd0b4105e
/src/parser/rules/InitializerRule.java
cd0b3594279591516822af5c63af10b74550610e
[]
no_license
Nachodlv/lexer-parser-interpreter
713e7eb124c164c84ef2ba6dd5032457608ff893
31818e2a181a77031b161ec33de1c14236bb2a33
refs/heads/master
2020-05-29T10:12:22.623062
2019-07-20T20:20:38
2019-07-20T20:20:38
189,088,749
0
0
null
null
null
null
UTF-8
Java
false
false
758
java
package parser.rules; import parser.NodeType; import parser.nodes.NonTerminalNode; import parser.nodes.TreeNode; import java.util.ArrayList; import java.util.Stack; public class InitializerRule implements Rule { @Override public Stack<TreeNode> apply(Stack<TreeNode> stack) { TreeNode additive = stack.pop(); TreeNode equals = stack.pop(); ArrayList<TreeNode> child = new ArrayList<>(); child.add(equals); child.add(additive); NonTerminalNode node = new NonTerminalNode( child, NodeType.INITIALIZER, additive.getRow(), additive.getColumn(), additive.getValue()); stack.push(node); return stack; } }
3af94038c15e0a0f3501eb8187614defe5e38f6f
cd345f67964effea829e5e90b0979dc79bcd4af4
/easyrecyclerview/src/main/java/com/jude/easyrecyclerview/extRecyclerView.java
7e97788790f3a230a1f3f1fe5892c71ec1202295
[ "Apache-2.0" ]
permissive
utkozavr/EasyRecyclerView
ebfae936c85142a7e8bd3bb27903a39634f52589
cb969771c4f5d1315332ff4d52aaf7ccfafe7008
refs/heads/master
2021-01-20T12:55:40.992555
2017-02-28T06:46:59
2017-02-28T06:46:59
82,670,071
0
0
null
2017-02-21T11:03:24
2017-02-21T11:03:24
null
UTF-8
Java
false
false
5,308
java
package com.jude.easyrecyclerview; import android.content.Context; import android.support.annotation.Nullable; import android.support.v4.view.InputDeviceCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; public class extRecyclerView extends RecyclerView { private static final int INVALID_POINTER = -1; private int mScrollState = SCROLL_STATE_IDLE; private int mScrollPointerId = INVALID_POINTER; private int mInitialTouchX; private int mInitialTouchY; private int mLastTouchX; private int mLastTouchY; private int mDistX; private int mDistY; private boolean canScroll; private int scrollDistanceTrigger; private int scrollDistance; public extRecyclerView(Context context) { super(context); canScroll = true; } public extRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); canScroll = true; } public extRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); canScroll = true; } @Override public boolean onInterceptTouchEvent(MotionEvent e) { Log.d("extRecyclerView", "onInterceptTouchEvent"); final int action = MotionEventCompat.getActionMasked(e); final int actionIndex = MotionEventCompat.getActionIndex(e); switch (action) { case MotionEvent.ACTION_DOWN: Log.d("extRecyclerView", "ACTION_DOWN"); mScrollPointerId = e.getPointerId(0); mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); mDistX = 0; mDistY = 0; Log.d("mInitialTouchX", String.valueOf(mInitialTouchX)); Log.d("mInitialTouchY", String.valueOf(mInitialTouchY)); break; case MotionEventCompat.ACTION_POINTER_DOWN: Log.d("extRecyclerView", "ACTION_POINTER_DOWN"); mScrollPointerId = e.getPointerId(actionIndex); mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f); mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f); mDistX = 0; mDistY = 0; Log.d("mInitialTouchX", String.valueOf(mInitialTouchX)); Log.d("mInitialTouchY", String.valueOf(mInitialTouchY)); break; case MotionEvent.ACTION_MOVE: { Log.d("extRecyclerView", "ACTION_MOVE"); final int index = e.findPointerIndex(mScrollPointerId); if (index < 0) { Log.e("%%%", "Error processing scroll; pointer index for id " + mScrollPointerId + " not found. Did any MotionEvents get skipped?"); return false; } final int x = (int) (e.getX(index) + 0.5f); final int y = (int) (e.getY(index) + 0.5f); mDistX = x - mInitialTouchX; mDistY = y - mInitialTouchY; Log.d("x", String.valueOf(x)); Log.d("y", String.valueOf(y)); Log.d("dx", String.valueOf(mDistX)); Log.d("dy", String.valueOf(mDistY)); } break; case MotionEventCompat.ACTION_POINTER_UP: { //onPointerUp(e); Log.d("extRecyclerView", "ACTION_POINTER_UP"); } break; case MotionEvent.ACTION_UP: { //mVelocityTracker.clear(); //stopNestedScroll(); Log.d("extRecyclerView", "ACTION_UP"); if(canScroll){ if(mDistY > 300){ //super.smoothScrollBy(mInitialTouchX, mInitialTouchY + 100); super.scrollBy(0, -30); //super.stopScroll(); } else if (mDistY < -300){ //super.smoothScrollBy(mInitialTouchX, mInitialTouchY - 100); super.scrollBy(0, (int) 30); //super.stopScroll(); } } } break; case MotionEvent.ACTION_CANCEL: { //cancelTouch(); Log.d("extRecyclerView", "ACTION_CANCEL"); } } //return super.onInterceptTouchEvent(e); return false; } @Override public void onScrollStateChanged(int state) { if(state == 0){ canScroll = true; } else { canScroll = false; } } public void setScrollDistanceTrigger(int scrollDistanceTrigger) { this.scrollDistanceTrigger = scrollDistanceTrigger; } public void setScrollDistance(int scrollDistance) { this.scrollDistance = scrollDistance; } public int getScrollDistanceTrigger() { return scrollDistanceTrigger; } public int getScrollDistance() { return scrollDistance; } }
[ "123" ]
123
4af426e4cbf76dd848917082cea2b80a2b0409d3
e3ed7864bee05a2304f74aa0ea3503da9593fa7e
/slot-dist-adam2/src/clive/peer/membership/ShuffleResponse.java
7e8cbf275fbe16f9e2c213e407a9b83637feeadd
[]
no_license
payberah/distro
1142d13f66bc95d17f08b1adcc0dfe3838f7ed34
c1ea273f45add843890974951dd71b1861a2a39d
refs/heads/master
2021-01-10T05:26:27.688806
2015-05-27T13:56:18
2015-05-27T13:56:18
36,368,246
0
0
null
null
null
null
UTF-8
Java
false
false
1,650
java
package clive.peer.membership; import java.util.UUID; import clive.peer.common.MSMessage; import clive.peer.common.MSPeerAddress; public class ShuffleResponse extends MSMessage { private static final long serialVersionUID = -5022051054665787770L; private final UUID requestId; private final DescriptorBuffer randomBuffer; private double[] hitRatio; private LockState lockstate; private double v; //------------------------------------------------------------------- public ShuffleResponse(MSPeerAddress source, MSPeerAddress destination, UUID requestId, DescriptorBuffer randomBuffer, double[] hitRatio, LockState lockstate, double v) { super(source, destination); this.requestId = requestId; this.randomBuffer = randomBuffer; this.hitRatio = hitRatio; this.lockstate = lockstate; this.v = v; } //------------------------------------------------------------------- public UUID getRequestId() { return requestId; } //------------------------------------------------------------------- public DescriptorBuffer getRandomBuffer() { return randomBuffer; } //------------------------------------------------------------------- public double[] getHitRatio() { return hitRatio; } //------------------------------------------------------------------- public double getV() { return v; } //------------------------------------------------------------------- public LockState getLockState() { return lockstate; } //------------------------------------------------------------------- public int getSize() { return 0; //return hitRatio.length; } }
c5071510bc99faf8970673d649419bb517a19066
2c0edfcd9e6ddf16a88762a018589cbebe6fa8e8
/CleanSheets/src/main/java/csheets/ext/macro_beanshell/ui/MacroBeanShellAction.java
d73049bbe02a88511f1fd3d3c3b41aa74f2a008c
[]
no_license
ABCurado/University-Projects
7fb32b588f2c7fbe384ca947d25928b8d702d667
6c9475f5ef5604955bc21bb4f8b1d113a344d7ab
refs/heads/master
2021-01-12T05:25:21.614584
2017-01-03T15:29:00
2017-01-03T15:29:00
77,926,226
1
3
null
null
null
null
UTF-8
Java
false
false
971
java
package csheets.ext.macro_beanshell.ui; import csheets.CleanSheets; import csheets.ui.ctrl.BaseAction; import csheets.ui.ctrl.UIController; import java.awt.event.ActionEvent; import static javax.swing.Action.SMALL_ICON; import javax.swing.ImageIcon; /** * * @author Rui Bento */ public class MacroBeanShellAction extends BaseAction { /** * The user interface controller */ private UIController uiController; /** * Creates a new action. * * @param uiController the user interface controller */ public MacroBeanShellAction(UIController uiController) { this.uiController = uiController; } @Override protected String getName() { return "Create Macro/BeanShell"; } protected void defineProperties() { putValue(SMALL_ICON, new ImageIcon(CleanSheets.class. getResource("ext/macro_beanshell/script_small.png"))); } @Override public void actionPerformed(ActionEvent e) { new MacroBeanShellPanel(uiController).setVisible(true); } }
d2ba8336f25d69c99fefbc3ff70b4d821408d50d
3fee38bd6c122cbca05594cbee5ba8ba98435efc
/recommendsystem/src/main/java/com/usst/recommendsystem/common/SystemFilterService.java
fae707e7a60f0835a9d7c2ff75a1418faa76395a
[ "Apache-2.0" ]
permissive
shenzeyu/recommend
7e3cd526442b58b8f46ece9fca6c342f93a76126
515cd02ff20b8329f46a65d14c016326ce20ec13
refs/heads/master
2021-01-10T03:50:59.022456
2016-03-06T14:36:20
2016-03-06T14:36:53
50,432,861
0
0
null
null
null
null
UTF-8
Java
false
false
2,303
java
package com.usst.recommendsystem.common; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; @Service public class SystemFilterService { private static final Logger logger = Logger.getLogger(SystemFilterService.class); private static final String LOGIN_URL = "frontLogin.do"; public void dofilter(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); boolean isNotNeedFilter = SystemFilter.isNotNeedFilter(uri); if (-1 != uri.indexOf("!")) { if (!isNotNeedFilter) { Object systemUser = request.getSession().getAttribute("loginUser"); boolean isLogin = false; if (systemUser != null) { isLogin = true; } if (!isLogin) { String loginUrl = request.getContextPath() + SystemFilter.adminLoginUrl; String remoteAddr = request.getRemoteAddr(); logger.warn("illegal access! url:" + uri + " ;visitor ip:" + remoteAddr); printErrorInfo(response, loginUrl, "请先登录!"); } } } else if (!isNotNeedFilter) { Object loginCustomer = request.getSession().getAttribute("loginCustomer"); boolean isLogin = false; if (loginCustomer != null) { isLogin = true; } if (!isLogin) { String loginUrl = request.getContextPath() + SystemFilter.frontLoginUrl; String remoteAddr = request.getRemoteAddr(); logger.warn("illegal access! url:" + uri + " ;visitor ip:" + remoteAddr); printErrorInfo(response, loginUrl, "请先登录!"); return; } } } public void printErrorInfo(HttpServletResponse response, String loginUrl, String errorInfo) { loginUrl = loginUrl + "frontLogin.do"; response.setContentType("text/html; charset=UTF-8"); PrintWriter writer = null; try { writer = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } writer.write("<script language='javascript'>"); writer.write("alert('" + errorInfo + "');"); writer.write("window.location.href='" + loginUrl + "';"); writer.write("</script>"); writer.close(); } }
9a4f3e5c253d8bb84a1a78e21f36ab7055e3ba41
6e47c6f01fba8e2b545778bc9150335ccfecedf2
/src/test/java/com/chieftain/examination/PropTest.java
43b8c011b0d1e008ac211db8d0c3a8ecec06956c
[]
no_license
yuanbp/examination
3d7d8956dae8a236359a81b221a2db7ec55910bc
2dbdaa898b8d45115bee2f912b8056f5b29e8fec
refs/heads/master
2022-09-17T02:45:52.717122
2020-07-01T05:34:11
2020-07-01T05:34:11
163,947,366
0
0
null
null
null
null
UTF-8
Java
false
false
856
java
package com.chieftain.examination; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * com.chieftain.jtestcodes [workset] * Created by chieftain on 2018/10/9 * * @author chieftain on 2018/10/9 */ public class PropTest { public Properties prop = null; public PropTest() { try { InputStream inputStream = PropTest.class.getClassLoader().getResourceAsStream("application.properties"); prop = new Properties(); prop.load(inputStream); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { PropTest propTest = new PropTest(); System.out.println(propTest.prop.getProperty("test")); } }
9557c82d62e46bb7f29326a85c07998da85abe4b
c5d2de197f99d0c087fc59d8bac5d0c7989f2d09
/src/com/cos/util/MyUtils.java
fc988801e2bab86182aea04a2f2edd0bf5ee699b
[]
no_license
SEOK8561/jhblog
975a6f8f86b20250c772e832ed82045bba81e454
a0e78a5c8b7226a13d646114366285753393dbfe
refs/heads/master
2020-05-18T16:53:40.579856
2019-05-02T07:12:09
2019-05-02T07:12:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,098
java
package com.cos.util; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import javax.servlet.http.HttpServletResponse; public class MyUtils { public static LocalDate StringToLocalDate(String target) { LocalDate result = LocalDate.parse( target, DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm:ss")); return result; } public static void script(String msg, HttpServletResponse response) { try { PrintWriter script = response.getWriter(); script.println("<script>"); script.println("alert('"+msg+"')"); script.println("history.back()"); script.println("</script>"); } catch (IOException e) { e.printStackTrace(); } } public static void script(String msg, String url, HttpServletResponse response) { try { PrintWriter script = response.getWriter(); script.println("<script>"); script.println("alert('"+msg+"')"); script.println("location.href='"+url+"'"); script.println("</script>"); } catch (IOException e) { e.printStackTrace(); } } }
91162d2e2df70a6608d911d6c82fa4cce48dd69b
986bb9554b584c584410a022c896704b5ad22ea2
/app/src/main/java/com/example/katrinpolitexercise/database/data/greenDAOclasses/LoginDataDao.java
af18292139702b4a0552eb26993096aef83236d1
[]
no_license
katrinpolit/KatrinPolitExercise
8ae6f3265f3e36f7506048dbb88fd4ab780986b7
be319ca783f9f2e5bbc2d0ab21d362d95e34f6f6
refs/heads/master
2021-04-30T05:18:40.072527
2018-02-14T21:26:39
2018-02-14T21:26:39
121,412,007
0
0
null
null
null
null
UTF-8
Java
false
false
3,864
java
package com.example.katrinpolitexercise.database.data.greenDAOclasses; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "UserTable". */ public class LoginDataDao extends AbstractDao<LoginData, String> { public static final String TABLENAME = "UserTable"; /** * Properties of entity LoginData.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Email = new Property(0, String.class, "Email", true, "EMAIL"); public final static Property Pass = new Property(1, String.class, "pass", false, "PASS"); } private DaoSession daoSession; public LoginDataDao(DaoConfig config) { super(config); } public LoginDataDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); this.daoSession = daoSession; } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"UserTable\" (" + // "\"EMAIL\" TEXT PRIMARY KEY NOT NULL ," + // 0: Email "\"PASS\" TEXT NOT NULL );"); // 1: pass } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"UserTable\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, LoginData entity) { stmt.clearBindings(); String Email = entity.getEmail(); if (Email != null) { stmt.bindString(1, Email); } stmt.bindString(2, entity.getPass()); } @Override protected final void bindValues(SQLiteStatement stmt, LoginData entity) { stmt.clearBindings(); String Email = entity.getEmail(); if (Email != null) { stmt.bindString(1, Email); } stmt.bindString(2, entity.getPass()); } @Override protected final void attachEntity(LoginData entity) { super.attachEntity(entity); entity.__setDaoSession(daoSession); } @Override public String readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0); } @Override public LoginData readEntity(Cursor cursor, int offset) { LoginData entity = new LoginData( // cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // Email cursor.getString(offset + 1) // pass ); return entity; } @Override public void readEntity(Cursor cursor, LoginData entity, int offset) { entity.setEmail(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0)); entity.setPass(cursor.getString(offset + 1)); } @Override protected final String updateKeyAfterInsert(LoginData entity, long rowId) { return entity.getEmail(); } @Override public String getKey(LoginData entity) { if(entity != null) { return entity.getEmail(); } else { return null; } } @Override public boolean hasKey(LoginData entity) { return entity.getEmail() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
5e6441662c80f443eff0c4ea946d71ede5d06c32
ffa1cf186747c5662682df7797e35c4a941384a2
/src/main/java/cn/wolfcode/service/impl/SystemDictionaryServiceImpl.java
d6babb903110ecad2d26c5af37f2ce25d938fbb9
[]
no_license
mingguangax/mingguangax
7d42725354a706e82a9cae1008ac5799ecaa9b97
d598b7c2213e0d20f428da493ed472b3c683b3ea
refs/heads/master
2023-06-04T06:16:53.466686
2021-06-24T13:41:03
2021-06-24T13:41:03
379,928,931
0
0
null
null
null
null
UTF-8
Java
false
false
2,927
java
package cn.wolfcode.service.impl; import cn.wolfcode.domain.SystemDictionary; import cn.wolfcode.mapper.SystemDictionaryMapper; import cn.wolfcode.qo.QueryObject; import cn.wolfcode.service.ISystemDictionaryService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class SystemDictionaryServiceImpl implements ISystemDictionaryService { @Autowired private SystemDictionaryMapper systemDictionaryMapper; @Override public void insert(SystemDictionary systemDictionary) { systemDictionaryMapper.insert(systemDictionary); } @Override public void deleteById(Long id) { systemDictionaryMapper.deleteByPrimaryKey(id); } @Override public void update(SystemDictionary systemDictionary) { systemDictionaryMapper.update(systemDictionary); } @Override public List<SystemDictionary> selectById(Long id) { List<SystemDictionary> systemDictionary = systemDictionaryMapper.selectById(id); return systemDictionary; } @Override public List<SystemDictionary> selectAll() { List<SystemDictionary> systemDictionarys = systemDictionaryMapper.selectAll(); return systemDictionarys; } @Override public PageInfo<SystemDictionary> selectByList(QueryObject qo) { PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); List<SystemDictionary> systemDictionarys =systemDictionaryMapper.selectForList(qo); return new PageInfo<>(systemDictionarys); } @Override public List<SystemDictionary> selectQueryTree() { //图个数据字典下面可能有子字典,字字典可能还有字字典 // //最顶级一层 List<SystemDictionary> systemDictionaries = systemDictionaryMapper.selectByParentId(null); //查询出自己的子数据字典 存到模型层的itmes中 tree(systemDictionaries); return systemDictionaries; } @Override public List<SystemDictionary> queryBySb(String sn) { return systemDictionaryMapper.queryBySn(sn); } @Override public List<SystemDictionary> quertItemById(Long id) { return systemDictionaryMapper.selectItemById(id); } private void tree(List<SystemDictionary> systemDictionaries){ for (SystemDictionary systemDictionary : systemDictionaries) { Long systemDictionaryId = systemDictionary.getId(); List<SystemDictionary> childItems = systemDictionaryMapper.selectByParentId(systemDictionaryId); //把子数据字典存到对应的属性上 systemDictionary.setItems(childItems); if (childItems.size()>0) { tree(childItems); } } } }
f862fc448e3340a425742800e5de3e4634489718
14bc9d8490298c649d47b9fecca9e2fc83ab6301
/Java/Solutions/2.2 Simple Calculations - Exam Problems/Tiles.java
c61b3d1c6f78e812f6ffd5fda6b017679ece919e
[]
no_license
SoftUni/Programming-Basics-Resources
99e9e681f868b14e624e8e4550b18ed00fe433be
262204570036fe75f2d2755ad41e6e987ed7089b
refs/heads/master
2022-03-14T11:45:42.567764
2022-02-24T09:36:15
2022-02-24T09:36:15
89,230,307
32
12
null
2019-02-18T19:03:40
2017-04-24T11:02:23
Java
UTF-8
Java
false
false
799
java
import java.util.Scanner; public class Tiles { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Ground length int n = Integer.parseInt(scanner.nextLine()); // Tile width double w = Double.parseDouble(scanner.nextLine()); // Tile length double h = Double.parseDouble(scanner.nextLine()); // Bench width int a = Integer.parseInt(scanner.nextLine()); // Bench length int b = Integer.parseInt(scanner.nextLine()); int area = n * n; int bench = a * b; int areaToRepair = area - bench; double tiles = areaToRepair / (w * h); double time = tiles * 0.2; System.out.println(tiles); System.out.println(time); } }
dd2d473adb8cbfb8eda071284a9a6fa593ac410c
5407585b7749d94f5a882eee6f7129afc6f79720
/dm-code/dm-service/src/main/java/org/finra/dm/service/impl/EmrServiceImpl.java
241ef8956f0318d5a1c3fcfb15932701deb4b8e6
[ "Apache-2.0" ]
permissive
walw/herd
67144b0192178050118f5572c5aa271e1525e14f
e236f8f4787e62d5ebf5e1a55eda696d75c5d3cf
refs/heads/master
2021-01-14T14:16:23.163693
2015-10-08T14:23:54
2015-10-08T14:23:54
43,558,552
0
1
null
2015-10-02T14:50:59
2015-10-02T14:50:59
null
UTF-8
Java
false
false
55,247
java
/* * Copyright 2015 herd contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finra.dm.service.impl; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.xml.datatype.XMLGregorianCalendar; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.elasticmapreduce.model.Cluster; import com.amazonaws.services.elasticmapreduce.model.ClusterSummary; import com.amazonaws.services.elasticmapreduce.model.Step; import com.amazonaws.services.elasticmapreduce.model.StepSummary; import org.apache.http.HttpStatus; import org.apache.oozie.client.WorkflowAction; import org.apache.oozie.client.WorkflowJob; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.finra.dm.core.DmDateUtils; import org.finra.dm.core.helper.ConfigurationHelper; import org.finra.dm.dao.DmDao; import org.finra.dm.dao.EmrDao; import org.finra.dm.dao.OozieDao; import org.finra.dm.dao.config.DaoSpringModuleConfig; import org.finra.dm.dao.helper.DmStringHelper; import org.finra.dm.dao.helper.EmrHelper; import org.finra.dm.dao.helper.EmrPricingHelper; import org.finra.dm.dao.helper.XmlHelper; import org.finra.dm.dao.impl.OozieDaoImpl; import org.finra.dm.model.ObjectNotFoundException; import org.finra.dm.model.dto.AwsParamsDto; import org.finra.dm.model.dto.ConfigurationValue; import org.finra.dm.model.dto.EmrClusterAlternateKeyDto; import org.finra.dm.model.jpa.EmrClusterCreationLogEntity; import org.finra.dm.model.jpa.EmrClusterDefinitionEntity; import org.finra.dm.model.jpa.NamespaceEntity; import org.finra.dm.model.api.xml.EmrCluster; import org.finra.dm.model.api.xml.EmrClusterCreateRequest; import org.finra.dm.model.api.xml.EmrClusterDefinition; import org.finra.dm.model.api.xml.EmrMasterSecurityGroup; import org.finra.dm.model.api.xml.EmrMasterSecurityGroupAddRequest; import org.finra.dm.model.api.xml.EmrStep; import org.finra.dm.model.api.xml.OozieWorkflowAction; import org.finra.dm.model.api.xml.OozieWorkflowJob; import org.finra.dm.model.api.xml.RunOozieWorkflowRequest; import org.finra.dm.service.EmrService; import org.finra.dm.service.helper.DmDaoHelper; import org.finra.dm.service.helper.DmHelper; import org.finra.dm.service.helper.EmrStepHelper; import org.finra.dm.service.helper.EmrStepHelperFactory; /** * The EMR service implementation. */ @Service @Transactional(value = DaoSpringModuleConfig.DM_TRANSACTION_MANAGER_BEAN_NAME) public class EmrServiceImpl implements EmrService { @Autowired private DmDaoHelper dmDaoHelper; @Autowired private EmrHelper emrHelper; @Autowired private EmrPricingHelper emrPricingHelper; @Autowired private EmrDao emrDao; @Autowired private DmHelper dmHelper; @Autowired protected XmlHelper xmlHelper; @Autowired private ConfigurationHelper configurationHelper; @Autowired private EmrStepHelperFactory emrStepHelperFactory; @Autowired private DmDao dmDao; @Autowired private OozieDao oozieDao; @Autowired private DmStringHelper dmStringHelper; /** * Gets details of an existing EMR Cluster. Creates its own transaction. * * @param emrClusterAlternateKeyDto, the EMR cluster alternate key * @param emrClusterId, the cluster id of the cluster to get details * @param emrStepId, the step id of the step to get details * @param verbose, parameter for whether to return detailed information * @param retrieveOozieJobs parameter for whether to retrieve oozie job information * * @return the EMR Cluster object with details. * @throws Exception */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public EmrCluster getCluster(EmrClusterAlternateKeyDto emrClusterAlternateKeyDto, String emrClusterId, String emrStepId, boolean verbose, boolean retrieveOozieJobs) throws Exception { return getClusterImpl(emrClusterAlternateKeyDto, emrClusterId, emrStepId, verbose, retrieveOozieJobs); } /** * Gets details of an existing EMR Cluster. * * @param emrClusterAlternateKeyDto the EMR cluster alternate key * @param emrClusterId the cluster id of the cluster to get details * @param emrStepId the step id of the step to get details * @param verbose parameter for whether to return detailed information * @param retrieveOozieJobs parameter for whether to retrieve oozie job information * * @return the EMR Cluster object with details. * @throws Exception if an error occurred while getting the cluster. */ protected EmrCluster getClusterImpl(EmrClusterAlternateKeyDto emrClusterAlternateKeyDto, String emrClusterId, String emrStepId, boolean verbose, boolean retrieveOozieJobs) throws Exception { // Perform the request validation. emrHelper.validateEmrClusterKey(emrClusterAlternateKeyDto); // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(emrClusterAlternateKeyDto.getNamespace()); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(emrClusterAlternateKeyDto.getNamespace(), emrClusterAlternateKeyDto.getEmrClusterDefinitionName()); EmrCluster emrCluster = createEmrClusterFromRequest(null, namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName(), null, null, null, null); String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName()); try { // Get Cluster status if clusterId is specified if (StringUtils.hasText(emrClusterId)) { Cluster cluster = emrDao.getEmrClusterById(emrClusterId.trim(), emrHelper.getAwsParamsDto()); // Validate that, Cluster exists Assert.notNull(cluster, "An EMR cluster must exists with the cluster ID \"" + emrClusterId + "\"."); // Validate that, Cluster name match as specified Assert.isTrue(clusterName.equalsIgnoreCase(cluster.getName()), "Cluster name of specified cluster id \"" + emrClusterId + "\" must match the name specified."); emrCluster.setId(cluster.getId()); emrCluster.setStatus(cluster.getStatus().getState()); } else { ClusterSummary clusterSummary = emrDao.getActiveEmrClusterByName(clusterName, emrHelper.getAwsParamsDto()); // Validate that, Cluster exists with the name Assert.notNull(clusterSummary, "An EMR cluster must exists with the name \"" + clusterName + "\"."); emrCluster.setId(clusterSummary.getId()); emrCluster.setStatus(clusterSummary.getStatus().getState()); } // Get active step details if (emrHelper.isActiveEmrState(emrCluster.getStatus())) { StepSummary stepSummary = emrDao.getClusterActiveStep(emrCluster.getId(), emrHelper.getAwsParamsDto()); if (stepSummary != null) { EmrStep activeStep; // If verbose get active step details if (verbose) { activeStep = buildEmrStepFromAwsStep(emrDao.getClusterStep(emrCluster.getId(), stepSummary.getId(), emrHelper.getAwsParamsDto()), true); } else { activeStep = buildEmrStepFromAwsStepSummary(stepSummary); } emrCluster.setActiveStep(activeStep); } } // Get requested step details if (StringUtils.hasText(emrStepId)) { Step step = emrDao.getClusterStep(emrCluster.getId(), emrStepId.trim(), emrHelper.getAwsParamsDto()); emrCluster.setStep(buildEmrStepFromAwsStep(step, verbose)); } // Get oozie job details if requested. if (retrieveOozieJobs && (emrCluster.getStatus().equalsIgnoreCase("RUNNING") || emrCluster.getStatus().equalsIgnoreCase("WAITING"))) { emrCluster.setOozieWorkflowJobs(retrieveOozieJobs(emrCluster.getId())); } } catch (AmazonServiceException ex) { handleAmazonException(ex, "An Amazon exception occurred while getting EMR cluster details with name \"" + clusterName + "\"."); } return emrCluster; } /** * Retrieves the List of running oozie workflow jobs on the cluster. * * @param clusterId the cluster Id * * @return the List of running oozie workflow jobs on the cluster. * @throws Exception */ private List<OozieWorkflowJob> retrieveOozieJobs(String clusterId) throws Exception { // Retrieve cluster's master instance IP String masterIpAddress = getEmrClusterMasterIpAddress(clusterId); // Number of jobs to be included in the response. int jobsToInclude = dmStringHelper.getConfigurationValueAsInteger(ConfigurationValue.EMR_OOZIE_JOBS_TO_INCLUDE_IN_CLUSTER_STATUS); // List of wrapper jobs that have been found. List<WorkflowJob> jobsFound = oozieDao.getRunningEmrOozieJobsByName(masterIpAddress, OozieDaoImpl.DM_OOZIE_WRAPPER_WORKFLOW_NAME, 1, jobsToInclude); // Construct the response List<OozieWorkflowJob> oozieWorkflowJobs = new ArrayList<>(); for (WorkflowJob workflowJob : jobsFound) { // Get the client Workflow id. WorkflowAction clientWorkflowAction = emrHelper.getClientWorkflowAction(workflowJob); OozieWorkflowJob resultOozieWorkflowJob = new OozieWorkflowJob(); resultOozieWorkflowJob.setId(workflowJob.getId()); // If client workflow is null means that DM wrapper workflow has not started the client workflow yet. // Hence return status that it is still in DM preparation. if (clientWorkflowAction == null) { resultOozieWorkflowJob.setStatus(OozieDaoImpl.OOZIE_WORKFLOW_JOB_STATUS_DM_PREP); } else { resultOozieWorkflowJob.setStartTime(toXmlGregorianCalendar(clientWorkflowAction.getStartTime())); resultOozieWorkflowJob.setStatus(workflowJob.getStatus().toString()); } oozieWorkflowJobs.add(resultOozieWorkflowJob); } return oozieWorkflowJobs; } /** * Builds EmrStep object from the EMR step. Fills in details if verbose=true. */ private EmrStep buildEmrStepFromAwsStep(Step step, boolean verbose) { EmrStep emrStep = new EmrStep(); emrStep.setId(step.getId()); emrStep.setStepName(step.getName()); emrStep.setStatus(step.getStatus().getState()); if (verbose) { emrStep.setJarLocation(step.getConfig().getJar()); emrStep.setMainClass(step.getConfig().getMainClass()); emrStep.setScriptArguments(step.getConfig().getArgs()); emrStep.setContinueOnError(step.getActionOnFailure()); } return emrStep; } /** * Builds EmrStep object from the EMR StepSummary. Fills in details if verbose=true. */ private EmrStep buildEmrStepFromAwsStepSummary(StepSummary stepSummary) { EmrStep emrStep = new EmrStep(); emrStep.setId(stepSummary.getId()); emrStep.setStepName(stepSummary.getName()); emrStep.setStatus(stepSummary.getStatus().getState()); return emrStep; } /** * Creates a new EMR Cluster. Creates its own transaction. * * @param request the EMR cluster create request * * @return the created EMR cluster object * @throws Exception if there were any errors while creating the cluster. */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public EmrCluster createCluster(EmrClusterCreateRequest request) throws Exception { return createClusterImpl(request); } /** * <p> Creates a new EMR cluster based on the given request if the cluster with the given name does not already exist. If the cluster already exist, returns * the information about the existing cluster. </p> <p> The request must contain: </p> <ul> <li>A namespace and definition name which refer to an existing * EMR cluster definition.</li> <li>A valid cluster name to create.</li> </ul> <p> The request may optionally contain: </p> <ul> <li>A "dry run" flag, which * when set to {@code true}, no calls to AWS will occur, but validations and override will. Defaults to {@code false}.</li> <li>An override parameter, which * when set, overrides the given parameters in the cluster definition before creating the cluster. Defaults to no override. </li> </ul> <p> A successful * response will contain: </p> <ul> <li>The ID of the cluster that was created, or if the cluster already exists, the ID of the cluster that exists. This * field will be {@code null} when dry run flag is {@code true}.</li> <li>The status of the cluster that was created or already exists. The status will * normally be "Starting" on successful creations. This field will be {@code null} when dry run flag is {@code true}</li> <li>The namespace, definition * name, and cluster name of the cluster.</li> <li>The dry run flag, if given in the request.</li> <li>An indicator whether the cluster was created or not. * If the cluster already exists, the cluster will not be created and this flag will be set to {@code false}.</li> <li>The definition which was used to * create the cluster. If any overrides were given, this definition's values will be the values after the override. This field will be {@code null} if the * cluster was not created.</li> </ul> <p> Notes: </p> <ul> <li>At any point of the execution, if there are validation errors, the method will immediately * throw an exception.</li> <li>Even if the validations pass, AWS may still reject the request, which will cause this method to throw an exception.</li> * <li>Dry runs do not make any calls to AWS, therefore AWS may still reject the creation request even when a dry run succeeds.</li> </ul> * * @param request - {@link EmrClusterCreateRequest} The EMR cluster create request * * @return {@link EmrCluster} the created EMR cluster object * @throws Exception when the original EMR cluster definition XML is malformed */ protected EmrCluster createClusterImpl(EmrClusterCreateRequest request) throws Exception { AwsParamsDto awsParamsDto = emrHelper.getAwsParamsDto(); // Extract EMR cluster alternate key from the create request. EmrClusterAlternateKeyDto emrClusterAlternateKeyDto = getEmrClusterAlternateKey(request); // Perform the request validation. emrHelper.validateEmrClusterKey(emrClusterAlternateKeyDto); // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(emrClusterAlternateKeyDto.getNamespace()); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(emrClusterAlternateKeyDto.getNamespace(), emrClusterAlternateKeyDto.getEmrClusterDefinitionName()); // Replace all S3 managed location variables in xml String toReplace = getS3ManagedReplaceString(); String replacedConfigXml = emrClusterDefinitionEntity.getConfiguration().replaceAll(toReplace, emrHelper.getS3StagingLocation()); // Unmarshal definition xml into JAXB object. EmrClusterDefinition emrClusterDefinition = xmlHelper.unmarshallXmlToObject(EmrClusterDefinition.class, replacedConfigXml); // Perform override if override is set overrideEmrClusterDefinition(emrClusterDefinition, request.getEmrClusterDefinitionOverride()); // Perform the EMR cluster definition configuration validation. dmHelper.validateEmrClusterDefinitionConfiguration(emrClusterDefinition); // Find best price and update definition emrPricingHelper.updateEmrClusterDefinitionWithBestPrice(emrClusterDefinition); String clusterId = null; // The cluster ID record. String emrClusterStatus = null; Boolean emrClusterCreated = null; // Was cluster created? // If the dryRun flag is null or false. This is the default option if no flag is given. if (!Boolean.TRUE.equals(request.isDryRun())) { /* * Create the cluster only if the cluster does not already exist. * If the cluster is created, record the newly created cluster ID. * If the cluster already exists, record the existing cluster ID. * If there is any error while attempting to check for existing cluster or create a new one, handle the exception to throw appropriate exception. */ String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName()); try { ClusterSummary clusterSummary = emrDao.getActiveEmrClusterByName(clusterName, awsParamsDto); // If cluster does not already exist. if (clusterSummary == null) { clusterId = emrDao.createEmrCluster(clusterName, emrClusterDefinition, awsParamsDto); emrClusterCreated = true; EmrClusterCreationLogEntity emrClusterCreationLogEntity = new EmrClusterCreationLogEntity(); emrClusterCreationLogEntity.setNamespace(emrClusterDefinitionEntity.getNamespace()); emrClusterCreationLogEntity.setEmrClusterDefinitionName(emrClusterDefinitionEntity.getName()); emrClusterCreationLogEntity.setEmrClusterName(emrClusterAlternateKeyDto.getEmrClusterName()); emrClusterCreationLogEntity.setEmrClusterId(clusterId); emrClusterCreationLogEntity.setEmrClusterDefinition(xmlHelper.objectToXml(emrClusterDefinition)); dmDao.saveAndRefresh(emrClusterCreationLogEntity); } // If the cluster already exist. else { clusterId = clusterSummary.getId(); emrClusterCreated = false; emrClusterDefinition = null; // Do not include definition in response } emrClusterStatus = emrDao.getEmrClusterStatusById(clusterId, awsParamsDto); } catch (AmazonServiceException ex) { handleAmazonException(ex, "An Amazon exception occurred while creating EMR cluster with name \"" + clusterName + "\"."); } } // If the dryRun flag is true and not null else { emrClusterCreated = false; } return createEmrClusterFromRequest(clusterId, namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName(), emrClusterStatus, emrClusterCreated, request.isDryRun(), emrClusterDefinition); } /** * <p> Overrides the properties of {@code emrClusterDefinition} with the properties of {@code emrClusterDefinitionOverride}. </p> <p> If any property in * {@code emrClusterDefinitionOverride} is {@code null}, the property will remain unmodified. </p> <p> If any property in {@code * emrClusterDefinitionOverride} is not {@code null}, the property will be set. </p> <p> Any list or object type properties will be shallowly overridden. * That is, if a list is given in the override, the entire list will be set. Note that this is a shallow copy operation, so any modification to the override * list or object will affect the definition. </p> <p> This method does nothing if {@code emrClusterDefinitionOverride} is {@code null}. </p> * * @param emrClusterDefinition - definition to override * @param emrClusterDefinitionOverride - the override value or {@code null} */ @SuppressWarnings("PMD.CyclomaticComplexity") // Method is not complex. It's just very repetitive. private void overrideEmrClusterDefinition(EmrClusterDefinition emrClusterDefinition, EmrClusterDefinition emrClusterDefinitionOverride) { if (emrClusterDefinitionOverride != null) { if (emrClusterDefinitionOverride.getReleaseLabel() != null) { emrClusterDefinition.setReleaseLabel(emrClusterDefinitionOverride.getReleaseLabel()); } if (emrClusterDefinitionOverride.getApplications() != null) { emrClusterDefinition.setApplications(emrClusterDefinitionOverride.getApplications()); } if (emrClusterDefinitionOverride.getConfigurations() != null) { emrClusterDefinition.setConfigurations(emrClusterDefinitionOverride.getConfigurations()); } if (emrClusterDefinitionOverride.getSshKeyPairName() != null) { emrClusterDefinition.setSshKeyPairName(emrClusterDefinitionOverride.getSshKeyPairName()); } if (emrClusterDefinitionOverride.getSubnetId() != null) { emrClusterDefinition.setSubnetId(emrClusterDefinitionOverride.getSubnetId()); } if (emrClusterDefinitionOverride.getLogBucket() != null) { emrClusterDefinition.setLogBucket(emrClusterDefinitionOverride.getLogBucket()); } if (emrClusterDefinitionOverride.isKeepAlive() != null) { emrClusterDefinition.setKeepAlive(emrClusterDefinitionOverride.isKeepAlive()); } if (emrClusterDefinitionOverride.isVisibleToAll() != null) { emrClusterDefinition.setVisibleToAll(emrClusterDefinitionOverride.isVisibleToAll()); } if (emrClusterDefinitionOverride.isTerminationProtection() != null) { emrClusterDefinition.setTerminationProtection(emrClusterDefinitionOverride.isTerminationProtection()); } if (emrClusterDefinitionOverride.isEncryptionEnabled() != null) { emrClusterDefinition.setEncryptionEnabled(emrClusterDefinitionOverride.isEncryptionEnabled()); } if (emrClusterDefinitionOverride.getAmiVersion() != null) { emrClusterDefinition.setAmiVersion(emrClusterDefinitionOverride.getAmiVersion()); } if (emrClusterDefinitionOverride.getHadoopVersion() != null) { emrClusterDefinition.setHadoopVersion(emrClusterDefinitionOverride.getHadoopVersion()); } if (emrClusterDefinitionOverride.getHiveVersion() != null) { emrClusterDefinition.setHiveVersion(emrClusterDefinitionOverride.getHiveVersion()); } if (emrClusterDefinitionOverride.getPigVersion() != null) { emrClusterDefinition.setPigVersion(emrClusterDefinitionOverride.getPigVersion()); } if (emrClusterDefinitionOverride.getEc2NodeIamProfileName() != null) { emrClusterDefinition.setEc2NodeIamProfileName(emrClusterDefinitionOverride.getEc2NodeIamProfileName()); } if (emrClusterDefinitionOverride.isInstallOozie() != null) { emrClusterDefinition.setInstallOozie(emrClusterDefinitionOverride.isInstallOozie()); } if (emrClusterDefinitionOverride.getCustomBootstrapActionMaster() != null) { emrClusterDefinition.setCustomBootstrapActionMaster(emrClusterDefinitionOverride.getCustomBootstrapActionMaster()); } if (emrClusterDefinitionOverride.getCustomBootstrapActionAll() != null) { emrClusterDefinition.setCustomBootstrapActionAll(emrClusterDefinitionOverride.getCustomBootstrapActionAll()); } if (emrClusterDefinitionOverride.getAdditionalInfo() != null) { emrClusterDefinition.setAdditionalInfo(emrClusterDefinitionOverride.getAdditionalInfo()); } if (emrClusterDefinitionOverride.getInstanceDefinitions() != null) { emrClusterDefinition.setInstanceDefinitions(emrClusterDefinitionOverride.getInstanceDefinitions()); } if (emrClusterDefinitionOverride.getNodeTags() != null) { emrClusterDefinition.setNodeTags(emrClusterDefinitionOverride.getNodeTags()); } if (emrClusterDefinitionOverride.getDaemonConfigurations() != null) { emrClusterDefinition.setDaemonConfigurations(emrClusterDefinitionOverride.getDaemonConfigurations()); } if (emrClusterDefinitionOverride.getHadoopConfigurations() != null) { emrClusterDefinition.setHadoopConfigurations(emrClusterDefinitionOverride.getHadoopConfigurations()); } if (emrClusterDefinitionOverride.getServiceIamRole() != null) { emrClusterDefinition.setServiceIamRole(emrClusterDefinitionOverride.getServiceIamRole()); } if (emrClusterDefinitionOverride.getSupportedProduct() != null) { emrClusterDefinition.setSupportedProduct(emrClusterDefinitionOverride.getSupportedProduct()); } if (emrClusterDefinitionOverride.getHadoopJarSteps() != null) { emrClusterDefinition.setHadoopJarSteps(emrClusterDefinitionOverride.getHadoopJarSteps()); } } } /** * Terminates the EMR Cluster. Creates its own transaction. * * @param emrClusterAlternateKeyDto, the EMR cluster alternate key * @param overrideTerminationProtection, parameter for whether to override termination protection * * @return the terminated EMR cluster object * @throws Exception if there were any errors while terminating the cluster. */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public EmrCluster terminateCluster(EmrClusterAlternateKeyDto emrClusterAlternateKeyDto, boolean overrideTerminationProtection) throws Exception { return terminateClusterImpl(emrClusterAlternateKeyDto, overrideTerminationProtection); } /** * Terminates the EMR Cluster. * * @param emrClusterAlternateKeyDto the EMR cluster alternate key * @param overrideTerminationProtection parameter for whether to override termination protection * * @return the terminated EMR cluster object * @throws Exception if there were any errors while terminating the cluster. */ protected EmrCluster terminateClusterImpl(EmrClusterAlternateKeyDto emrClusterAlternateKeyDto, boolean overrideTerminationProtection) throws Exception { AwsParamsDto awsParamsDto = emrHelper.getAwsParamsDto(); // Perform the request validation. emrHelper.validateEmrClusterKey(emrClusterAlternateKeyDto); // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(emrClusterAlternateKeyDto.getNamespace()); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(emrClusterAlternateKeyDto.getNamespace(), emrClusterAlternateKeyDto.getEmrClusterDefinitionName()); String clusterId = null; String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName()); try { clusterId = emrDao.terminateEmrCluster(clusterName, overrideTerminationProtection, awsParamsDto); } catch (AmazonServiceException ex) { handleAmazonException(ex, "An Amazon exception occurred while terminating EMR cluster with name \"" + clusterName + "\"."); } return createEmrClusterFromRequest(clusterId, namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterAlternateKeyDto.getEmrClusterName(), emrDao.getEmrClusterStatusById(clusterId, awsParamsDto), null, null, null); } /** * Creates a EMR cluster alternate key from the relative values in the EMR Cluster Create Request. * * @param emrClusterCreateRequest the EMR cluster create request * * @return the EMR cluster alternate key */ private EmrClusterAlternateKeyDto getEmrClusterAlternateKey(EmrClusterCreateRequest emrClusterCreateRequest) { return EmrClusterAlternateKeyDto.builder().namespace(emrClusterCreateRequest.getNamespace()) .emrClusterDefinitionName(emrClusterCreateRequest.getEmrClusterDefinitionName()).emrClusterName(emrClusterCreateRequest.getEmrClusterName()) .build(); } /** * Creates a new EMR cluster object from request. * * @param clusterId the cluster Id. * @param namespaceCd the namespace Code * @param clusterDefinitionName the cluster definition * @param clusterName the cluster name * @param clusterStatus the cluster status * @param emrClusterCreated whether EMR cluster was created. * @param dryRun The dry run flag. * @param emrClusterDefinition the EMR cluster definition. * * @return the created EMR cluster object */ private EmrCluster createEmrClusterFromRequest(String clusterId, String namespaceCd, String clusterDefinitionName, String clusterName, String clusterStatus, Boolean emrClusterCreated, Boolean dryRun, EmrClusterDefinition emrClusterDefinition) { // Create the EMR cluster. EmrCluster emrCluster = new EmrCluster(); emrCluster.setId(clusterId); emrCluster.setNamespace(namespaceCd); emrCluster.setEmrClusterDefinitionName(clusterDefinitionName); emrCluster.setEmrClusterName(clusterName); emrCluster.setStatus(clusterStatus); emrCluster.setDryRun(dryRun); emrCluster.setEmrClusterCreated(emrClusterCreated); emrCluster.setEmrClusterDefinition(emrClusterDefinition); return emrCluster; } /** * Adds step to an existing EMR Cluster. Creates its own transaction. * <p/> * There are five serializable objects supported currently. They are 1: ShellStep - For shell scripts 2: OozieStep - For Oozie workflow xml files 3: * HiveStep - For hive scripts 4: HadoopJarStep - For Custom Map Reduce Jar files and 5: PigStep - For Pig scripts. * * @param request the EMR steps add request * * @return the EMR steps add object with added steps * @throws Exception if there were any errors while adding a step to the cluster. */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public Object addStepToCluster(Object request) throws Exception { return addStepToClusterImpl(request); } /** * Adds step to an existing EMR Cluster. * * @param request the EMR steps add request * * @return the EMR step add object with added steps * @throws Exception if there were any errors while adding a step to the cluster. */ protected Object addStepToClusterImpl(Object request) throws Exception { EmrStepHelper stepHelper = emrStepHelperFactory.getStepHelper(request.getClass().getName()); // Perform the request validation. validateAddStepToClusterRequest(request, stepHelper); // Perform the step specific validation stepHelper.validateAddStepRequest(request); // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(stepHelper.getRequestNamespace(request)); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(stepHelper.getRequestNamespace(request), stepHelper.getRequestEmrClusterDefinitionName(request)); // Update the namespace and cluster definition name in request from database. stepHelper.setRequestNamespace(request, namespaceEntity.getCode()); stepHelper.setRequestEmrClusterDefinitionName(request, emrClusterDefinitionEntity.getName()); String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), stepHelper.getRequestEmrClusterName(request)); Object emrStep = stepHelper.buildResponseFromRequest(request); try { String stepId = emrDao.addEmrStep(clusterName, stepHelper.getEmrStepConfig(emrStep), emrHelper.getAwsParamsDto()); stepHelper.setStepId(emrStep, stepId); } catch (AmazonServiceException ex) { handleAmazonException(ex, "An Amazon exception occurred while adding EMR step \"" + stepHelper.getRequestStepName(request) + "\" to cluster with name \"" + clusterName + "\"."); } return emrStep; } /** * Validates the add steps to EMR cluster create request. This method also trims request parameters. * * @param request the request. * * @throws IllegalArgumentException if any validation errors were found. */ private void validateAddStepToClusterRequest(Object request, EmrStepHelper stepHelper) throws IllegalArgumentException { String namespace = stepHelper.getRequestNamespace(request); String clusterDefinitionName = stepHelper.getRequestEmrClusterDefinitionName(request); String clusterName = stepHelper.getRequestEmrClusterName(request); // Validate required elements Assert.hasText(namespace, "A namespace must be specified."); Assert.hasText(clusterDefinitionName, "An EMR cluster definition name must be specified."); Assert.hasText(clusterName, "An EMR cluster name must be specified."); // Remove leading and trailing spaces. stepHelper.setRequestNamespace(request, namespace.trim()); stepHelper.setRequestEmrClusterDefinitionName(request, clusterDefinitionName.trim()); stepHelper.setRequestEmrClusterName(request, clusterName.trim()); } private String getS3ManagedReplaceString() { return configurationHelper.getProperty(ConfigurationValue.S3_STAGING_RESOURCE_LOCATION); } /** * Adds security groups to the master node of an existing EMR Cluster. Creates its own transaction. * * @param request, the EMR master security group add request * * @return the added EMR master security groups * @throws Exception if there were any errors adding the security groups to the cluster master. */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public EmrMasterSecurityGroup addSecurityGroupsToClusterMaster(EmrMasterSecurityGroupAddRequest request) throws Exception { return addSecurityGroupsToClusterMasterImpl(request); } /** * Adds security groups to the master node of an existing EMR Cluster. * * @param request the EMR master security group add request * * @return the added EMR master security groups * @throws Exception if there were any errors adding the security groups to the cluster master. */ protected EmrMasterSecurityGroup addSecurityGroupsToClusterMasterImpl(EmrMasterSecurityGroupAddRequest request) throws Exception { // Perform the request validation. validateAddSecurityGroupsToClusterMasterRequest(request); // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(request.getNamespace()); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(request.getNamespace(), request.getEmrClusterDefinitionName()); List<String> groupIds = null; String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), request.getEmrClusterName()); try { groupIds = emrDao.addEmrMasterSecurityGroups(clusterName, request.getSecurityGroupIds(), emrHelper.getAwsParamsDto()); } catch (AmazonServiceException ex) { handleAmazonException(ex, "An Amazon exception occurred while adding EMR security groups: " + dmHelper.buildStringWithDefaultDelimiter(request.getSecurityGroupIds()) + " to cluster: " + clusterName); } return createEmrClusterMasterGroupFromRequest(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), request.getEmrClusterName(), groupIds); } /** * Validates the add groups to EMR cluster master create request. This method also trims request parameters. * * @param request the request. * * @throws IllegalArgumentException if any validation errors were found. */ private void validateAddSecurityGroupsToClusterMasterRequest(EmrMasterSecurityGroupAddRequest request) throws IllegalArgumentException { // Validate required elements Assert.hasText(request.getNamespace(), "A namespace must be specified."); Assert.hasText(request.getEmrClusterDefinitionName(), "An EMR cluster definition name must be specified."); Assert.hasText(request.getEmrClusterName(), "An EMR cluster name must be specified."); Assert.notEmpty(request.getSecurityGroupIds(), "At least one security group must be specified."); for (String securityGroup : request.getSecurityGroupIds()) { Assert.hasText(securityGroup, "A security group value must be specified."); } // Remove leading and trailing spaces. request.setNamespace(request.getNamespace().trim()); request.setEmrClusterDefinitionName(request.getEmrClusterDefinitionName().trim()); request.setEmrClusterName(request.getEmrClusterName().trim()); String[] trimmedGroups = new String[request.getSecurityGroupIds().size()]; trimmedGroups = StringUtils.trimArrayElements(request.getSecurityGroupIds().toArray(trimmedGroups)); request.setSecurityGroupIds(Arrays.asList(trimmedGroups)); } /** * Creates a new EMR master group object from request. * * @param namespaceCd, the namespace Code * @param clusterDefinitionName, the cluster definition name * @param clusterName, the cluster name * @param groupIds, the List of groupId * * @return the created EMR master group object */ private EmrMasterSecurityGroup createEmrClusterMasterGroupFromRequest(String namespaceCd, String clusterDefinitionName, String clusterName, List<String> groupIds) { // Create the EMR cluster. EmrMasterSecurityGroup emrMasterSecurityGroup = new EmrMasterSecurityGroup(); emrMasterSecurityGroup.setNamespace(namespaceCd); emrMasterSecurityGroup.setEmrClusterDefinitionName(clusterDefinitionName); emrMasterSecurityGroup.setEmrClusterName(clusterName); emrMasterSecurityGroup.setSecurityGroupIds(groupIds); return emrMasterSecurityGroup; } /** * Runs oozie job on an existing EMR Cluster. Creates its own transaction. * * @param request the Run oozie workflow request * * @return the oozie workflow job that was submitted. * @throws Exception if there were any errors while submitting the job. */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public OozieWorkflowJob runOozieWorkflow(RunOozieWorkflowRequest request) throws Exception { return runOozieWorkflowImpl(request); } /** * Runs oozie job on an existing EMR Cluster. * * @param request the Run oozie workflow request * * @return the oozie workflow job that was submitted. * @throws Exception if there were any errors while submitting the job. */ protected OozieWorkflowJob runOozieWorkflowImpl(RunOozieWorkflowRequest request) throws Exception { // Perform the request validation. validateRunOozieWorkflowRequest(request); String namespace = request.getNamespace(); String emrClusterDefinitionName = request.getEmrClusterDefinitionName(); String emrClusterName = request.getEmrClusterName(); ClusterSummary clusterSummary = getRunningOrWaitingEmrCluster(namespace, emrClusterDefinitionName, emrClusterName); String emrClusterPrivateIpAddress = getEmrClusterMasterIpAddress(clusterSummary.getId()); String jobId = oozieDao.runOozieWorkflow(emrClusterPrivateIpAddress, request.getWorkflowLocation(), request.getParameters()); OozieWorkflowJob oozieWorkflowJob = new OozieWorkflowJob(); oozieWorkflowJob.setId(jobId); oozieWorkflowJob.setNamespace(namespace); oozieWorkflowJob.setEmrClusterDefinitionName(emrClusterDefinitionName); oozieWorkflowJob.setEmrClusterName(emrClusterName); return oozieWorkflowJob; } /** * Get the EMR master private IP address. * * @param emrClusterId the cluster id * * @return the master node private IP address * @throws Exception Exception */ private String getEmrClusterMasterIpAddress(String emrClusterId) throws Exception { AwsParamsDto awsParamsDto = emrHelper.getAwsParamsDto(); return emrDao.getEmrMasterInstance(emrClusterId, awsParamsDto).getPrivateIpAddress(); } /** * Get the cluster in RUNNING or WAITING status. * * @param namespace namespace * @param emrClusterDefinitionName emrClusterDefinitionName * @param emrClusterName emrClusterName * * @return ClusterSummary */ private ClusterSummary getRunningOrWaitingEmrCluster(String namespace, String emrClusterDefinitionName, String emrClusterName) { // Get the namespace and ensure it exists. NamespaceEntity namespaceEntity = dmDaoHelper.getNamespaceEntity(namespace); // Get the EMR cluster definition and ensure it exists. EmrClusterDefinitionEntity emrClusterDefinitionEntity = dmDaoHelper.getEmrClusterDefinitionEntity(namespace, emrClusterDefinitionName); String clusterName = emrHelper.buildEmrClusterName(namespaceEntity.getCode(), emrClusterDefinitionEntity.getName(), emrClusterName); // Look up cluster ClusterSummary clusterSummary = emrDao.getActiveEmrClusterByName(clusterName, emrHelper.getAwsParamsDto()); // We can only run oozie job when the cluster is up (RUNNING or WAITING). Can not submit job otherwise like bootstraping. // Make sure that cluster exists and is in RUNNING or WAITING state. if (clusterSummary == null || !(clusterSummary.getStatus().getState().equalsIgnoreCase("RUNNING") || clusterSummary.getStatus().getState().equalsIgnoreCase("WAITING"))) { throw new ObjectNotFoundException(String.format("Either the cluster \"%s\" does not exist or not in RUNNING or WAITING state.", clusterName)); } return clusterSummary; } /** * Get the oozie workflow. Starts a new transaction. * * @param namespace the namespace * @param emrClusterDefinitionName the EMR cluster definition name * @param emrClusterName the EMR cluster name * @param oozieWorkflowJobId the ooxie workflow Id. * @param verbose the flag to indicate whether to return verbose information * * @return OozieWorkflowJob OozieWorkflowJob * @throws Exception Exception */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public OozieWorkflowJob getEmrOozieWorkflowJob(String namespace, String emrClusterDefinitionName, String emrClusterName, String oozieWorkflowJobId, Boolean verbose) throws Exception { return getEmrOozieWorkflowJobImpl(namespace, emrClusterDefinitionName, emrClusterName, oozieWorkflowJobId, verbose); } /** * Get the oozie workflow. * * @param namespace the namespace * @param emrClusterDefinitionName the EMR cluster definition name * @param emrClusterName the EMR cluster name * @param oozieWorkflowJobId the ooxie workflow Id. * @param verbose the flag to indicate whether to return verbose information * * @return OozieWorkflowJob OozieWorkflowJob * @throws Exception Exception */ protected OozieWorkflowJob getEmrOozieWorkflowJobImpl(String namespace, String emrClusterDefinitionName, String emrClusterName, String oozieWorkflowJobId, Boolean verbose) throws Exception { // Validate parameters Assert.isTrue(StringUtils.hasText(namespace), "Namespace is required"); Assert.isTrue(StringUtils.hasText(emrClusterDefinitionName), "EMR cluster definition name is required"); Assert.isTrue(StringUtils.hasText(emrClusterName), "EMR cluster name is required"); Assert.isTrue(StringUtils.hasText(oozieWorkflowJobId), "Oozie workflow job ID is required"); // Trim string parameters String namespaceTrimmed = namespace.trim(); String emrClusterDefinitionNameTrimmed = emrClusterDefinitionName.trim(); String emrClusterNameTrimmed = emrClusterName.trim(); String oozieWorkflowJobIdTrimmed = oozieWorkflowJobId.trim(); // Retrieve cluster's master instance IP ClusterSummary emrClusterSummary = getRunningOrWaitingEmrCluster(namespaceTrimmed, emrClusterDefinitionNameTrimmed, emrClusterNameTrimmed); String masterIpAddress = getEmrClusterMasterIpAddress(emrClusterSummary.getId()); // Retrieve the wrapper oozie workflow. This workflow is the workflow that DM wraps the client's workflow to help copy client workflow definition from // S3 to HDFS. WorkflowJob wrapperWorkflowJob = oozieDao.getEmrOozieWorkflow(masterIpAddress, oozieWorkflowJobIdTrimmed); // Check to make sure that the workflow job is a DM wrapper workflow. Assert.isTrue(wrapperWorkflowJob.getAppName().equals(OozieDaoImpl.DM_OOZIE_WRAPPER_WORKFLOW_NAME), "The oozie workflow with job ID '" + oozieWorkflowJobIdTrimmed + "' is not created by DM. Please ensure that the workflow was created through DM."); // Retrieve the client workflow's job action by navigating through the actions of the wrapper workflow. The client's workflow job ID is represented as // the action's external ID. WorkflowAction clientWorkflowAction = emrHelper.getClientWorkflowAction(wrapperWorkflowJob); WorkflowJob clientWorkflowJob = null; String clientWorkflowStatus = null; boolean hasClientWorkflowInfo = false; WorkflowAction errorWrapperWorkflowAction = null; /* * If the client workflow action is not found, there are three possibilities: * 1. DM_PREP: The client workflow has not yet been run. * 2. DM_FAILED : DM wrapper workflow failed to run successfully. * 3. If client workflow action is found but does not have the external ID, means that it failed to kick off the client workflow. Possible causes: * 3.1 workflow.xml is not present in the location provided. * 3.2 workflow.xml is not a valid workflow. */ if (clientWorkflowAction == null || clientWorkflowAction.getExternalId() == null) { // If wrapper workflow is FAILED/KILLED, means wrapper failed without running client workflow // else DM_PREP if (wrapperWorkflowJob.getStatus().equals(WorkflowJob.Status.KILLED) || wrapperWorkflowJob.getStatus().equals(WorkflowJob.Status.FAILED)) { clientWorkflowStatus = OozieDaoImpl.OOZIE_WORKFLOW_JOB_STATUS_DM_FAILED; // Get error information. errorWrapperWorkflowAction = emrHelper.getFirstWorkflowActionInError(wrapperWorkflowJob); } else { clientWorkflowStatus = OozieDaoImpl.OOZIE_WORKFLOW_JOB_STATUS_DM_PREP; } } else { // Retrieve the client workflow clientWorkflowJob = oozieDao.getEmrOozieWorkflow(masterIpAddress, clientWorkflowAction.getExternalId()); hasClientWorkflowInfo = true; } // Construct result OozieWorkflowJob resultOozieWorkflowJob = new OozieWorkflowJob(); resultOozieWorkflowJob.setId(oozieWorkflowJobId); resultOozieWorkflowJob.setNamespace(namespace); resultOozieWorkflowJob.setEmrClusterDefinitionName(emrClusterDefinitionName); resultOozieWorkflowJob.setEmrClusterName(emrClusterName); // If client workflow is information is not available that DM wrapper workflow has not started the client workflow yet or failed to start. // Hence return status that it is still in DM preparation. if (!hasClientWorkflowInfo) { resultOozieWorkflowJob.setStatus(clientWorkflowStatus); if (errorWrapperWorkflowAction != null) { resultOozieWorkflowJob.setErrorCode(errorWrapperWorkflowAction.getErrorCode()); resultOozieWorkflowJob.setErrorMessage(errorWrapperWorkflowAction.getErrorMessage()); } } else { resultOozieWorkflowJob.setStartTime(toXmlGregorianCalendar(clientWorkflowJob.getStartTime())); resultOozieWorkflowJob.setEndTime(toXmlGregorianCalendar(clientWorkflowJob.getEndTime())); resultOozieWorkflowJob.setStatus(clientWorkflowJob.getStatus().toString()); // Construct actions in the result if verbose flag is explicitly true, default to false if (Boolean.TRUE.equals(verbose)) { List<OozieWorkflowAction> oozieWorkflowActions = new ArrayList<>(); for (WorkflowAction workflowAction : clientWorkflowJob.getActions()) { OozieWorkflowAction resultOozieWorkflowAction = new OozieWorkflowAction(); resultOozieWorkflowAction.setId(workflowAction.getId()); resultOozieWorkflowAction.setName(workflowAction.getName()); resultOozieWorkflowAction.setStartTime(toXmlGregorianCalendar(workflowAction.getStartTime())); resultOozieWorkflowAction.setEndTime(toXmlGregorianCalendar(workflowAction.getEndTime())); resultOozieWorkflowAction.setStatus(workflowAction.getStatus().toString()); resultOozieWorkflowAction.setErrorCode(workflowAction.getErrorCode()); resultOozieWorkflowAction.setErrorMessage(workflowAction.getErrorMessage()); oozieWorkflowActions.add(resultOozieWorkflowAction); } resultOozieWorkflowJob.setWorkflowActions(oozieWorkflowActions); } } return resultOozieWorkflowJob; } /** * Builds the {@link XMLGregorianCalendar} for the given {@link Date} * * @param date date * * @return XMLGregorianCalendar */ private XMLGregorianCalendar toXmlGregorianCalendar(Date date) { XMLGregorianCalendar result = null; if (date != null) { result = DmDateUtils.getXMLGregorianCalendarValue(date); } return result; } /** * Validates the run oozie workflow request. * * @param request the request. * * @throws IllegalArgumentException if any validation errors were found. */ private void validateRunOozieWorkflowRequest(RunOozieWorkflowRequest request) { // Validate required elements Assert.hasText(request.getNamespace(), "A namespace must be specified."); Assert.hasText(request.getEmrClusterDefinitionName(), "An EMR cluster definition name must be specified."); Assert.hasText(request.getEmrClusterName(), "An EMR cluster name must be specified."); Assert.hasText(request.getWorkflowLocation(), "An oozie workflow location must be specified."); // Validate that parameter names are there and not duplicate dmHelper.validateParameters(request.getParameters()); // Remove leading and trailing spaces. request.setNamespace(request.getNamespace().trim()); request.setEmrClusterDefinitionName(request.getEmrClusterDefinitionName().trim()); request.setEmrClusterName(request.getEmrClusterName().trim()); } /** * Handles the AmazonServiceException, throws corresponding exception based on status code in amazon exception. */ private void handleAmazonException(AmazonServiceException ex, String message) throws IllegalArgumentException, ObjectNotFoundException { if (ex.getStatusCode() == HttpStatus.SC_BAD_REQUEST) { throw new IllegalArgumentException(message + " Reason: " + ex.getMessage(), ex); } else if (ex.getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new ObjectNotFoundException(message + " Reason: " + ex.getMessage(), ex); } throw ex; } }
48701dcbff4f93431896e2801ddfb546d333bae7
79415d7fc801c74f483c04a7a0e68fb223b8cfb3
/Index.java
1a22518766090d1e0d455cc42d2e5a07919f002b
[]
no_license
ragavivasudevan-cse/ragavivasu
8c8275712cdf1aa2107a1c733bd71ab8d88fef4b
87f0b04a9ac56e1656e376297dc3f154cb912531
refs/heads/master
2021-01-17T18:35:52.003562
2017-08-22T17:47:33
2017-08-22T17:47:33
71,537,569
0
1
null
null
null
null
UTF-8
Java
false
false
487
java
package guvi; import java.util.Scanner; public class Index { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } for(int i=0;i<n;i++){ if(i==a[i]){ System.out.println(a[i]); } } sc.close(); } }
adbf3f73241ee9aab6bd54f2bd5c510da374e69e
a7c0637c5c0e4b5b1016357ff314519165bb6231
/integration-test/src/main/java/org/apache/storm/st/topology/window/TimeDataIncrementingSpout.java
8b061d7339bc059d875d332320b12e42c6d5d492
[ "Apache-2.0", "GPL-1.0-or-later", "BSD-3-Clause", "MIT", "BSD-2-Clause" ]
permissive
MeninaChimp/storm
60800e6d2ebfce5c51282a44cb3a0f2402230381
53d13997b3a8d0bc3a52e0ef45418e4308de8bb3
refs/heads/master
2020-03-31T04:49:44.291639
2018-10-05T21:08:18
2018-10-05T21:08:18
151,921,311
1
0
Apache-2.0
2018-10-07T08:35:49
2018-10-07T08:35:49
null
UTF-8
Java
false
false
2,591
java
/* * Copyright 2018 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.storm.st.topology.window; import java.util.Map; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.st.topology.TestableTopology; import org.apache.storm.st.topology.window.data.TimeData; import org.apache.storm.st.utils.StringDecorator; import org.apache.storm.st.utils.TimeUtil; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.tuple.Values; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TimeDataIncrementingSpout extends BaseRichSpout { private static final Logger LOG = LoggerFactory.getLogger(TimeDataIncrementingSpout.class); private SpoutOutputCollector collector; private int currentNum; private String componentId; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(TimeData.getFields()); } @Override public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) { componentId = context.getThisComponentId(); this.collector = collector; } @Override public void nextTuple() { //Emitting too quickly can lead to spurious test failures because the worker log may roll right before we read it //Sleep a bit between emits TimeUtil.sleepMilliSec(ThreadLocalRandom.current() .nextInt(TestableTopology.MIN_SLEEP_BETWEEN_EMITS_MS, TestableTopology.MAX_SLEEP_BETWEEN_EMITS_MS)); currentNum++; TimeData data = TimeData.newData(currentNum); final Values tuple = data.getValues(); collector.emit(tuple); LOG.info(StringDecorator.decorate(componentId, data.toString())); } }
c7d7f39678a6f7ae0658c2b8fa8013ae3bde0464
92a4f92535287bb654b0851c545ace2cde373b0a
/app/src/main/java/com/jahanzaib/themoviedb/apicalls/usecase/GetTopRatedMoviesUseCase.java
b75d7ccd71a62e32eb5f91e1a423397d633cc742
[]
no_license
JahanZaibHafeez/TDMB-Application
4d84b13b9376e7bce347564113c7a66d082c335b
fb30757e26202b84fe207adca4c4200795769801
refs/heads/master
2021-01-21T11:31:03.614244
2017-08-31T13:50:02
2017-08-31T13:50:02
102,005,437
0
0
null
null
null
null
UTF-8
Java
false
false
1,757
java
package com.jahanzaib.themoviedb.apicalls.usecase; import com.jahanzaib.themoviedb.apicalls.BaseUseCase; import com.jahanzaib.themoviedb.apicalls.BaseUseCaseCallback; import com.jahanzaib.themoviedb.apicalls.entitymodel.MovieEntity; import com.jahanzaib.themoviedb.apicalls.service.API; import com.jahanzaib.themoviedb.apicalls.service.response.GetTopRatedMoviesResponse; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Created by progr on 29/08/2017. */ public class GetTopRatedMoviesUseCase extends BaseUseCase { public interface GetTopRatedMoviesUseCaseCallback extends BaseUseCaseCallback { void onMoviesSearched(List<MovieEntity> movieEntities); } private String apiKey; public GetTopRatedMoviesUseCase(String apiKey, GetTopRatedMoviesUseCase.GetTopRatedMoviesUseCaseCallback callback) { super(callback); this.apiKey = API.API_KEY; } @Override public void onRun() throws Throwable { API.http().topRatedMovies(apiKey, new Callback<GetTopRatedMoviesResponse>() { @Override public void success(GetTopRatedMoviesResponse topRatedMovieResponse, Response response) { ((GetTopRatedMoviesUseCase.GetTopRatedMoviesUseCaseCallback) callback).onMoviesSearched(topRatedMovieResponse.getResults()); } @Override public void failure(RetrofitError error) { if (error.getKind() == RetrofitError.Kind.NETWORK) { errorReason = NETWORK_ERROR; } else { errorReason = error.getResponse().getReason(); } onCancel(); } }); } }
ad8e908793d6c38ff015cfb02e4828aca17a1e4b
f666b4220961b708c527af67b4972af258cd03a8
/src/Planet.java
0b2e9a9b1a631c9ea81d84598101ccdfb9f9f3d4
[]
no_license
Manolo947/PracticeExercise
e022da024fe6133318388cc72202a3d47d6a21e9
3ccf8acee280a1a9e82695ceedf79fdb8b114ef7
refs/heads/master
2020-07-25T04:20:58.716661
2019-09-12T20:18:07
2019-09-12T20:18:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,440
java
public class Planet { private String name; private double distance; // in light-years private double radius; // in kilometers private int population; /* * Create a constructor that uses the given parameters. * A planet has a 5% chance of having alien life. * In case of alien life, population is random. */ public Planet(String name, double distance, double radius) { // Your code here } /* * Creates an identical planet to the one given. */ public Planet(Planet planet) { // Your code here } public boolean equals(Object e) { if(e instanceof Planet && ((Planet) e).name.equals(this.name)) return true; return false; } // Getters public String getName() { return this.name; } public double getDistance() { return this.distance; } public double getRadius() { return this.radius; } public int getPopulation() { return this.population; } /* * Write a method that indicates if there is alien life or not. */ public boolean alienLife() { // Your code here return false; } /* * Write a method that returns the distance in miles: * 1 light year is approximately 5.88e12 miles */ public double getDistanceMiles() { // Your code here return 0.0; } /* * Assuming the planets are perfect spheres, return the volume * of the planet. * V = 4/3 * pi * r^3 */ public double getVolume() { // Your code here return 0.0; } /* * Create a method that returns true if the calling Planet is * bigger and false otherwise */ public boolean isBigger(Planet planet) { // Your code here return false; } /* * A civilization has come to colonize the planet! If the planet * already has alien life, a war will break out. The planet * with the bigger population will win, but their population will * be reduced by 50%. In the case the populations are equal, * no one will survive. If the planet is vacant, all of the * incoming population will move in. */ public void colonize(int incomingPopulation) { // Your code here } /* * Create a method where there's a 50/50 chance of a population * boom or decrease. Either double or cut the population by half */ public void populationEvent() { // Your code here } /* * Return the planet as a string * Ex: Planet Jupiter */ public String toString() { // Your code here return null; } public static void main(String[] args) { } }
1626ef94af1fb2910d3cf28201327268d18506ad
b162956df616b70d3adb53293b751e757e6b6202
/src/main/java/WanZhuanShuJuJieGou/Arrays/AddElementInArray03/Main.java
d336ef6c8fa511ad30c50831f11ca9d578087c4f
[]
no_license
bijiaha0/leetcode-practice
a200418e341a24e40853bd6ec521a69191b03221
3d72dfaff05ef64cf555a2df5259903aecdd1b69
refs/heads/master
2020-12-10T04:12:19.715015
2020-01-13T03:08:36
2020-01-13T03:08:36
233,496,869
1
0
null
2020-10-13T18:48:41
2020-01-13T02:42:35
Java
UTF-8
Java
false
false
132
java
package WanZhuanShuJuJieGou.Arrays.AddElementInArray03; public class Main { public static void main(String[] args) { } }
aaa923758ce8a38dbb12f9ab0419a3b07b77076b
3cfb49672d87d53c82ad97fdb4b13f4e97c3a00a
/webservice/src/main/java/com/futuretech/webservice/WebserviceApplication.java
ec9693861fbfbebffff5b2a7442a24672f637757
[]
no_license
MoreEndeavor/changzheng
b12131a32cc03163a6c859ed32b9dc090e0623f7
dfbee2bfbe20bc8c035d42813a44e90b16e9848d
refs/heads/master
2023-02-06T17:37:48.983942
2020-12-16T14:33:02
2020-12-16T14:33:02
322,008,671
0
0
null
null
null
null
UTF-8
Java
false
false
338
java
package com.futuretech.webservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebserviceApplication { public static void main(String[] args) { SpringApplication.run(WebserviceApplication.class, args); } }