blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
b11a06e1a5924e5f3c3854413f6fade2cfd6c4fd
Java
jiangweiming/demo
/storm-demo/src/main/java/org/skywing/demo/storm/TopologyRunner.java
UTF-8
1,343
2.3125
2
[]
no_license
package org.skywing.demo.storm; import java.net.URL; import org.skywing.demo.storm.bolt.WordCounter; import org.skywing.demo.storm.bolt.WordNormalizer; import org.skywing.demo.storm.spout.WordReader; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; public class TopologyRunner { public static void main(String[] args) throws InterruptedException { //Topology definition TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("word-reader", new WordReader()); builder.setBolt("word-normalizer", new WordNormalizer()).shuffleGrouping("word-reader"); builder.setBolt("word-counter", new WordCounter(), 2).fieldsGrouping("word-normalizer", new Fields("word")); //Configuration Config conf = new Config(); URL url = TopologyRunner.class.getResource("/words.txt"); conf.put("wordsFile", url.getPath()); conf.setDebug(false); //Topology run conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("started-example", conf, builder.createTopology()); Thread.sleep(1000); cluster.shutdown(); /* StormSubmitter submitter = new StormSubmitter(); submitter.submitTopology("started-example", conf, builder.createTopology()); */ } }
true
93d3643f4e7ccac565de93a8507055b855978b9a
Java
murthy98/Corporateclassifieds
/authmicroservice/src/test/java/com/cts/authmicroservice/controller/UserControllerTest.java
UTF-8
1,962
2.15625
2
[]
no_license
package com.cts.authmicroservice.controller; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.userdetails.UserDetails; import com.cts.authmicroservice.jwt.JwtUtil; import com.cts.authmicroservice.model.AuthResponse; import com.cts.authmicroservice.model.UserModel; import com.cts.authmicroservice.model.UserToken; import com.cts.authmicroservice.repository.UserRepository; import com.cts.authmicroservice.service.UserServiceImpl; import static org.mockito.Mockito.when; @SpringBootTest public class UserControllerTest { @InjectMocks UserController userController; AuthResponse authResponse; UserDetails userdetails; @Mock JwtUtil jwtutil; @Mock UserServiceImpl userServiceImpl; @Mock UserRepository userRepository; @Test public void loginTest() { UserModel userLoginCredentials = new UserModel(1,"admin","admin"); UserToken userToken= new UserToken("token","admin",1); when(userServiceImpl.login(userLoginCredentials)).thenReturn(userToken); assertEquals(userController.login(userLoginCredentials).getBody(),userToken); } @Test public void validityTest() { AuthResponse auth = new AuthResponse("admin", 1, true); ResponseEntity<AuthResponse> response = new ResponseEntity<>(auth,HttpStatus.OK); when(userServiceImpl.getValidity("bearer token")).thenReturn(auth); assertEquals(userController.getValidity("bearer token"),response); } @Test public void getEmpIdTest() { UserModel user=new UserModel(1,"admin","admin"); when(userServiceImpl.getEmpId("admin")).thenReturn(user.getEmpid()); assertEquals(userController.getEmpId("admin"),1); } }
true
8144450a0a30ba26c21f58de9f69f076c643d25c
Java
AlexVel76/springBoot-SpringWS-REST
/src/main/java/com/epam/htsa/restconvertor/Ticket2PdfMessageConverter.java
UTF-8
1,479
2.5
2
[]
no_license
package com.epam.htsa.restconvertor; import com.epam.htsa.entity.Ticket; import com.google.common.collect.Lists; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import java.io.IOException; public class Ticket2PdfMessageConverter extends AbstractHttpMessageConverter<Object> { public Ticket2PdfMessageConverter() { super(new MediaType("application","pdf")); } @Override protected boolean supports(Class<?> clazz) { return clazz.isInstance(Ticket.class); } @Override protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return super.read(clazz, inputMessage); } @Override protected void writeInternal(Object t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { outputMessage.getHeaders().setAccept(Lists.newArrayList(new MediaType("application", "pdf"))); writeInternal(t, outputMessage); } @Override protected boolean canRead(MediaType mediaType) { return false; } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return super.canWrite(clazz, mediaType); } }
true
471fd12502ede315dab40ea0f2e06e7031e6f348
Java
Separd-ui/SnapShip
/app/src/main/java/com/example/snapship/Adapters/PhotoAdapter.java
UTF-8
2,427
2.28125
2
[]
no_license
package com.example.snapship.Adapters; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.RecyclerView; import com.example.snapship.Fragments.HomeFragment; import com.example.snapship.Fragments.PostDetailFragment; import com.example.snapship.R; import com.example.snapship.Uttils.Post; import com.squareup.picasso.Picasso; import java.util.ConcurrentModificationException; import java.util.List; public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ViewHolderData> { private Context context; private List<Post> postList; public PhotoAdapter(Context context, List<Post> postList) { this.context = context; this.postList = postList; } @NonNull @Override public PhotoAdapter.ViewHolderData onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.image_item,parent,false); return new ViewHolderData(view); } @Override public void onBindViewHolder(@NonNull PhotoAdapter.ViewHolderData holder, int position) { holder.setData(postList.get(position)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor=context.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit(); editor.putString("postKey",postList.get(position).getKey()); editor.apply(); ((FragmentActivity)context).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new PostDetailFragment()).commit(); } }); } @Override public int getItemCount() { return postList.size(); } public class ViewHolderData extends RecyclerView.ViewHolder { ImageView img_post; public ViewHolderData(@NonNull View itemView) { super(itemView); img_post=itemView.findViewById(R.id.img_adapter); } private void setData(Post post) { Picasso.get().load(post.getImageid()).into(img_post); } } }
true
9ad02cc4b7b67d3175cbc4056bfe5450d2b42eae
Java
chadYeo/Anime-TV
/app/src/main/java/com/example/chadyeo/animetv/api/Anime.java
UTF-8
5,061
2.421875
2
[]
no_license
package com.example.chadyeo.animetv.api; import java.io.Serializable; import java.util.ArrayList; public class Anime implements Serializable { private int id; private String title_english; private String title_romaji; private String title_japanese; private String description; private String source; // Source (Manga, Light novel etc.) private ArrayList<String> genres; private ArrayList<String> synonyms; private int start_date_fuzzy; private int end_date_fuzzy; private ArrayList<Studio> studio; private double average_score; private int popularity; private String type; //Movie, TV Short, TV etc. private int season; private int total_episodes; private int total_chapters; private int total_volume; private int duration; private String youtube_id; private String image_url_sml; private String image_url_med; private String image_url_lge; private String image_url_banner; public String getType() { return type; } public void setType(String type) { this.type = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle_english() { return title_english; } public void setTitle_english(String title_english) { this.title_english = title_english; } public String getTitle_romaji() { return title_romaji; } public void setTitle_romaji(String title_romaji) { this.title_romaji = title_romaji; } public String getTitle_japanese() { return title_japanese; } public void setTitle_japanese(String title_japanese) { this.title_japanese = title_japanese; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public ArrayList<String> getGenres() { return genres; } public void setGenres(ArrayList<String> genres) { this.genres = genres; } public double getAverage_score() { return average_score; } public void setAverage_score(double average_score) { this.average_score = average_score; } public int getPopularity() { return popularity; } public void setPopularity(int popularity) { this.popularity = popularity; } public int getSeason() { return season; } public void setSeason(int season) { this.season = season; } public int getTotal_episodes() { return total_episodes; } public void setTotal_episodes(int total_episodes) { this.total_episodes = total_episodes; } public int getTotal_chapters() { return total_chapters; } public void setTotal_chapters(int total_chapters) { this.total_chapters = total_chapters; } public int getTotal_volume() { return total_volume; } public void setTotal_volume(int total_volume) { this.total_volume = total_volume; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public String getYoutube_id() { return youtube_id; } public void setYoutube_id(String youtube_id) { this.youtube_id = youtube_id; } public String getImage_url_sml() { return image_url_sml; } public void setImage_url_sml(String image_url_sml) { this.image_url_sml = image_url_sml; } public String getImage_url_med() { return image_url_med; } public void setImage_url_med(String image_url_med) { this.image_url_med = image_url_med; } public String getImage_url_lge() { return image_url_lge; } public void setImage_url_lge(String image_url_lge) { this.image_url_lge = image_url_lge; } public String getImage_url_banner() { return image_url_banner; } public void setImage_url_banner(String image_url_banner) { this.image_url_banner = image_url_banner; } public ArrayList<String> getSynonyms() { return synonyms; } public void setSynonyms(ArrayList<String> synonyms) { this.synonyms = synonyms; } public ArrayList<Studio> getStudio() { return studio; } public void setStudio(ArrayList<Studio> studio) { this.studio = studio; } public int getStart_date_fuzzy() { return start_date_fuzzy; } public void setStart_date_fuzzy(int start_date_fuzzy) { this.start_date_fuzzy = start_date_fuzzy; } public int getEnd_date_fuzzy() { return end_date_fuzzy; } public void setEnd_date_fuzzy(int end_date_fuzzy) { this.end_date_fuzzy = end_date_fuzzy; } }
true
6f690e1cd6d9bd12a622105e1347973ac80f25ca
Java
EphramWang/SBHMS
/usbSerialExamples/src/main/java/com/hoho/android/usbserial/chart/TempMonChart.java
UTF-8
9,752
2.203125
2
[ "MIT" ]
permissive
package com.hoho.android.usbserial.chart; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import com.hoho.android.usbserial.examples.DataConstants; import com.hoho.android.usbserial.examples.R; import com.hoho.android.usbserial.model.PressureDataPack; import com.hoho.android.usbserial.model.VoltageDataPack; import com.hoho.android.usbserial.util.Utils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import androidx.annotation.Nullable; public class TempMonChart extends ChartBase { public static final int TEMP_COUNT = 2;//温度数量 Path[] pathList = { new Path(), new Path(), new Path() }; int[] colorList = {R.color.battery1, R.color.battery2, R.color.battery3, R.color.battery4, R.color.battery5, R.color.battery6}; public TempMonChart(Context context) { super(context); } public TempMonChart(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public TempMonChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private ArrayList<VoltageDataPack> voltageDataList; private ArrayList<PressureDataPack> pressureDataList; @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //draw backgroud paint.setAntiAlias(false); paint.setStyle(Paint.Style.FILL); paint.setColor(getResources().getColor(R.color.bgDark)); canvas.drawRect(mainRect, paint); //draw line paint.setStyle(Paint.Style.STROKE); paint.setColor(getResources().getColor(R.color.bgLight)); float center = (mainRect.top + mainRect.bottom) / 2f; canvas.drawLine(mainRect.left, center, mainRect.right, center, paint);; //reset paths for (int i = 0; i < pathList.length; i++) { pathList[i].reset(); } //reset maxmin int maxT = DataConstants.TEMP_MIN; int minT = DataConstants.TEMP_MAX; float x = mainRect.right; float y = (mainRect.top + mainRect.bottom) / 2f; float xDiff = mainRect.width() / (mCount - 1); if (voltageDataList != null) { for (int i = voltageDataList.size() - 1; i >= 0; i--) { VoltageDataPack voltageDataPack = voltageDataList.get(i); for (int j = 0; j < TEMP_COUNT; j++) { int data = voltageDataPack.tempListDisplay[j]; if (data < minT) { minT = data; } if (data > maxT) { maxT = data; } } x = x - xDiff; if (x < mainRect.left) { break; } } if (minT > maxT) { minT = DataConstants.TEMP_MIN; maxT = DataConstants.TEMP_MAX; } x = mainRect.right; for (int i = voltageDataList.size() - 1; i >= 0; i--) { VoltageDataPack voltageDataPack = voltageDataList.get(i); for (int j = 0; j < TEMP_COUNT; j++) { y = mainRect.top + mainRect.height() * (maxT - voltageDataPack.tempListDisplay[j]) / (maxT - minT); if (pathList[j].isEmpty()) { pathList[j].moveTo(x, y); } else { pathList[j].lineTo(x, y); } } x = x - xDiff; if (x < mainRect.left) { break; } } } float maxP = DataConstants.PRESSURE_MIN; float minP = DataConstants.PRESSURE_MAX; if (pressureDataList != null) { x = mainRect.right; for (int i = pressureDataList.size() - 1; i >= 0; i--) { PressureDataPack pressureDataPack = pressureDataList.get(i); float data = pressureDataPack.pressureDisplay; if (data < minP) { minP = data; } if (data > maxP) { maxP = data; } x = x - xDiff; if (x < mainRect.left) { break; } } if (minP > maxP) { minP = DataConstants.PRESSURE_MIN; maxP = DataConstants.PRESSURE_MAX; } x = mainRect.right; for (int i = pressureDataList.size() - 1; i >= 0; i--) { PressureDataPack pressureDataPack = pressureDataList.get(i); y = mainRect.top + mainRect.height() * (maxP - pressureDataPack.pressureDisplay) / (maxP - minP); if (pathList[2].isEmpty()) { pathList[2].moveTo(x, y); } else { pathList[2].lineTo(x, y); } x = x - xDiff; if (x < mainRect.left) { break; } } } for (int j = 0; j < 3; j++) { paint.setColor(getResources().getColor(colorList[j])); paint.setStrokeWidth(2); canvas.drawPath(pathList[j], paint); } //draw legend paint.setStyle(Paint.Style.FILL); paint.setColor(getResources().getColor(R.color.textColorDark)); paint.setAntiAlias(true); paint.setTextSize(Utils.dp2px(getContext(), 12)); paint.setTextAlign(Paint.Align.LEFT); canvas.drawText(maxT + "°C", mainRect.left, mainRect.top + Utils.dp2px(getContext(), 12), paint); canvas.drawText(minT + "°C", mainRect.left, mainRect.bottom - Utils.dp2px(getContext(), 12), paint); canvas.drawText((maxT + minT) / 2 + "°C", mainRect.left, center, paint); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText(maxP + "Bar", mainRect.right, mainRect.top + Utils.dp2px(getContext(), 12), paint); canvas.drawText(minP + "Bar", mainRect.right, mainRect.bottom - Utils.dp2px(getContext(), 12), paint); canvas.drawText((maxP + minP) / 2 + "Bar", mainRect.right, center, paint); if (voltageDataList.size() > 0) { try { long lastTime = voltageDataList.get(voltageDataList.size() - 1).timestamp; long firstTime; if (voltageDataList.size() <= mCount) { firstTime = voltageDataList.get(0).timestamp; } else { firstTime = voltageDataList.get(voltageDataList.size() - mCount).timestamp; } String strDateFormat = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat); paint.setTextAlign(Paint.Align.RIGHT); canvas.drawText(sdf.format(new Date(lastTime)), mainRect.right, mainRect.bottom - Utils.dp2px(getContext(), 0), paint); paint.setTextAlign(Paint.Align.LEFT); canvas.drawText(sdf.format(new Date(firstTime)), mainRect.left, mainRect.bottom - Utils.dp2px(getContext(), 0), paint); } catch (Exception e) { } } //draw touch line if (mIsDrawLine) { paint.setColor(Color.WHITE); canvas.drawLine(mTouchLineX, mainRect.top, mTouchLineX, mainRect.bottom, paint); } } public void setVoltageDataList(ArrayList<VoltageDataPack> voltageDataList) { this.voltageDataList = voltageDataList; postInvalidate(); } public void setPressureDataList(ArrayList<PressureDataPack> pressureDataList) { this.pressureDataList = pressureDataList; postInvalidate(); } private int getIndexByX(float x) { float xDiff = mainRect.width() / (mCount - 1); float num = x / xDiff; return Math.round(num); } @Override public void onLongPressUp(float x, float y) { super.onLongPressUp(x, y); try { mTouchCallBack.onTouch(voltageDataList.get(voltageDataList.size() - 1), pressureDataList.get(pressureDataList.size() - 1)); } catch (Exception e) { } } @Override public void onLongPressMove(float x, float y) { super.onLongPressMove(x, y); VoltageDataPack voltageDataPack = null; PressureDataPack pressureDataPack = null; try { int index = voltageDataList.size() - mCount + getIndexByX(x); voltageDataPack = voltageDataList.get(index); } catch (Exception e) { } try { int index2 = pressureDataList.size() - mCount + getIndexByX(x); pressureDataPack = pressureDataList.get(index2); } catch (Exception e) { } mTouchCallBack.onTouch(voltageDataPack, pressureDataPack); } @Override public void onLongPressDown(float x, float y) { super.onLongPressDown(x, y); VoltageDataPack voltageDataPack = null; PressureDataPack pressureDataPack = null; try { int index = voltageDataList.size() - mCount + getIndexByX(x); voltageDataPack = voltageDataList.get(index); } catch (Exception e) { } try { int index2 = pressureDataList.size() - mCount + getIndexByX(x); pressureDataPack = pressureDataList.get(index2); } catch (Exception e) { } mTouchCallBack.onTouch(voltageDataPack, pressureDataPack); } }
true
51012ffbe0bb7c9e0e3c67cc3eea872d746bd1c0
Java
Fighting-Lee/fastjgame
/game-reload/src/test/java/com/wjybxx/fastjgame/reload/ClassReloadTest.java
UTF-8
1,707
2.21875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 wjybxx * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wjybxx.fastjgame.reload; import com.sun.tools.attach.VirtualMachine; import com.wjybxx.fastjgame.reload.mgr.ClassReloadMgr; import java.lang.management.ManagementFactory; /** * @author wjybxx * @version 1.0 * date - 2020/11/30 * github - https://github.com/hl845740757 */ public class ClassReloadTest { /** * 请在启动参数中添加 -Djdk.attach.allowAttachSelf=true * 否则抛出 java.io.IOException: Can not attach to current VM 异常。 */ public static void main(String[] args) throws Exception { startClassReloadAgent(); final ClassReloadMgr classReloadMgr = new ClassReloadMgr("game-reload/target", "classes"); classReloadMgr.reloadAll(); } /** * 启动热更新代理组件 */ private static void startClassReloadAgent() throws Exception { final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; final VirtualMachine vm = VirtualMachine.attach(pid); // jar包必须放在可加载路径 vm.loadAgent("./game-libs/game-classreloadagent-1.0.jar"); } }
true
236823c91d689080fec07e45b284cb08fe3552ea
Java
xsm535820171/ContentProviderProject
/app/src/main/java/com/my/contentprovider/MainActivity.java
UTF-8
7,385
2.296875
2
[]
no_license
package com.my.contentprovider; 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.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.lidroid.xutils.view.annotation.event.OnClick; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * ContentProvider:不同应用程序之间进行数据交换的标准API,ContentProvider以某种Uri的形式对外提供数据, * 允许其他应用访问和修改数据;其他应用程序使用ContentProvider根据Uri去访问指定的数据。 由于是四大组件之一,需要在清单文件中配置。。 API:Application Programming Interface ,,应用程序编程接口 Uri:Uniform Resource Identifier,统一资源标识符;是一个用于标识某一互联网资源名称的字符串。 由于不同的应用程序记录数据的方式差别很大,使用SharedPreferences、文件或数据库不利于应用程序间进行数据交换 完整开发一个ContentProvider的步骤: 1、定义自己的ContentProvider类,该类需要继承Android提供的ContentProvider基类; 2、在清单文件AndroidManifest.xml中,注册ContentProvider,就像注册Activity一样。 注册ContentProvider时需要为他绑定一个域名; 通过ContentResolver操作ContentProvider暴露的数据的步骤: 1、调用Activity的getContentResolver()获取ContentResolver对象; 2、调用ContentResolver的方法操作数据 insert(Uri uri,ContentValues contentvalues):向Uri对应的ContentProvider中插入contentvalues数据 delete(Uri uri,String where,String[] selectionArgs):删除Uri对应的ContentProvider中where提交匹配的数据 update(Uri uri,ContentValues contentvalues,String where,String[] selectionArgs):更新Uri对应的 ContentProvider中where提交匹配的数据 query(Uri uri,String[] projection,String where,String[] selectionArgs,String sortOrder): 查询Uri对应的ContentProvider中where提交匹配的数据 一般来说ContentProvider是单例模式, */ public class MainActivity extends AppCompatActivity { ContentResolver contentResolver; @ViewInject(R.id.word_et) EditText word_et; @ViewInject(R.id.detail_et) EditText detail_et; @ViewInject(R.id.search_et) EditText search_et; @OnClick({R.id.add_bt,R.id.other_bt,R.id.search_bt,R.id.update_bt,R.id.delete_bt,R.id.seleteall_bt}) public void OnCLick(View view){ switch (view.getId()){ case R.id.add_bt: Uri uri=Uri.parse("content://com.my.peoviderword/word"); String add_text = word_et.getText().toString(); String detail_text = detail_et.getText().toString(); ContentValues contentValues=new ContentValues(); contentValues.put("word",add_text); contentValues.put("detail",detail_text); contentResolver.insert(uri,contentValues); //第一种方法添加数据 // insertData(myDatabaseHelper.getReadableDatabase(),add_text,detail_text); word_et.setText(""); detail_et.setText(""); Toast.makeText(this,"添加成功",Toast.LENGTH_LONG).show(); //第二种方法添加数据 // ContentValues contentValues=new ContentValues(); // contentValues.put("word",add_text); // contentValues.put("detail",detail_text); // myDatabaseHelper.getReadableDatabase().insert("dict",null,contentValues); break; case R.id.search_bt: String search=search_et.getText().toString(); Uri uri1=Uri.parse("content://com.my.peoviderword/words"); Cursor cursor=contentResolver.query(uri1,null,"word like ? or detail like ?",new String[]{"%"+search+"%","%"+search+"%"},null); Bundle bundle=new Bundle(); bundle.putSerializable("key",convertCursorToList(cursor)); Intent intent=new Intent(MainActivity.this,MyDatabaseList.class); intent.putExtras(bundle); startActivity(intent); Toast.makeText(this,"查找成功,欧耶",Toast.LENGTH_LONG).show(); // queryData(myDatabaseHelper.getReadableDatabase(),search); break; case R.id.update_bt: String add_text1 = word_et.getText().toString(); String detail_text1 = detail_et.getText().toString(); Uri uri2=Uri.parse("content://com.my.peoviderword/words"); ContentValues contentValues1=new ContentValues(); contentValues1.put("detail",detail_text1); contentResolver.update(uri2,contentValues1,"word=?",new String[]{add_text1}); Toast.makeText(this,"修改成功,欧耶",Toast.LENGTH_LONG).show(); // updateData(myDatabaseHelper.getReadableDatabase(),add_text1,detail_text1); break; case R.id.delete_bt: String word=search_et.getText().toString(); Uri uri3=Uri.parse("content://com.my.peoviderword/words"); contentResolver.delete(uri3,"word=?",new String[]{word}); Toast.makeText(this,"删除成功,欧耶",Toast.LENGTH_LONG).show(); // deleteData(myDatabaseHelper.getReadableDatabase(),word); break; case R.id.seleteall_bt: // queryAllData(myDatabaseHelper.getReadableDatabase()); Uri uri4=Uri.parse("content://com.my.peoviderword/words"); Cursor cursor1=contentResolver.query(uri4,null,null,null,null); Bundle bundle1=new Bundle(); bundle1.putSerializable("key",convertCursorToList(cursor1)); Intent intent1=new Intent(MainActivity.this,MyDatabaseList.class); intent1.putExtras(bundle1); startActivity(intent1); Toast.makeText(this,"查找所有,欧耶",Toast.LENGTH_LONG).show(); case R.id.other_bt: // Intent intent=new Intent(this, DbUtilesActivity.class); // startActivity(intent); default: break; } } @Override protected void onCreate(Bundle savedInstanceState) { contentResolver=getContentResolver(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewUtils.inject(this); contentResolver=getContentResolver(); } public ArrayList<Map<String,String>> convertCursorToList(Cursor cursor){ ArrayList<Map<String ,String>> result=new ArrayList<Map<String ,String>>(); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put("word",cursor.getString(1)); map.put("detail",cursor.getString(2)); result.add(map); } return result; } }
true
0363847401c194cc5fc7473382b57f3dc8e5a4ba
Java
adambarron15/SoulSaver
/src/dev/SoulSaver/entities/creatures/Enemies/LaserBeam.java
UTF-8
2,207
2.65625
3
[]
no_license
package dev.SoulSaver.entities.creatures.Enemies; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import dev.SoulSaver.Handler; import dev.SoulSaver.creatures.NPC; import dev.SoulSaver.entities.EntityManager; import dev.SoulSaver.gfx.Assets; import dev.SoulSaver.utils.CreaturesUtil; public class LaserBeam extends NPC { private int rotation; private boolean left, right; private BufferedImage image; public LaserBeam(Handler handler, float x, float y, int world,boolean left, boolean right) { super(handler, x, y, 1f, false, 100); timer.Start(); this.world=world; this.left=left; this.right=right; setAnimation(world); } @Override public void action() { xMove = 0; yMove = 0; if (this.getCollisionBounds(0f, 0f).intersects(handler.getWorld().getEntityManager().getPlayer().getRectangle()) && timer.run(.8f)) { handler.getWorld().getEntityManager().getPlayer().hurt(); timer.Start(); } if (CreaturesUtil.dist(EntityManager.getPlayer().getX() + 32, EntityManager.getPlayer().getY() + 32, x + 32, y + 32) > 100) { active=false; } } public void setPosition(){ if(left || right){ rotation=90; }else { rotation=0; } } public void setAnimation(int world) { switch (world) { case 1: // Maze image = Assets.sandLaser; break; case 2: // Fire-ice image = Assets.iceLaser; break; case 3: // Swamp break; case 4: // Mansion image = Assets.pictureLaser; break; case 5: // Ship image = Assets.cannonLaser; break; case 6: // Dungeon image = Assets.dungeonLaser; break; case 7: // Forest image = Assets.treeLaser; break; case 8: // Sky image = Assets.rainLaser; break; case 9: //Digital image = Assets.digitalLaser; break; } } @Override public void tick(){ action(); move(); } @Override public void render(Graphics2D g) { AffineTransform at=AffineTransform.getTranslateInstance((int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset())); at.rotate(Math.toRadians(rotation)); at.scale(2, 2); g.drawImage(image,at,null); } }
true
04d9a1ac8b9176fb40ef30c2fc7a57e1a9001b77
Java
olamonir/DaryClean
/app/src/main/java/com/example/ola/dryclean/Adapters/UserAddressesRecyclerView.java
UTF-8
2,793
2.21875
2
[]
no_license
package com.example.ola.dryclean.Adapters; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.ola.dryclean.Activites.DryDetailsActivity; import com.example.ola.dryclean.Objects.UserInfo; import com.example.ola.dryclean.R; import java.util.List; /** * Created by ola on 1/28/2017. */ public class UserAddressesRecyclerView extends RecyclerView.Adapter<UserAddressesRecyclerView.MyViewHolder> { private Typeface diwanMuna ; private final Activity context; private Typeface geDinarTwoLight ; private List<UserInfo.ResultBean.DataBean.AddressesBean> data; public UserAddressesRecyclerView(Activity context, List<UserInfo.ResultBean.DataBean.AddressesBean> list){ this.context = context; this.data=list ; this.diwanMuna = Typeface.createFromAsset(this.context.getAssets(), "fonts/DiwanMuna.ttf"); this.geDinarTwoLight = Typeface.createFromAsset(this.context.getAssets(), "fonts/ge-dtwol.otf"); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.add_new_add_list_item, parent, false); itemView.setOnClickListener(new UserAddressesRecyclerView.MyOnClickListener()); return new UserAddressesRecyclerView.MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.tvTitle.setText(String.valueOf(data.get(position).getAddress())); holder.tvTitle.setTypeface(geDinarTwoLight); } @Override public int getItemCount() { return data.size(); } class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.clickContainer: Intent intent = new Intent(context , DryDetailsActivity.class); context.startActivity(intent); Toast.makeText(context ,"mmmmm" ,Toast.LENGTH_SHORT).show(); break; // int itemPosition = recyclerView.indexOfChild(v); // Log.e("Clicked and Position is ",String.valueOf(itemPosition)); } } } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView tvTitle; public MyViewHolder(View view) { super(view); tvTitle = (TextView) view.findViewById(R.id.text_title); } } }
true
a89aeab8b156aac970145020eaef19683e3b5b20
Java
NikiHard/cuddly-pancake
/sources/p035ru/unicorn/ujin/data/profile/repository/ProfileRemoteRepository$requestRegister2core$1.java
UTF-8
1,648
1.6875
2
[]
no_license
package p035ru.unicorn.ujin.data.profile.repository; import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import p035ru.unicorn.ujin.data.api.response.authorization.Register2coreResponseData; import p035ru.unicorn.ujin.data.realm.Resource; import p046io.reactivex.functions.Function; @Metadata(mo51341bv = {1, 0, 3}, mo51342d1 = {"\u0000\u000e\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\u0010\u0000\u001a\u0016\u0012\u0004\u0012\u00020\u0002 \u0003*\n\u0012\u0004\u0012\u00020\u0002\u0018\u00010\u00010\u00012\f\u0010\u0004\u001a\b\u0012\u0004\u0012\u00020\u00020\u0001H\n¢\u0006\u0002\b\u0005"}, mo51343d2 = {"<anonymous>", "Lru/unicorn/ujin/data/realm/Resource;", "Lru/unicorn/ujin/data/api/response/authorization/Register2coreResponseData;", "kotlin.jvm.PlatformType", "data", "apply"}, mo51344k = 3, mo51345mv = {1, 4, 1}) /* renamed from: ru.unicorn.ujin.data.profile.repository.ProfileRemoteRepository$requestRegister2core$1 */ /* compiled from: ProfileRemoteRepository.kt */ final class ProfileRemoteRepository$requestRegister2core$1<T, R> implements Function<Resource<Register2coreResponseData>, Resource<Register2coreResponseData>> { public static final ProfileRemoteRepository$requestRegister2core$1 INSTANCE = new ProfileRemoteRepository$requestRegister2core$1(); ProfileRemoteRepository$requestRegister2core$1() { } public final Resource<Register2coreResponseData> apply(Resource<Register2coreResponseData> resource) { Intrinsics.checkNotNullParameter(resource, "data"); return Resource.success(resource.getError(), resource.getMessage(), resource.getData()); } }
true
210c9af75f8e7424db88a9399e69ff0c7a19f160
Java
designreuse/motour
/motour-core/src/main/java/club/motour/loader/CodeMetaLoader.java
UTF-8
640
1.734375
2
[]
no_license
package club.motour.loader; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.sylksoft.ss3a.loader.PreLoader; import club.motour.model.CodeMeta; import club.motour.service.CodeMetaService; import club.motour.util.CodeMetaUtils; @Component("codeMetaLoader") public class CodeMetaLoader implements PreLoader { @Autowired CodeMetaService codeMetaService; @Override public void load() { List<CodeMeta> list = codeMetaService.getAllCodeMeta(); CodeMetaUtils.getInstance().reloadCodeMetaMap(list); } }
true
6bfe7157463499356669e7d7d4a2acabca992b26
Java
AuroraBenitez/orca-sys-backend
/src/main/java/com/orca/orca_sys/model/FondoCapital.java
UTF-8
1,327
1.90625
2
[]
no_license
package com.orca.orca_sys.model; import java.util.Date; public class FondoCapital { private Integer codigo; private String descripcion; private Integer monto; private String tipo; private Date fecha; private String usuario; private String estado; private String observacion; public Integer getCodigo() { return codigo; } public void setCodigo(Integer codigo) { this.codigo = codigo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Integer getMonto() { return monto; } public void setMonto(Integer monto) { this.monto = monto; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public String getObservacion() { return observacion; } public void setObservacion(String observacion) { this.observacion = observacion; } }
true
35e97957371873ad1a30f0eeae58f865115c29e9
Java
universAAL/samples
/tutorials/tut.service.bus.caller/src/main/java/org/universAAL/tutorials/service/bus/caller/Activator.java
UTF-8
3,039
2.234375
2
[ "Apache-2.0" ]
permissive
/* Copyright 2016-2020 Carsten Stockloew See the NOTICE file distributed with this work for additional information regarding copyright ownership 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.universAAL.tutorials.service.bus.caller; import org.universAAL.middleware.container.ModuleActivator; import org.universAAL.middleware.container.ModuleContext; import org.universAAL.middleware.service.DefaultServiceCaller; import org.universAAL.middleware.service.ServiceCaller; import org.universAAL.middleware.service.ServiceRequest; import org.universAAL.ontology.device.LightActuator; import org.universAAL.ontology.device.ValueDevice; import org.universAAL.ontology.phThing.DeviceService; /** * The module activator handles the starting and stopping of this module. It is * similar to the OSGi BundleActivator. * * In our case, we simply want to call a service, so we do this directly in the * start method. * * @author Carsten Stockloew */ public class Activator implements ModuleActivator { public void start(ModuleContext mc) throws Exception { // Create the service caller ServiceCaller caller = new DefaultServiceCaller(mc); // Create a service request to turn on a light source. The requested // service (a subclass of 'Service', here: DeviceService) acts as 'entry // point' in the ontology. Starting from this class we go along some // property path and describe what the service should do/return and // what input parameters we provide at that path. // In this tutorial, we request a service that can turn on a light // source (= setting the value of a LightActuator to 100%) ServiceRequest turnOn = new ServiceRequest(new DeviceService(), null); // We add a value filter: at the path 'controls' the value must be a // specific light actuator. All other operations (e.g. change effects or // return values) only operate on those filtered instances. turnOn.addValueFilter(new String[] { DeviceService.PROP_CONTROLS }, new LightActuator("urn:org.universAAL.space:KitchenLight")); // We add a change effect: at the path 'controls-hasValue' the service // should change the value to 100 turnOn.addChangeEffect(new String[] { DeviceService.PROP_CONTROLS, ValueDevice.PROP_HAS_VALUE }, new Integer(100)); // Now call the service caller.call(turnOn); // Close our service caller and free all resources. The caller // should be re-used if multiple calls need to be made. caller.close(); } public void stop(ModuleContext arg0) throws Exception { } }
true
5b1edee205f20d74cbb0d1f84f4874da43eda0a1
Java
ningzhao/P04
/src/main/java/structuralPatterns/bridgePattern/Shape.java
UTF-8
326
2.484375
2
[]
no_license
package structuralPatterns.bridgePattern; /** * Created by Ning on 4/11/18. */ public abstract class Shape { DrawImplementor impl; public abstract void draw(); // 22 public abstract void resize(int factor); // 33 how about adding more and more features? // ResizeImplementor resizeImplementor; }
true
ccc6250199e9ad396838658524f8bf5214399a6f
Java
moutainhigh/myRepository
/pl/rondaful-supplier-service/src/main/java/com/rondaful/cloud/supplier/vo/WareHouseAuthorizeVO.java
UTF-8
1,760
2.09375
2
[]
no_license
package com.rondaful.cloud.supplier.vo; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * * @author songjie * */ @ApiModel(description = "授权对像VO") public class WareHouseAuthorizeVO implements Serializable { @ApiModelProperty(value = "主键id") private Integer id; @ApiModelProperty(value = "自定义名称") private String customName; @ApiModelProperty(value = "appKey") private String appKey; @ApiModelProperty(value = "appToken") private String appToken; @ApiModelProperty(value = "服务商id") private Integer serviceId; @ApiModelProperty(value = "[0=停用,1=启用,2删除]") private Integer status; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCustomName() { return customName; } public void setCustomName(String customName) { this.customName = customName == null ? null : customName.trim(); } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey == null ? null : appKey.trim(); } public String getAppToken() { return appToken; } public void setAppToken(String appToken) { this.appToken = appToken == null ? null : appToken.trim(); } public Integer getServiceId() { return serviceId; } public void setServiceId(Integer serviceId) { this.serviceId = serviceId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
true
794d377b3c4b63d02a1e84abc796cb55b7c4c44c
Java
a0248327/JSF2.2
/JSF2.2/mygourmet-fullstack/mygourmet-webapp/src/main/java/at/irian/jsfatwork/gui/util/CdiUtil.java
UTF-8
645
2.046875
2
[]
no_license
package at.irian.jsfatwork.gui.util; import org.apache.myfaces.extensions.cdi.core.api.provider.BeanManagerProvider; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import java.util.Set; /** * */ public class CdiUtil { public static <T> T resolveBean(Class<T> clazz) { BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(clazz); Bean<?> bean = beanManager.resolve(beans); return (T)beanManager.getReference(bean, clazz, beanManager.createCreationalContext(bean)); } }
true
9764a7321ab646292eeeafa9d660d3d7f2298a89
Java
filpaw/kulki
/src/main/java/sample/Ball.java
UTF-8
1,298
3.15625
3
[]
no_license
package sample; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import static sample.Board.SIZE; public class Ball extends StackPane { private final BallType type; private double mouseX, mouseY; private double oldX, oldY; public BallType getType() { return type; } public double getOldY() { return oldY; } public double getOldX() { return oldX; } public Ball(BallType type, int col, int row) { this.type = type; move(col, row); Circle circle = new Circle(SIZE / 3.5); circle.setFill(Color.valueOf(String.valueOf(type))); circle.setTranslateX((SIZE - SIZE / 3.5 * 2) / 2); circle.setTranslateY((SIZE - SIZE / 3.5 * 2) / 2); getChildren().add(circle); setOnMousePressed(e -> { mouseX = e.getSceneX(); mouseY = e.getSceneY(); }); setOnMouseDragged(e -> { relocate(e.getSceneX() - mouseX + oldX, e.getSceneY() - mouseY + oldY); }); } public void move(int col, int row) { oldX = col * SIZE; oldY = row * SIZE; relocate(oldX, oldY); } public void abortMove() { relocate(oldX, oldY); } }
true
9c6f556f9a27e8d4eef326b3d30362d3c9a77018
Java
dstmath/OppoR15
/app/src/main/java/java/nio/file/ClosedFileSystemException.java
UTF-8
161
1.578125
2
[]
no_license
package java.nio.file; public class ClosedFileSystemException extends IllegalStateException { static final long serialVersionUID = -8158336077256193488L; }
true
70b3f570cb9520e650700bef7b3906d6211b2c4e
Java
league-level4-student/level4-module1-JoeJoePotato
/src/_03_Switch_Statement_Practice/CustomButtonOptionPanes.java
UTF-8
1,505
4.125
4
[]
no_license
package _03_Switch_Statement_Practice; import javax.swing.JOptionPane; public class CustomButtonOptionPanes { public static void main(String[] args) { String[] options = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int input = JOptionPane.showOptionDialog(null, "Choose a day of the week", "Custom Buttons", 0, -1, null, options, 0); String choice = options[input]; //use a switch statement to do something cool for each option switch(choice) { case "Sunday": System.out.println("Sorry, but the churches are closed due to COVID19. I hope God understands."); break; case "Monday": System.out.println("Don't mention today's name to Garfield. He might go beserk."); break; case "Tuesday": System.out.println("Isn't it weird to not physically be at school at this poiint in the week?"); break; case "Wedneday": System.out.println("By now youv'e probably adjusted to the new scedules."); break; case "Thursday": System.out.println("You ate five snickers bars during class today. Probably because your desk is next to the pantry now."); break; case "Friday": System.out.println("In a normal school week, you'd rejoice at the coming of the weekend. But your still home all day, so there is very little difference."); break; case "Saturday": System.out.println("Somehow, Saturday no longer feels mystical. You don't have to go to school, but you weren't all week anyways."); break; } } }
true
00ff5a4ea61c97b1201fe30c11ac957300ec83e1
Java
magefree/mage
/Mage/src/main/java/mage/filter/common/FilterArtifactOrEnchantmentCard.java
UTF-8
776
2.359375
2
[ "MIT" ]
permissive
package mage.filter.common; import mage.constants.CardType; import mage.filter.FilterCard; import mage.filter.predicate.Predicates; /** * @author TheElk801 */ public class FilterArtifactOrEnchantmentCard extends FilterCard { public FilterArtifactOrEnchantmentCard() { this("artifact or enchantment card"); } public FilterArtifactOrEnchantmentCard(String name) { super(name); this.add(Predicates.or(CardType.ARTIFACT.getPredicate(), CardType.ENCHANTMENT.getPredicate())); } protected FilterArtifactOrEnchantmentCard(final FilterArtifactOrEnchantmentCard filter) { super(filter); } @Override public FilterArtifactOrEnchantmentCard copy() { return new FilterArtifactOrEnchantmentCard(this); } }
true
6c0f416b581d7b1d0110d430c7eb3c1630567358
Java
hacjy/LibCommon
/app/src/main/java/com/ha/cjy/libcommon/test/GameViewPagerViewActivity.java
UTF-8
1,470
1.984375
2
[]
no_license
package com.ha.cjy.libcommon.test; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.FrameLayout; import com.ha.cjy.common.ui.base.BaseToolbarActivity; import com.ha.cjy.common.util.ToolbarFactory; import com.ha.cjy.libcommon.R; /** * 测试:默认的ViewPager视图:3个tab项 * Created by cjy on 2018/7/18. */ public class GameViewPagerViewActivity extends BaseToolbarActivity { private FrameLayout mLayoutContent; private GameViewPager mViewPager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_viewpager); } @Override public void initDataBeforeView() { } @Override public void initData() { } @Override public void initView() { mLayoutContent = findViewById(R.id.game_viewpager); mViewPager = new GameViewPager(GameViewPagerViewActivity.this); mLayoutContent.addView(mViewPager); } @Override public void initListener() { } @Override public View getContentView() { return mViewPager; } @Override protected void initToolbar() { ToolbarFactory.initLeftBackToolbar(GameViewPagerViewActivity.this,"","我的游戏列表"); } @Override protected int getToolbarLayout() { return R.layout.default_toolbar_layout; } }
true
9bd6a69366aec39c18cfb5ec458427556f8b440a
Java
MihaelMihov/ClockApplication
/src/com/company/MyFrame.java
UTF-8
1,651
3.359375
3
[]
no_license
package com.company; import javax.swing.*; import java.awt.*; import java.text.SimpleDateFormat; import java.util.Calendar; public class MyFrame extends JFrame { SimpleDateFormat timeFormat; SimpleDateFormat dayFormat; JLabel timeLabel; String time; JLabel dateLabel; String date; MyFrame() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Nice clock to track the time..."); this.setLayout(new FlowLayout()); this.setSize(450, 195); this.setResizable(false); this.setVisible(true); timeFormat = new SimpleDateFormat("kk : mm : ss"); timeLabel = new JLabel(); timeLabel.setFont(new Font("Times New Roman", Font.PLAIN, 80)); timeLabel.setForeground(new Color(0x00FF00)); timeLabel.setBackground(Color.black); timeLabel.setOpaque(true); dayFormat = new SimpleDateFormat("dd-MM-yyyy, EEEE :)"); dateLabel = new JLabel(); dateLabel.setFont(new Font("Arial", Font.PLAIN, 35)); dateLabel.setForeground(new Color(0xFF0000)); this.add(timeLabel); this.add(dateLabel); this.setVisible(true); setTime(); } public void setTime() { while (true) { time = timeFormat.format(Calendar.getInstance().getTime()); timeLabel.setText(time); date = dayFormat.format(Calendar.getInstance().getTime()); dateLabel.setText(date); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
true
6fa6a121d95283358f73bb0f361f842d81dd1a7b
Java
mukhtiarahmed/rest-example
/src/main/java/com/hackerrank/assignment/security/JwtAuthorizationTokenFilter.java
UTF-8
3,679
2.40625
2
[ "Apache-2.0" ]
permissive
package com.hackerrank.assignment.security; import com.hackerrank.assignment.dto.UserDTO; import com.hackerrank.assignment.service.UserService; import io.jsonwebtoken.ExpiredJwtException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; /** * @author mukhtiar.ahmed * @version 1.0 */ @Component public class JwtAuthorizationTokenFilter extends OncePerRequestFilter { private static Logger log = LoggerFactory.getLogger(JwtAuthorizationTokenFilter.class); @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserService userService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { log.debug("processing authentication for '{}'", request.getRequestURL()); final String requestTokenHeader = request.getHeader("Authorization"); String userName = null; String jwtToken = null; if (StringUtils.isNotEmpty(requestTokenHeader) && requestTokenHeader.startsWith("Bearer ")) { jwtToken = requestTokenHeader.substring(7); try { userName = jwtTokenUtil.getUsernameFromToken(jwtToken); } catch (IllegalArgumentException e) { log.error("an error occurred during getting username from token", e); } catch (ExpiredJwtException e) { log.warn("the token is expired and not valid anymore", e); } } else { log.warn("couldn't find bearer string, will ignore the header"); log.warn("JWT Token does not begin with Bearer String"); } // Once we get the token validate it. if (StringUtils.isNotEmpty(userName) && SecurityContextHolder.getContext().getAuthentication() == null) { UserDTO user = userService.getUserDTOByUserName(userName); // if token is valid configure Spring Security to manually set // authentication if (user != null && jwtTokenUtil.validateToken(jwtToken, user)) { String role = user.getRole(); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( user, null, Arrays.asList(new SimpleGrantedAuthority(role))); usernamePasswordAuthenticationToken .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // After setting the Authentication in the context, we specify // that the current user is authenticated. So it passes the // Spring Security Configurations successfully. SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } chain.doFilter(request, response); } }
true
d53d63d6c348052891a21955322eb61fbd1bec62
Java
kanthima/projectevefinal
/app/src/main/java/com/example/eve/myapplication/MeAdapter.java
UTF-8
1,639
2.3125
2
[]
no_license
package com.example.eve.myapplication; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by eve on 11/29/2015. */ public class MeAdapter extends BaseAdapter { //Explicit private Context objContext; private String[] nameStrings,countStrings; public MeAdapter(String[] countStrings, Context objContext, String[] nameStrings) { this.countStrings = countStrings; this.objContext = objContext; this.nameStrings = nameStrings; }//Constructor @Override public int getCount() { return nameStrings.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View v, ViewGroup viewGroup) { LayoutInflater objLayoutInflater = (LayoutInflater) objContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View objView1 = objLayoutInflater.inflate(R.layout.activity_history2, viewGroup, false); TextView nameTextView = (TextView) objView1.findViewById(R.id.textView17); nameTextView.setText( nameStrings[i]); TextView countTextView = (TextView) objView1.findViewById(R.id.textView18); countTextView.setText("จำนวนครั้งที่เลี้ยง "+countStrings[i]); return objView1; } }//main class
true
b978fa6f34edb4a641a91e3126f9d3b31c133903
Java
CarlosAndres20/NinosOutLimits
/src/java/Model/Asignatura.java
UTF-8
827
2.296875
2
[]
no_license
/* * 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 Model; /** * * @author Usuario */ public class Asignatura { private int id_Asignaturas; private int id_Juegos ; private String Nombre ; public int getId_Asignaturas() { return id_Asignaturas; } public void setId_Asignaturas(int id_Asignaturas) { this.id_Asignaturas = id_Asignaturas; } public int getId_Juegos() { return id_Juegos; } public void setId_Juegos(int id_Juegos) { this.id_Juegos = id_Juegos; } public String getNombre() { return Nombre; } public void setNombre(String Nombre) { this.Nombre = Nombre; } }
true
904298d2a612daa659beda0a99c1da944f0b4552
Java
qvaibhavpatil/Playground
/Sum of first and last digit/Main.java
UTF-8
403
3.046875
3
[]
no_license
import java.util.Scanner; class Main { public static void main (String[] args){ // Type your code here Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //System.out.println(n); int x = n%10; while (n >= 10) { n=n/10; } int l = n%10; //System.out.println(l); int sum = l+x; System.out.println(sum); } }
true
f35c1a0c6e52869d6403cbde0713c238e59b3baa
Java
kenthewala/codechef
/codechef/src/codechef/ATM.java
UTF-8
748
2.96875
3
[]
no_license
package codechef; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class ATM { public static void main(String s[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String input = br.readLine(); String[] Arrinput = input.split("\\s"); int withdrawalAmount = Integer.parseInt(Arrinput[0]); float accountBalance = Float.parseFloat(Arrinput[1]); if((withdrawalAmount<accountBalance-0.50) && (withdrawalAmount%5==0)) { accountBalance -= withdrawalAmount+0.50; } pw.printf("%3.2f",accountBalance); pw.close(); br.close(); } }
true
4fe92bebd6b062ed061f73a1d6e9fa28f00d99f1
Java
cxlnnhy/onetwo
/core/modules/common/src/test/java/org/onetwo/common/utils/SimpleTest.java
UTF-8
1,696
1.882813
2
[ "Apache-2.0" ]
permissive
package org.onetwo.common.utils; import static org.junit.Assert.assertEquals; import java.util.Date; import org.joda.time.DateTime; import org.junit.Test; import org.onetwo.common.date.DateUtils; import org.onetwo.common.date.NiceDate; public class SimpleTest { @Test public void test(){ Date date = NiceDate.New().nextMinute(1).getTime(); System.out.println(date.getTime()); String str1 = "iid=22878612236&device_id=46503731872&ac=wifi&channel=meizu&aid=32&app_name=video_article&version_code=627&version_name=6.2.7&device_platform=android&ab_version=249703%2C221019%2C236847%2C241077%2C249883%2C249510%2C248462%2C229578%2C235216%2C249817%2C249631%2C235963%2C250931%2C236030%2C239019%2C247773%2C252404%2C235684%2C249824%2C249815%2C252010%2C252594%2C249830%2C248257%2C150151&ssmix=a&device_type=m3+note&device_brand=Meizu&language=zh&os_api=22&os_version=5.1&uuid=862143030676147&openudid=70fc30601792caf7&manifest_version_code=227&resolution=1080*1920&dpi=480&update_version_code=6272&_rticket=1515583161361"; String str2 = "iid=22878612236&device_id=46503731872&ac=wifi&channel=meizu&aid=32&app_name=video_article&version_code=627&version_name=6.2.7&device_platform=android&ab_version=249703%2C221019%2C236847%2C241077%2C249883%2C249510%2C248462%2C229578%2C235216%2C249817%2C249631%2C235963%2C250931%2C236030%2C239019%2C247773%2C252404%2C235684%2C249824%2C249815%2C252010%2C252594%2C249830%2C248257%2C150151&ssmix=a&device_type=m3+note&device_brand=Meizu&language=zh&os_api=22&os_version=5.1&uuid=862143030676147&openudid=70fc30601792caf7&manifest_version_code=227&resolution=1080*1920&dpi=480&update_version_code=6272&_rticket=1515583400989"; assertEquals(str1, str2); } }
true
07b2f6d74f794d8605aa43c94ca7c8949d88f946
Java
Ayafathy3/Sakan
/app/src/main/java/com/aya/sakan/ui/search/SearchActivity.java
UTF-8
1,756
1.78125
2
[]
no_license
package com.aya.sakan.ui.search; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.aya.sakan.R; import com.aya.sakan.ui.addPost.AddPostActivity; import com.aya.sakan.ui.home.HomeActivity; import com.aya.sakan.util.Data; import com.google.android.material.tabs.TabLayout; import com.reginald.editspinner.EditSpinner; import java.util.ArrayList; import java.util.List; public class SearchActivity extends AppCompatActivity { private TextView title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); addFragment(new SearchFragment()); setListeners(); } private void setListeners() { title = findViewById(R.id.title); title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(SearchActivity.this, HomeActivity.class)); finishAffinity(); } }); } public void addFragment(Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.add(R.id.container, fragment); transaction.commit(); } }
true
a87e414f0c53eab87413a029a8dd8d9ecebb5a6d
Java
HAHOOS/CraftBlocker
/CraftBlocker/src/plugin/hahoos/pl/API/PlayerTryCraft.java
UTF-8
1,237
2.4375
2
[]
no_license
package plugin.hahoos.pl.API; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.inventory.ItemStack; public class PlayerTryCraft extends Event implements Cancellable { Player p; ItemStack i; boolean cancelled; public PlayerTryCraft(Player p, ItemStack i) { this.p = p; this.i = i; } public Player getPlayer() { return p; } public ItemStack getItem() { return i; } public void setCancelled(boolean bool) { this.cancelled = bool; } private static final HandlerList handlers = new HandlerList(); public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } public void onCraftEvent(CraftItemEvent event) { Bukkit.getPluginManager().callEvent(new PlayerTryCraft((Player)event.getWhoClicked(), event.getCurrentItem())); while(cancelled == false) { } } @Override public boolean isCancelled() { return this.cancelled; } }
true
2763cce7cab89b894d2bfac521609d2841fd1ebf
Java
google-code/badass-android
/android-app/src/fr/slvn/badass/activity/AboutActivity.java
UTF-8
1,020
2.40625
2
[]
no_license
package fr.slvn.badass; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class AboutActivity extends Activity implements OnClickListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); setTitle(getString(R.string.main_menu_about)); findViewById(R.id.about_book1).setOnClickListener(this); findViewById(R.id.about_book2).setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.about_book1: launchBrowsing(getString(R.string.url_badass_book)); break; case R.id.about_book2: launchBrowsing(getString(R.string.url_badass_legend)); break; } } private void launchBrowsing(String url) { Uri uriUrl = Uri.parse(url); startActivity(new Intent(Intent.ACTION_VIEW, uriUrl)); } }
true
94eead1ee48b20517768627923fbf3fedfa9e20f
Java
AliesYangpai/DesignMode
/lib_design_mode_create/src/main/java/com/alie/libdesignmodecreate/createmode/singleton/SingleInnerClass.java
UTF-8
590
2.84375
3
[]
no_license
package com.alie.libdesignmodecreate.createmode.singleton; /** * Created by Alie on 2019/7/6. * 内部类创建法: * 静态内部类的静态属性实例化的时候,jvm内部会自行控制线程安全;此方法与单锁双空发效果一直 * 版本 */ public class SingleInnerClass { private SingleInnerClass() { } private static class SingleInnerClassViewHolder { private static SingleInnerClass mInstance = new SingleInnerClass(); } public static SingleInnerClass getInstance() { return SingleInnerClassViewHolder.mInstance; } }
true
ad89e9e99fdd78a671935812941a6a73ce92f050
Java
FearlessGames/spaced
/ardorgui/src/main/java/se/ardorgui/lua/bindings/LuaKeyBindings.java
UTF-8
2,023
2.375
2
[]
no_license
package se.ardorgui.lua.bindings; import com.ardor3d.input.Key; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import se.ardortech.input.KeyListener; import se.fearless.common.lua.LuaVm; import se.krka.kahlua.integration.annotations.LuaMethod; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; @Singleton public class LuaKeyBindings implements KeyListener { private final LuaVm luaVm; private final Map<Key, Object> keyPressedBinds; private final Map<Key, Object> keyReleasedBinds; private final Set<Key> pressedKeys; @Inject public LuaKeyBindings(@Named("gui") LuaVm luaVm) { this.luaVm = luaVm; keyPressedBinds = new EnumMap<Key, Object>(Key.class); keyReleasedBinds = new EnumMap<Key, Object>(Key.class); pressedKeys = EnumSet.noneOf(Key.class); } @LuaMethod(global = true, name = "OnKeyDown") public void setKeyDownAction(String keyString, final Object action) { keyPressedBinds.put(Key.valueOf(keyString), action); } @LuaMethod(global = true, name = "OnKeyUp") public void setKeyUpAction(String keyString, final Object action) { keyReleasedBinds.put(Key.valueOf(keyString), action); } public void clearBinds() { keyPressedBinds.clear(); keyReleasedBinds.clear(); } @Override public boolean onKey(char character, Key keyCode, boolean pressed) { if (pressed) { pressedKeys.add(keyCode); Object action = keyPressedBinds.get(keyCode); if (action != null) { luaVm.luaCall(action, keyCode.name()); return true; } } else { pressedKeys.remove(keyCode); Object action = keyReleasedBinds.get(keyCode); if (action != null) { luaVm.luaCall(action, keyCode.name()); return true; } } return false; } @LuaMethod(name = "IsButtonDown", global = true) public boolean isButtonPressed(String keyString) { return pressedKeys.contains(Key.valueOf(keyString)); } }
true
b504a0e6cbb24c4b99e407a6dc928bcd8d50a0c2
Java
Mxxxxx/Java-SuanFa
/src/数组相关/二位数组递增.java
UTF-8
1,206
3.75
4
[]
no_license
package 数组相关; /** * @Author Meng Xin * @Date 2020/7/20 16:01 */ public class 二位数组递增 { //在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, // 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数, // 判断数组中是否含有该整数。 public boolean Find(int target, int[][] array) { if (array == null) { return false; } int i = 0; int j = array[0].length - 1; while (i < array.length && j >= 0) { if (target < array[i][j]) { //array[i][j]一定是当前行最大的,当前列最小的 //target < array[i][j],比当前列最小的还小,则当前列之后的不存在该值,排除当前列 j--; } else if (target > array[i][j]) { //target > array[i][j],比当前行最大的还大,则该行不存在该值,排除当前行 i++; } else { //找到 return true; } } return false; } }
true
a39cc017f4afd610a12416d361bf2f3f8d309eae
Java
FambaJava/CloudSystem
/Master/src/main/java/cloudsystem/command/commands/TestCommand.java
UTF-8
410
2.484375
2
[]
no_license
package cloudsystem.command.commands; import cloudsystem.command.listener.Command; public class TestCommand implements Command { @Override public void execute(String[] args) { if (args.length != 1) { for (String arg : args) { System.out.println(arg); } } else System.out.println("you need to type in more args then one."); } }
true
15e40ed8d3801c67f8256a3914747c539c7d3c8d
Java
yilylong/RXjavaDemo
/app/src/main/java/com/zhl/rx/entry/Platform.java
UTF-8
278
1.734375
2
[ "Apache-2.0" ]
permissive
package com.zhl.rx.entry; import com.zhl.rx.bean.ShangjiaAModule; import com.zhl.rx.bean.ZhaiNan; import dagger.Component; /** * 描述: * Created by zhaohl on 2018-5-29. */ @Component(modules = ShangjiaAModule.class) public interface Platform { ZhaiNan waimai(); }
true
c60252b62265ba1179dfaf43cc1451dd83fa9c0f
Java
nikosxenakis/ImagInLexis
/src/main/java/com/xenakis/application/ScreenPane.java
UTF-8
4,662
2.703125
3
[ "MIT" ]
permissive
package com.xenakis.application; import java.net.URL; import java.util.HashMap; import com.xenakis.ImagInLexis; import com.xenakis.service.TestService; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.beans.property.DoubleProperty; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.StackPane; import javafx.util.Duration; import com.xenakis.screenController.QuestionScreenController; import com.xenakis.screenController.ScreenController; import com.xenakis.screenData.QuestionScreenData; import com.xenakis.screenData.ScreenDataHolder; import org.apache.log4j.Logger; public class ScreenPane extends StackPane { private final Logger logger; //Holds the screens to be displayed private final HashMap<String, Node> screens = new HashMap<>(); private final HashMap<String, ScreenController> screenControllersList = new HashMap<>(); public ScreenPane() { super(); this.logger = Logger.getLogger(ScreenPane.class); } //Add the screen to the collection private void addScreen(String name, Node screen){ screens.put(name, screen); } //Returns the Node with the appropriate name public Node getScreen(String name){ return screens.get(name); } public ScreenController getController(String screenId){ ScreenController sc = screenControllersList.get(screenId); if(sc == null) logger.error("Controller of screen: " + screenId + " is null"); return sc; } private void addController(String screenId, ScreenController screenController) { logger.info("addController: "+screenId+" " + screenController); screenControllersList.put(screenId, screenController); } //Loads the com.xenakis.fxml file, add the screen to the screens collection and //finally injects the screenPane to the controller. public void loadScreen(String screenId, TestService testService){ try { String resource = ResourcePathsHolder.getResourcePaths(screenId); URL url = ImagInLexis.class.getResource(resource); FXMLLoader loader = new FXMLLoader(url); Parent loadScreen = loader.load(); ScreenController screenController = loader.getController(); screenController.setScreenPane(this); addController(screenId,screenController); addScreen(screenId, loadScreen); if(screenController instanceof QuestionScreenController){ QuestionScreenData screenData = ScreenDataHolder.getScreenData(screenId); ((QuestionScreenController)screenController).setData(screenData, testService); } } catch(Exception e){ logger.error(e.getMessage()); } } //This method tries to displayed the screen with a predefined name. //First it makes sure the screen has been already loaded. Then if there is more than //one screen the new screen is been added second, and then the current screen is removed. // If there isn't any screen being displayed, the new screen is just added to the root. public void setScreen(final String screenId){ if (screens.get(screenId) != null) { //screen loaded final DoubleProperty opacity = opacityProperty(); if (!getChildren().isEmpty()) { //if there is more than one screen Timeline fade = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)), new KeyFrame(new Duration(100), t -> { getChildren().remove(0); //remove the displayed screen getChildren().add(0, screens.get(screenId)); //add the screen Timeline fadeIn = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)), new KeyFrame(new Duration(100), new KeyValue(opacity, 1.0)) ); fadeIn.play(); }, new KeyValue(opacity, 0.0)) ); fade.play(); } else{ setOpacity(0.0); getChildren().add(screens.get(screenId)); //no one else been displayed, then just show Timeline fadeIn = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)), new KeyFrame(new Duration(200), new KeyValue(opacity, 1.0)) ); fadeIn.play(); } } else { logger.error("setScreen with screenId = " + screenId + " failed"); } } //This method will remove the screen with the given name from the collection of screens public void unloadScreen(String name){ if(screens.get(name) != null) screens.remove(name); } }
true
a10ae3785a653c2866074ae045b47fc1b81c2473
Java
bogdan-todorovic/synx
/src/main/java/rs/ac/uns/ftn/web/synx/model/Report.java
UTF-8
1,804
2.0625
2
[]
no_license
package rs.ac.uns.ftn.web.synx.model; import java.io.Serializable; import java.util.Date; import rs.ac.uns.ftn.web.synx.util.ReportDecree; public class Report implements Serializable { private static final long serialVersionUID = 3141571559237090248L; private String id; private String content; private Date creationDate; private String author; private String subforum; private String topic; private String comment; private ReportDecree decree; public Report() {} public Report(String content, Date creationDate, String author, String subforum, String topic, String comment, ReportDecree decree) { super(); this.content = content; this.creationDate = creationDate; this.author = author; this.subforum = subforum; this.topic = topic; this.comment = comment; this.decree = decree; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getSubforum() { return subforum; } public void setSubforum(String subforum) { this.subforum = subforum; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public ReportDecree getDecree() { return decree; } public void setDecree(ReportDecree decree) { this.decree = decree; } }
true
ee97f306125b948ab3f8a8b4f3b829082cbe6e3b
Java
asmisloff/InterviewTraining
/ht01/src/main/java/Person.java
UTF-8
1,484
2.765625
3
[]
no_license
import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class Person { private String firstName; private String lastName; private String middleName; private String country; private String address; private String phone; private int age; private String gender; private Person() { firstName = ""; lastName = ""; middleName = ""; country = ""; address = ""; phone = ""; age = 0; gender = ""; } public static Person createInstance() { return new Person(); } public Person withFirstName(String firstName) { this.firstName = firstName; return this; } public Person withLastName(String lastName) { this.lastName = lastName; return this; } public Person withMiddleName(String middleName) { this.middleName = middleName; return this; } public Person withCountry(String country) { this.country = country; return this; } public Person withAddress(String address) { this.address = address; return this; } public Person withPhone(String phone) { this.phone = phone; return this; } public Person withAge(int age) { this.age = age; return this; } public Person withGender(String gender) { this.gender = gender; return this; } }
true
263532d04ba6091d9cdf5ee80f1cedc7a711323c
Java
CarbonStudiosSTR/CarbonWebPlay
/carbonWebApp/src/main/java/com/carbonstr/spring/controller/RegisterController.java
UTF-8
1,246
2.296875
2
[]
no_license
package com.carbonstr.spring.controller; import com.carbonstr.spring.model.Account; import com.carbonstr.spring.service.RegisterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class RegisterController { private RegisterService registerService; @Autowired(required = true) @Qualifier(value = "registerService") public void setPersonService(RegisterService ps) { this.registerService = ps; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String register(Model model) { model.addAttribute("account", new Account()); return "register"; } @RequestMapping(value = "/register/create", method = RequestMethod.POST) public String createAccount(@ModelAttribute("account") Account a) { this.registerService.registerAccount(a); return "redirect:/sign_in"; } }
true
d5e91619dd08df9d0bc5d12443a40e4ca4fceae9
Java
Hsly-XiaoWen/springbootDemo
/src/main/java/com/juemuren/config/ds/TdSqlSessionTemplate.java
UTF-8
14,514
2.03125
2
[]
no_license
package com.juemuren.config.ds; import com.alibaba.druid.pool.DruidAbstractDataSource; import com.alibaba.druid.pool.DruidPooledConnection; import org.apache.ibatis.cursor.Cursor; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.executor.BatchResult; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.StatementType; import org.apache.ibatis.session.*; import org.mybatis.spring.MyBatisExceptionTranslator; import org.mybatis.spring.SqlSessionTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.dao.support.PersistenceExceptionTranslator; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.List; import java.util.Map; import static java.lang.reflect.Proxy.newProxyInstance; import static org.apache.ibatis.reflection.ExceptionUtil.unwrapThrowable; import static org.mybatis.spring.SqlSessionUtils.*; /** * 为了解决存储过程报错, 导致事务没有正常关闭, 并且数据库连接被重复使用导致事务卡死的问题 */ public class TdSqlSessionTemplate extends SqlSessionTemplate { private static final Logger logger = LoggerFactory.getLogger(TdSqlSessionTemplate.class); private final SqlSessionFactory sqlSessionFactory; private final ExecutorType executorType; private final SqlSession sqlSessionProxy; private final PersistenceExceptionTranslator exceptionTranslator; public TdSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { this(sqlSessionFactory, sqlSessionFactory.getConfiguration().getDefaultExecutorType()); } public TdSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType) { this(sqlSessionFactory, executorType, new MyBatisExceptionTranslator( sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true)); } public TdSqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { super(sqlSessionFactory, executorType, exceptionTranslator); this.sqlSessionFactory = sqlSessionFactory; this.executorType = executorType; this.exceptionTranslator = exceptionTranslator; this.sqlSessionProxy = (SqlSession) newProxyInstance( SqlSessionFactory.class.getClassLoader(), new Class[] { SqlSession.class }, new SqlSessionInterceptor()); } @Override public SqlSessionFactory getSqlSessionFactory() { return this.sqlSessionFactory; } @Override public ExecutorType getExecutorType() { return this.executorType; } @Override public PersistenceExceptionTranslator getPersistenceExceptionTranslator() { return this.exceptionTranslator; } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement) { return this.sqlSessionProxy.<T> selectOne(statement); } /** * {@inheritDoc} */ @Override public <T> T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.<T> selectOne(statement, parameter); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey); } /** * {@inheritDoc} */ @Override public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) { return this.sqlSessionProxy.<K, V> selectMap(statement, parameter, mapKey, rowBounds); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement) { return this.sqlSessionProxy.selectCursor(statement); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter) { return this.sqlSessionProxy.selectCursor(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement) { return this.sqlSessionProxy.<E> selectList(statement); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter) { return this.sqlSessionProxy.<E> selectList(statement, parameter); } /** * {@inheritDoc} */ @Override public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { return this.sqlSessionProxy.<E> selectList(statement, parameter, rowBounds); } /** * {@inheritDoc} */ @Override public void select(String statement, ResultHandler handler) { this.sqlSessionProxy.select(statement, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, handler); } /** * {@inheritDoc} */ @Override public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { this.sqlSessionProxy.select(statement, parameter, rowBounds, handler); } /** * {@inheritDoc} */ @Override public int insert(String statement) { return this.sqlSessionProxy.insert(statement); } /** * {@inheritDoc} */ @Override public int insert(String statement, Object parameter) { return this.sqlSessionProxy.insert(statement, parameter); } /** * {@inheritDoc} */ @Override public int update(String statement) { return this.sqlSessionProxy.update(statement); } /** * {@inheritDoc} */ @Override public int update(String statement, Object parameter) { return this.sqlSessionProxy.update(statement, parameter); } /** * {@inheritDoc} */ @Override public int delete(String statement) { return this.sqlSessionProxy.delete(statement); } /** * {@inheritDoc} */ @Override public int delete(String statement, Object parameter) { return this.sqlSessionProxy.delete(statement, parameter); } /** * {@inheritDoc} */ @Override public <T> T getMapper(Class<T> type) { return getConfiguration().getMapper(type, this); } /** * {@inheritDoc} */ @Override public void commit() { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void commit(boolean force) { throw new UnsupportedOperationException("Manual commit is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback() { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void rollback(boolean force) { throw new UnsupportedOperationException("Manual rollback is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Manual close is not allowed over a Spring managed SqlSession"); } /** * {@inheritDoc} */ @Override public void clearCache() { this.sqlSessionProxy.clearCache(); } /** * {@inheritDoc} * */ @Override public Configuration getConfiguration() { return this.sqlSessionFactory.getConfiguration(); } /** * {@inheritDoc} */ @Override public Connection getConnection() { return this.sqlSessionProxy.getConnection(); } /** * {@inheritDoc} * * @since 1.0.2 * */ @Override public List<BatchResult> flushStatements() { return this.sqlSessionProxy.flushStatements(); } /** * Allow gently dispose bean: * <pre> * {@code * * <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> * <constructor-arg index="0" ref="sqlSessionFactory" /> * </bean> * } *</pre> * * The implementation of {@link DisposableBean} forces spring context to use {@link DisposableBean#destroy()} method instead of {@link SqlSessionTemplate#close()} to shutdown gently. * * @see SqlSessionTemplate#close() * @see org.springframework.beans.factory.support.DisposableBeanAdapter#inferDestroyMethodIfNecessary * @see org.springframework.beans.factory.support.DisposableBeanAdapter#CLOSE_METHOD_NAME */ @Override public void destroy() throws Exception { //This method forces spring disposer to avoid call of SqlSessionTemplate.close() which gives UnsupportedOperationException } /** * Proxy needed to route MyBatis method calls to the proper SqlSession got * from Spring's Transaction Manager * It also unwraps exceptions thrown by {@code Method#invoke(Object, Object...)} to * pass a {@code PersistenceException} to the {@code PersistenceExceptionTranslator}. */ private class SqlSessionInterceptor implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { SqlSession sqlSession = getSqlSession( TdSqlSessionTemplate.this.sqlSessionFactory, TdSqlSessionTemplate.this.executorType, TdSqlSessionTemplate.this.exceptionTranslator); try { Object result = method.invoke(sqlSession, args); if (!isSqlSessionTransactional(sqlSession, TdSqlSessionTemplate.this.sqlSessionFactory)) { // force commit even on non-dirty sessions because some databases require // a commit/rollback before calling close() sqlSession.commit(true); } return result; } catch (Throwable t) { Throwable unwrapped = unwrapThrowable(t); //如果存储过程没有返回正常结果, 需要标记物理连接应该丢弃 closePhysicalConnectionByCallableEx(sqlSession, args, unwrapped); if (TdSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) { // release the connection to avoid a deadlock if the translator is no loaded. See issue #22 closeSqlSession(sqlSession, TdSqlSessionTemplate.this.sqlSessionFactory); sqlSession = null; Throwable translated = TdSqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped); if (translated != null) { unwrapped = translated; } } throw unwrapped; } finally { if (sqlSession != null) { closeSqlSession(sqlSession, TdSqlSessionTemplate.this.sqlSessionFactory); } } } } /** * 如果存储过程没有返回正常结果, 需要标记物理连接应该丢弃 * @param sqlSession * @param args * @param unwrapped */ private void closePhysicalConnectionByCallableEx(SqlSession sqlSession, Object[] args, Throwable unwrapped) { try { if(unwrapped instanceof PersistenceException && args.length > 0) { MappedStatement ms = sqlSessionFactory.getConfiguration().getMappedStatement((String) args[0]); if(ms != null && ms.getStatementType().equals(StatementType.CALLABLE)) { Connection connection = sqlSession.getConnection(); if(connection instanceof DruidPooledConnection) { DruidPooledConnection pooledConnection = (DruidPooledConnection) connection; pooledConnection.abandond(); pooledConnection.addConnectionEventListener(new ConnectionClosedListener()); logger.info("存储过程执行出现异常, 标记物理连接应该丢弃: " + connection.toString()); } } } } catch (Exception e) { logger.error("因为存储过程执行报错, 尝试关闭物理连接的时候发生错误", e); } } static class ConnectionClosedListener implements ConnectionEventListener { private static final Logger logger = LoggerFactory.getLogger(ConnectionClosedListener.class); @Override public void connectionClosed(ConnectionEvent event) { try { if(event.getSource() instanceof DruidPooledConnection) { DruidPooledConnection conn = (DruidPooledConnection)event.getSource(); if(conn.isAbandonded() && !conn.isDisable() && !conn.isClosed()) { DruidAbstractDataSource dataSource = conn.getConnectionHolder().getDataSource(); dataSource.discardConnection(conn.getConnection()); logger.info("存储过程执行出现异常, 成功关闭物理连接: " + conn.toString()); } } } catch (Exception e) { logger.error("关闭物理连接的时候发生错误", e); } } @Override public void connectionErrorOccurred(ConnectionEvent event) { } } }
true
6bf388d7f4f8d4839e9b7adfbecc83a50fd79146
Java
jpory/hibernate-reverse
/src/main/java/com/gantang/generatecode/model/GenerateProperty.java
UTF-8
2,789
2.359375
2
[]
no_license
package com.gantang.generatecode.model; import java.util.HashMap; import java.util.Map; /** * * @author jiangyp * */ public class GenerateProperty { private static Map<String, String> TYPE_MAPPING = new HashMap<>(); private static Map<String, String> JS_TYPE_MAPPING = new HashMap<>(); static { TYPE_MAPPING.put("VARCHAR2", "String"); TYPE_MAPPING.put("NVARCHAR2", "String"); TYPE_MAPPING.put("CHAR", "Boolean"); TYPE_MAPPING.put("NUMBER", "Long"); TYPE_MAPPING.put("DATE", "Date"); JS_TYPE_MAPPING.put("VARCHAR2", "string"); JS_TYPE_MAPPING.put("NVARCHAR2", "string"); JS_TYPE_MAPPING.put("CHAR", "boolean"); JS_TYPE_MAPPING.put("NUMBER", "number"); JS_TYPE_MAPPING.put("DATE", "date"); } private String name; private String cloumnName; private String methodName; private String type; private String jsType; private Integer length = 255; private Integer precision; private Integer scale; private String isNull; public GenerateProperty(String name, String cloumnName, String type, Integer length, Integer precision, Integer scale, String isNull) { super(); this.name = name; this.methodName = name.substring(0, 1).toUpperCase() + name.substring(1); this.cloumnName = cloumnName; this.type = TYPE_MAPPING.get(type); this.jsType = JS_TYPE_MAPPING.get(type); this.length = length; this.precision = precision; this.scale = scale; this.isNull = isNull; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCloumnName() { return cloumnName; } public void setCloumnName(String cloumnName) { this.cloumnName = cloumnName; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getJsType() { return jsType; } public void setJsType(String jsType) { this.jsType = jsType; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Integer getPrecision() { return precision; } public void setPrecision(Integer precision) { this.precision = precision; } public Integer getScale() { return scale; } public void setScale(Integer scale) { this.scale = scale; } public String getIsNull() { return isNull; } public void setIsNull(String isNull) { this.isNull = isNull; } @Override public String toString() { return "Property [name=" + name + ", cloumnName=" + cloumnName + ", methodName=" + methodName + ", type=" + type + ", length=" + length + ", precision=" + precision + ", scale=" + scale + ", isNull=" + isNull + "]"; } }
true
e3425fb9a96148ef12cede27371acf4cb9aedafb
Java
synowa/simple-chatty-bot
/Problems/Snail/src/Main.java
UTF-8
716
3.734375
4
[]
no_license
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); /* On the input the program receives non-negative integers H, A, B, where H > B and A > B. Every integer does not exceed 100. */ int h = scanner.nextInt(); int a = scanner.nextInt(); int b = scanner.nextInt(); int result = (int)Math.ceil((double) (h - a) / (a - b)) + 1; /* first part counts how many days and nights it will take to get to the height which is smaller from the given one (H) exactly by the amount of one day trip (which is A) */ System.out.println(result); } }
true
d0f63ccacf3bd7041fd1a64b1ccef0e2f9ece064
Java
kousuke/annotated-contracts
/contract-core/contract-verifier/src/main/java/com/github/sebhoss/contract/verifier/impl/DelegatingContractSyntaxCheck.java
UTF-8
1,107
2.28125
2
[ "LicenseRef-scancode-unknown-license-reference", "WTFPL" ]
permissive
/* * Copyright © 2012 Sebastian Hoß <mail@shoss.de> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ package com.github.sebhoss.contract.verifier.impl; import java.util.Set; import javax.inject.Inject; import com.github.sebhoss.contract.annotation.Contract; import com.github.sebhoss.contract.verifier.ContractSyntaxCheck; /** * Delegates syntax checks to a set of encapsulated syntax check instances. */ public final class DelegatingContractSyntaxCheck implements ContractSyntaxCheck { private final Set<ContractSyntaxCheck> checks; /** * @param checks * The syntax checks to perform. */ @Inject public DelegatingContractSyntaxCheck(final Set<ContractSyntaxCheck> checks) { this.checks = checks; } @Override public void validate(final Contract contract) { for (final ContractSyntaxCheck check : checks) { check.validate(contract); } } }
true
201d7cc8856ad5f848e8a9e81a244d36bd56f923
Java
javagurulv/java_1_thursday_2020_online
/src/main/java/teacher/lesson_17_multithreading/lessoncode/StreamApiMultyThreading.java
UTF-8
392
2.75
3
[]
no_license
package teacher.lesson_17_multithreading.lessoncode; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class StreamApiMultyThreading { public static void main(String[] args) { List<String> list = new ArrayList<>(); List<String> result = list.stream().parallel() .filter(s -> s.equals("ABC")) .collect(Collectors.toList()); } }
true
89a12ddd97d465bc9d80a88a0ca7f07559682712
Java
athena-proxy/athena
/athena-core/src/main/java/me/ele/jarch/athena/util/log/RawSQLContxt.java
UTF-8
1,901
2.140625
2
[ "Apache-2.0" ]
permissive
package me.ele.jarch.athena.util.log; import java.util.StringJoiner; /** * @author jinghao.wang */ public class RawSQLContxt { private String rawSQL; private String sqlWithoutComment; private String clientInfo; private String user; private String dalGroup; private String transactionId; public RawSQLContxt() { } public String rawSQL() { return rawSQL; } public RawSQLContxt rawSQL(String rawSQL) { this.rawSQL = rawSQL; return this; } public String sqlWithoutComment() { return sqlWithoutComment; } public RawSQLContxt sqlWithoutComment(String sqlWithoutComment) { this.sqlWithoutComment = sqlWithoutComment; return this; } public String clientInfo() { return clientInfo; } public RawSQLContxt clientInfo(String clientInfo) { this.clientInfo = clientInfo; return this; } public String transactionId() { return transactionId; } public RawSQLContxt transactionId(String transactionId) { this.transactionId = transactionId; return this; } public String user() { return user; } public RawSQLContxt user(String user) { this.user = user; return this; } public String dalGroup() { return dalGroup; } public RawSQLContxt dalGroup(String dalGroup) { this.dalGroup = dalGroup; return this; } @Override public String toString() { return new StringJoiner(", ", RawSQLContxt.class.getSimpleName() + "[", "]") .add("rawSQL='" + rawSQL + "'").add("sqlWithoutComment='" + sqlWithoutComment + "'") .add("clientInfo='" + clientInfo + "'").add("user='" + user + "'") .add("dalGroup='" + dalGroup + "'").add("transactionId='" + transactionId + "'") .toString(); } }
true
43ee847f75c14b32f02924b0f4cb7e8be16b3563
Java
aleksandr-hrankin/api-employees
/src/main/java/ua/antibyte/service/EmployeeInitializer.java
UTF-8
2,292
2.453125
2
[]
no_license
package ua.antibyte.service; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import javax.annotation.PostConstruct; import lombok.extern.log4j.Log4j; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.springframework.stereotype.Component; import ua.antibyte.exception.ApiConnectionException; import ua.antibyte.model.Employee; import ua.antibyte.model.dto.request.EmployeesRequestDto; import ua.antibyte.service.mapper.EmployeeMapper; @Component @Log4j public class EmployeeInitializer { private static final String GET_EMPLOYEES_URL = "https://randomuser.me/api/?results=20"; private final CloseableHttpClient httpClient; private final ObjectMapper objectMapper; private final EmployeeService employeeService; private final EmployeeMapper employeeMapper; public EmployeeInitializer(CloseableHttpClient httpClient, ObjectMapper objectMapper, EmployeeService employeeService, EmployeeMapper employeeMapper) { this.httpClient = httpClient; this.objectMapper = objectMapper; this.employeeService = employeeService; this.employeeMapper = employeeMapper; } @PostConstruct private void init() { saveEmployeesToDb(loadEmployeesFromApi()); } private EmployeesRequestDto loadEmployeesFromApi() { HttpGet request = new HttpGet(GET_EMPLOYEES_URL); try (CloseableHttpResponse response = httpClient.execute(request)) { log.info("Data have been successfully received at " + GET_EMPLOYEES_URL); return objectMapper.readValue(response.getEntity().getContent(), EmployeesRequestDto.class); } catch (IOException e) { throw new ApiConnectionException("Can't send request to " + GET_EMPLOYEES_URL, e); } } private void saveEmployeesToDb(EmployeesRequestDto employeesRequestDto) { List<Employee> employees = employeeMapper .mapEmployeesRequestDtoToEmployees(employeesRequestDto); employeeService.addAll(employees); } }
true
941dc011b791116ad465d6fe76fa129e7feaa2bb
Java
allenday/reddit-nlp
/src/main/java/com/allenday/dataflow/reddit/Injector.java
UTF-8
3,504
2.453125
2
[]
no_license
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.allenday.dataflow.reddit; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.google.api.services.pubsub.Pubsub; import com.google.api.services.pubsub.model.PublishRequest; import com.google.api.services.pubsub.model.PubsubMessage; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; class Injector { private static Pubsub pubsub; private static String topic; private static String project; private static final String MESSAGE_ID_ATTRIBUTE = "id"; private static final int numMessages = 10; private static final int delayInMillis = 500; // How long to sleep, in ms, between creation of the threads that make API requests to PubSub. private static final int THREAD_SLEEP_MS = 500; private static final Gson gson = new Gson(); public static void publishData(int numMessages, int delayInMillis) throws IOException { List<PubsubMessage> pubsubMessages = new ArrayList<>(); for (int i = 0; i < Math.max(1, numMessages); i++) { Long currTime = System.currentTimeMillis(); String id = UUID.randomUUID().toString(); String msg = "msg_"+id; String title = "title_"+id; String selftext = "selftext happy "+id; ImmutableMap<String,String> payload = ImmutableMap.of( MESSAGE_ID_ATTRIBUTE, id, "title", title, "selftext", selftext ); String json = gson.toJson(payload); PubsubMessage pubsubMessage = new PubsubMessage().encodeData(json.getBytes("UTF-8")); pubsubMessage.setAttributes(payload); System.out.println(json); pubsubMessages.add(pubsubMessage); } PublishRequest publishRequest = new PublishRequest(); publishRequest.setMessages(pubsubMessages); pubsub.projects().topics().publish(topic, publishRequest).execute(); } public static void main(String[] args) throws GeneralSecurityException, IOException, InterruptedException { if (args.length < 2) { System.out.println( "Usage: Injector project-name (topic-name|none) "); System.exit(1); } project = args[0]; String topicName = args[1]; // Create the PubSub client. pubsub = InjectorUtils.getClient(); // Create the PubSub topic as necessary. topic = InjectorUtils.getFullyQualifiedTopicName(project, topicName); InjectorUtils.createTopic(pubsub, topic); System.out.println("Injecting to topic: " + topic); System.out.println("Starting Injector"); // Publish messages at a rate determined by the QPS and Thread sleep settings. for (int i = 0; true; i++) { // Start a thread to inject some data. new Thread() { public void run() { try { publishData(numMessages, delayInMillis); } catch (IOException e) { System.err.println(e); } } }.start(); // Wait before creating another injector thread. Thread.sleep(THREAD_SLEEP_MS); } } }
true
99f86db1bc2cd94af7b87b7e25a8d625c7ccb020
Java
rszy/SpringShop
/src/main/java/pl/javastart/springshop/Cart.java
UTF-8
1,502
2.78125
3
[]
no_license
package pl.javastart.springshop; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * Created by Rysiek on 2017-02-23. */ @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class Cart { // private List<Product> products; private Map<Product, Integer> productIntegerMap; private BigDecimal totalPrice; public Cart() { productIntegerMap = new HashMap<>(); } public void add(Product product) { if (!productIntegerMap.containsKey(product)){ productIntegerMap.put(product, 1); } else { Integer amount = productIntegerMap.get(product); amount++; productIntegerMap.put(product, amount); } } public Map<Product, Integer> getProducts() { return productIntegerMap; } public BigDecimal priceCalc() { totalPrice = BigDecimal.ZERO; for (Map.Entry<Product, Integer> entry: productIntegerMap.entrySet()){ totalPrice = totalPrice.add(entry.getKey().getPrice().multiply(new BigDecimal(entry.getValue()))); } return totalPrice; } public void deleteProduct(Product product) { productIntegerMap.remove(product); } public BigDecimal getTotalPrice() { return totalPrice; } }
true
d7cf752e9e954e265929d5e42ddf636f5a9ec4e2
Java
piyushkapoorixe/my_dalmia
/src/com/model/BannerModel.java
UTF-8
697
2.28125
2
[]
no_license
package com.model; public class BannerModel { private String Id; private String Title; private String Image; private String RegionId; private String Region; public String getId() { return Id; } public void setId(String id) { Id = id; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getImage() { return Image; } public void setImage(String image) { Image = image; } public String getRegionId() { return RegionId; } public void setRegionId(String regionId) { RegionId = regionId; } public String getRegion() { return Region; } public void setRegion(String region) { Region = region; } }
true
424f6af335bed276091cb6f4ce4eebb756921171
Java
action-hong/ZhihuDemo
/app/src/main/java/com/example/kkopite/zhihudemo/db/DBHelper.java
UTF-8
1,878
2.328125
2
[]
no_license
package com.example.kkopite.zhihudemo.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by forever 18 kkopite on 2016/7/1 21:01. */ public class DBHelper extends SQLiteOpenHelper { public static final String TABLE_NAME = "daily_news_lists"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_DATE = "date"; public static final String COLUMN_CONTENT = "content"; public static final String TABLE_FAV = "daily_news_fav"; public static final String COLUMN_NEWS_ID = "news_id"; public static final String COLUMN_NEWS_TITLE = "news_title"; public static final String COLUMN_NEWS_IMAGE = "news_image"; public static final String DATABASE_NAME = "daily_news.db"; public static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_DATE + " CHAR(8) UNIQUE, " + COLUMN_CONTENT + " TEXT NOT NULL);"; public static final String DATABASE_CREATE_FAV = "CREATE TABLE " + TABLE_FAV + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NEWS_ID + " INTEGER UNIQUE, " + COLUMN_NEWS_TITLE + " TEXT, " + COLUMN_NEWS_IMAGE + " TEXT);"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(DATABASE_CREATE_FAV); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } }
true
32120284eac09c42bab704e2f8ad5a22dba645fc
Java
myxland/wms-cloud
/wms-saas/src/main/java/com/zlsrj/wms/saas/rest/TenantCustomerMeterChangeLogRestController.java
UTF-8
24,974
2.046875
2
[]
no_license
package com.zlsrj.wms.saas.rest; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.zlsrj.wms.api.dto.TenantCustomerMeterChangeLogQueryParam; import com.zlsrj.wms.api.entity.TenantInfo; import com.zlsrj.wms.api.entity.TenantCustomerMeterChangeLog; import com.zlsrj.wms.api.vo.TenantCustomerMeterChangeLogVo; import com.zlsrj.wms.common.api.CommonResult; import com.zlsrj.wms.saas.service.IIdService; import com.zlsrj.wms.saas.service.ITenantInfoService; import com.zlsrj.wms.saas.service.ITenantCustomerMeterChangeLogService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; @Api(value = "信息变更", tags = { "信息变更操作接口" }) @RestController @Slf4j public class TenantCustomerMeterChangeLogRestController { @Autowired private ITenantCustomerMeterChangeLogService tenantCustomerMeterChangeLogService; @Autowired private ITenantInfoService tenantInfoService; @Autowired private IIdService idService; @ApiOperation(value = "根据ID查询信息变更") @RequestMapping(value = "/tenant-customer-meter-change-logs/{id}", method = RequestMethod.GET) public TenantCustomerMeterChangeLogVo getById(@PathVariable("id") Long id) { TenantCustomerMeterChangeLog tenantCustomerMeterChangeLog = tenantCustomerMeterChangeLogService.getById(id); return entity2vo(tenantCustomerMeterChangeLog); } @ApiOperation(value = "根据参数查询信息变更列表") @RequestMapping(value = "/tenant-customer-meter-change-logs", method = RequestMethod.GET) public Page<TenantCustomerMeterChangeLogVo> page(@RequestBody TenantCustomerMeterChangeLogQueryParam tenantCustomerMeterChangeLogQueryParam, @RequestParam(value = "page", defaultValue = "1") int page, // @RequestParam(value = "rows", defaultValue = "10") int rows, // @RequestParam(value = "sort") String sort, // 排序列字段名 @RequestParam(value = "order") String order // 可以是 'asc' 或者 'desc',默认值是 'asc' ) { IPage<TenantCustomerMeterChangeLog> pageTenantCustomerMeterChangeLog = new Page<TenantCustomerMeterChangeLog>(page, rows); QueryWrapper<TenantCustomerMeterChangeLog> queryWrapperTenantCustomerMeterChangeLog = new QueryWrapper<TenantCustomerMeterChangeLog>(); queryWrapperTenantCustomerMeterChangeLog.orderBy(StringUtils.isNotEmpty(sort), "asc".equals(order), sort); queryWrapperTenantCustomerMeterChangeLog.lambda() .eq(tenantCustomerMeterChangeLogQueryParam.getId() != null, TenantCustomerMeterChangeLog::getId, tenantCustomerMeterChangeLogQueryParam.getId()) .eq(tenantCustomerMeterChangeLogQueryParam.getTenantId() != null, TenantCustomerMeterChangeLog::getTenantId, tenantCustomerMeterChangeLogQueryParam.getTenantId()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerId() != null, TenantCustomerMeterChangeLog::getCustomerId, tenantCustomerMeterChangeLogQueryParam.getCustomerId()) .eq(tenantCustomerMeterChangeLogQueryParam.getCsutomerIdNew() != null, TenantCustomerMeterChangeLog::getCsutomerIdNew, tenantCustomerMeterChangeLogQueryParam.getCsutomerIdNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerName() != null, TenantCustomerMeterChangeLog::getCustomerName, tenantCustomerMeterChangeLogQueryParam.getCustomerName()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerNameNew() != null, TenantCustomerMeterChangeLog::getCustomerNameNew, tenantCustomerMeterChangeLogQueryParam.getCustomerNameNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerAddress() != null, TenantCustomerMeterChangeLog::getCustomerAddress, tenantCustomerMeterChangeLogQueryParam.getCustomerAddress()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerAddressNew() != null, TenantCustomerMeterChangeLog::getCustomerAddressNew, tenantCustomerMeterChangeLogQueryParam.getCustomerAddressNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerTypeId() != null, TenantCustomerMeterChangeLog::getCustomerTypeId, tenantCustomerMeterChangeLogQueryParam.getCustomerTypeId()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerTypeIdNew() != null, TenantCustomerMeterChangeLog::getCustomerTypeIdNew, tenantCustomerMeterChangeLogQueryParam.getCustomerTypeIdNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerStatus() != null, TenantCustomerMeterChangeLog::getCustomerStatus, tenantCustomerMeterChangeLogQueryParam.getCustomerStatus()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerStatusNew() != null, TenantCustomerMeterChangeLog::getCustomerStatusNew, tenantCustomerMeterChangeLogQueryParam.getCustomerStatusNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerPaymentMethod() != null, TenantCustomerMeterChangeLog::getCustomerPaymentMethod, tenantCustomerMeterChangeLogQueryParam.getCustomerPaymentMethod()) .eq(tenantCustomerMeterChangeLogQueryParam.getCustomerPaymentMethodNew() != null, TenantCustomerMeterChangeLog::getCustomerPaymentMethodNew, tenantCustomerMeterChangeLogQueryParam.getCustomerPaymentMethodNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceType() != null, TenantCustomerMeterChangeLog::getInvoiceType, tenantCustomerMeterChangeLogQueryParam.getInvoiceType()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceTypeNew() != null, TenantCustomerMeterChangeLog::getInvoiceTypeNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceTypeNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceName() != null, TenantCustomerMeterChangeLog::getInvoiceName, tenantCustomerMeterChangeLogQueryParam.getInvoiceName()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceNameNew() != null, TenantCustomerMeterChangeLog::getInvoiceNameNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceNameNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceTaxNo() != null, TenantCustomerMeterChangeLog::getInvoiceTaxNo, tenantCustomerMeterChangeLogQueryParam.getInvoiceTaxNo()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceTaxNoNew() != null, TenantCustomerMeterChangeLog::getInvoiceTaxNoNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceTaxNoNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceAddress() != null, TenantCustomerMeterChangeLog::getInvoiceAddress, tenantCustomerMeterChangeLogQueryParam.getInvoiceAddress()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceAddressNew() != null, TenantCustomerMeterChangeLog::getInvoiceAddressNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceAddressNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceTel() != null, TenantCustomerMeterChangeLog::getInvoiceTel, tenantCustomerMeterChangeLogQueryParam.getInvoiceTel()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceTelNew() != null, TenantCustomerMeterChangeLog::getInvoiceTelNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceTelNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankCode() != null, TenantCustomerMeterChangeLog::getInvoiceBankCode, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankCode()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankCodeNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankCodeNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankCodeNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankName() != null, TenantCustomerMeterChangeLog::getInvoiceBankName, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankName()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankNameNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankNameNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankNameNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankAccountNo() != null, TenantCustomerMeterChangeLog::getInvoiceBankAccountNo, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankAccountNo()) .eq(tenantCustomerMeterChangeLogQueryParam.getInvoiceBankAccountNoNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankAccountNoNew, tenantCustomerMeterChangeLogQueryParam.getInvoiceBankAccountNoNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterId() != null, TenantCustomerMeterChangeLog::getMeterId, tenantCustomerMeterChangeLogQueryParam.getMeterId()) .eq(tenantCustomerMeterChangeLogQueryParam.getPriceTypeId() != null, TenantCustomerMeterChangeLog::getPriceTypeId, tenantCustomerMeterChangeLogQueryParam.getPriceTypeId()) .eq(tenantCustomerMeterChangeLogQueryParam.getPriceTypeIdNew() != null, TenantCustomerMeterChangeLog::getPriceTypeIdNew, tenantCustomerMeterChangeLogQueryParam.getPriceTypeIdNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterLastSettlePointer() != null, TenantCustomerMeterChangeLog::getMeterLastSettlePointer, tenantCustomerMeterChangeLogQueryParam.getMeterLastSettlePointer()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterLastSettlePointerNew() != null, TenantCustomerMeterChangeLog::getMeterLastSettlePointerNew, tenantCustomerMeterChangeLogQueryParam.getMeterLastSettlePointerNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getManufactorId() != null, TenantCustomerMeterChangeLog::getManufactorId, tenantCustomerMeterChangeLogQueryParam.getManufactorId()) .eq(tenantCustomerMeterChangeLogQueryParam.getManufactorIdNew() != null, TenantCustomerMeterChangeLog::getManufactorIdNew, tenantCustomerMeterChangeLogQueryParam.getManufactorIdNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterType() != null, TenantCustomerMeterChangeLog::getMeterType, tenantCustomerMeterChangeLogQueryParam.getMeterType()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterTypeNew() != null, TenantCustomerMeterChangeLog::getMeterTypeNew, tenantCustomerMeterChangeLogQueryParam.getMeterTypeNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getCaliberId() != null, TenantCustomerMeterChangeLog::getCaliberId, tenantCustomerMeterChangeLogQueryParam.getCaliberId()) .eq(tenantCustomerMeterChangeLogQueryParam.getCaliberIdNew() != null, TenantCustomerMeterChangeLog::getCaliberIdNew, tenantCustomerMeterChangeLogQueryParam.getCaliberIdNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterMachineCode() != null, TenantCustomerMeterChangeLog::getMeterMachineCode, tenantCustomerMeterChangeLogQueryParam.getMeterMachineCode()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterMachineCodeNew() != null, TenantCustomerMeterChangeLog::getMeterMachineCodeNew, tenantCustomerMeterChangeLogQueryParam.getMeterMachineCodeNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterIotCode() != null, TenantCustomerMeterChangeLog::getMeterIotCode, tenantCustomerMeterChangeLogQueryParam.getMeterIotCode()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterIotCodeNew() != null, TenantCustomerMeterChangeLog::getMeterIotCodeNew, tenantCustomerMeterChangeLogQueryParam.getMeterIotCodeNew()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterPeoples() != null, TenantCustomerMeterChangeLog::getMeterPeoples, tenantCustomerMeterChangeLogQueryParam.getMeterPeoples()) .eq(tenantCustomerMeterChangeLogQueryParam.getMeterPeoplesNew() != null, TenantCustomerMeterChangeLog::getMeterPeoplesNew, tenantCustomerMeterChangeLogQueryParam.getMeterPeoplesNew()) ; IPage<TenantCustomerMeterChangeLog> tenantCustomerMeterChangeLogPage = tenantCustomerMeterChangeLogService.page(pageTenantCustomerMeterChangeLog, queryWrapperTenantCustomerMeterChangeLog); Page<TenantCustomerMeterChangeLogVo> tenantCustomerMeterChangeLogVoPage = new Page<TenantCustomerMeterChangeLogVo>(page, rows); tenantCustomerMeterChangeLogVoPage.setCurrent(tenantCustomerMeterChangeLogPage.getCurrent()); tenantCustomerMeterChangeLogVoPage.setPages(tenantCustomerMeterChangeLogPage.getPages()); tenantCustomerMeterChangeLogVoPage.setSize(tenantCustomerMeterChangeLogPage.getSize()); tenantCustomerMeterChangeLogVoPage.setTotal(tenantCustomerMeterChangeLogPage.getTotal()); tenantCustomerMeterChangeLogVoPage.setRecords(tenantCustomerMeterChangeLogPage.getRecords().stream()// .map(e -> entity2vo(e))// .collect(Collectors.toList())); return tenantCustomerMeterChangeLogVoPage; } @ApiOperation(value = "新增信息变更") @RequestMapping(value = "/tenant-customer-meter-change-logs", method = RequestMethod.POST) public TenantCustomerMeterChangeLogVo save(@RequestBody TenantCustomerMeterChangeLog tenantCustomerMeterChangeLog) { if (tenantCustomerMeterChangeLog.getId() == null || tenantCustomerMeterChangeLog.getId().compareTo(0L) <= 0) { tenantCustomerMeterChangeLog.setId(idService.selectId()); } boolean success = tenantCustomerMeterChangeLogService.save(tenantCustomerMeterChangeLog); if (success) { TenantCustomerMeterChangeLog tenantCustomerMeterChangeLogDatabase = tenantCustomerMeterChangeLogService.getById(tenantCustomerMeterChangeLog.getId()); return entity2vo(tenantCustomerMeterChangeLogDatabase); } log.info("save TenantCustomerMeterChangeLog fail,{}", ToStringBuilder.reflectionToString(tenantCustomerMeterChangeLog, ToStringStyle.JSON_STYLE)); return null; } @ApiOperation(value = "更新信息变更全部信息") @RequestMapping(value = "/tenant-customer-meter-change-logs/{id}", method = RequestMethod.PUT) public TenantCustomerMeterChangeLogVo updateById(@PathVariable("id") Long id, @RequestBody TenantCustomerMeterChangeLog tenantCustomerMeterChangeLog) { tenantCustomerMeterChangeLog.setId(id); boolean success = tenantCustomerMeterChangeLogService.updateById(tenantCustomerMeterChangeLog); if (success) { TenantCustomerMeterChangeLog tenantCustomerMeterChangeLogDatabase = tenantCustomerMeterChangeLogService.getById(id); return entity2vo(tenantCustomerMeterChangeLogDatabase); } log.info("update TenantCustomerMeterChangeLog fail,{}", ToStringBuilder.reflectionToString(tenantCustomerMeterChangeLog, ToStringStyle.JSON_STYLE)); return null; } @ApiOperation(value = "根据参数更新信息变更信息") @RequestMapping(value = "/tenant-customer-meter-change-logs/{id}", method = RequestMethod.PATCH) public TenantCustomerMeterChangeLogVo updatePatchById(@PathVariable("id") Long id, @RequestBody TenantCustomerMeterChangeLog tenantCustomerMeterChangeLog) { TenantCustomerMeterChangeLog tenantCustomerMeterChangeLogWhere = TenantCustomerMeterChangeLog.builder()// .id(id)// .build(); UpdateWrapper<TenantCustomerMeterChangeLog> updateWrapperTenantCustomerMeterChangeLog = new UpdateWrapper<TenantCustomerMeterChangeLog>(); updateWrapperTenantCustomerMeterChangeLog.setEntity(tenantCustomerMeterChangeLogWhere); updateWrapperTenantCustomerMeterChangeLog.lambda()// //.eq(TenantCustomerMeterChangeLog::getId, id) // .set(tenantCustomerMeterChangeLog.getId() != null, TenantCustomerMeterChangeLog::getId, tenantCustomerMeterChangeLog.getId()) .set(tenantCustomerMeterChangeLog.getTenantId() != null, TenantCustomerMeterChangeLog::getTenantId, tenantCustomerMeterChangeLog.getTenantId()) .set(tenantCustomerMeterChangeLog.getCustomerId() != null, TenantCustomerMeterChangeLog::getCustomerId, tenantCustomerMeterChangeLog.getCustomerId()) .set(tenantCustomerMeterChangeLog.getCsutomerIdNew() != null, TenantCustomerMeterChangeLog::getCsutomerIdNew, tenantCustomerMeterChangeLog.getCsutomerIdNew()) .set(tenantCustomerMeterChangeLog.getCustomerName() != null, TenantCustomerMeterChangeLog::getCustomerName, tenantCustomerMeterChangeLog.getCustomerName()) .set(tenantCustomerMeterChangeLog.getCustomerNameNew() != null, TenantCustomerMeterChangeLog::getCustomerNameNew, tenantCustomerMeterChangeLog.getCustomerNameNew()) .set(tenantCustomerMeterChangeLog.getCustomerAddress() != null, TenantCustomerMeterChangeLog::getCustomerAddress, tenantCustomerMeterChangeLog.getCustomerAddress()) .set(tenantCustomerMeterChangeLog.getCustomerAddressNew() != null, TenantCustomerMeterChangeLog::getCustomerAddressNew, tenantCustomerMeterChangeLog.getCustomerAddressNew()) .set(tenantCustomerMeterChangeLog.getCustomerTypeId() != null, TenantCustomerMeterChangeLog::getCustomerTypeId, tenantCustomerMeterChangeLog.getCustomerTypeId()) .set(tenantCustomerMeterChangeLog.getCustomerTypeIdNew() != null, TenantCustomerMeterChangeLog::getCustomerTypeIdNew, tenantCustomerMeterChangeLog.getCustomerTypeIdNew()) .set(tenantCustomerMeterChangeLog.getCustomerStatus() != null, TenantCustomerMeterChangeLog::getCustomerStatus, tenantCustomerMeterChangeLog.getCustomerStatus()) .set(tenantCustomerMeterChangeLog.getCustomerStatusNew() != null, TenantCustomerMeterChangeLog::getCustomerStatusNew, tenantCustomerMeterChangeLog.getCustomerStatusNew()) .set(tenantCustomerMeterChangeLog.getCustomerPaymentMethod() != null, TenantCustomerMeterChangeLog::getCustomerPaymentMethod, tenantCustomerMeterChangeLog.getCustomerPaymentMethod()) .set(tenantCustomerMeterChangeLog.getCustomerPaymentMethodNew() != null, TenantCustomerMeterChangeLog::getCustomerPaymentMethodNew, tenantCustomerMeterChangeLog.getCustomerPaymentMethodNew()) .set(tenantCustomerMeterChangeLog.getInvoiceType() != null, TenantCustomerMeterChangeLog::getInvoiceType, tenantCustomerMeterChangeLog.getInvoiceType()) .set(tenantCustomerMeterChangeLog.getInvoiceTypeNew() != null, TenantCustomerMeterChangeLog::getInvoiceTypeNew, tenantCustomerMeterChangeLog.getInvoiceTypeNew()) .set(tenantCustomerMeterChangeLog.getInvoiceName() != null, TenantCustomerMeterChangeLog::getInvoiceName, tenantCustomerMeterChangeLog.getInvoiceName()) .set(tenantCustomerMeterChangeLog.getInvoiceNameNew() != null, TenantCustomerMeterChangeLog::getInvoiceNameNew, tenantCustomerMeterChangeLog.getInvoiceNameNew()) .set(tenantCustomerMeterChangeLog.getInvoiceTaxNo() != null, TenantCustomerMeterChangeLog::getInvoiceTaxNo, tenantCustomerMeterChangeLog.getInvoiceTaxNo()) .set(tenantCustomerMeterChangeLog.getInvoiceTaxNoNew() != null, TenantCustomerMeterChangeLog::getInvoiceTaxNoNew, tenantCustomerMeterChangeLog.getInvoiceTaxNoNew()) .set(tenantCustomerMeterChangeLog.getInvoiceAddress() != null, TenantCustomerMeterChangeLog::getInvoiceAddress, tenantCustomerMeterChangeLog.getInvoiceAddress()) .set(tenantCustomerMeterChangeLog.getInvoiceAddressNew() != null, TenantCustomerMeterChangeLog::getInvoiceAddressNew, tenantCustomerMeterChangeLog.getInvoiceAddressNew()) .set(tenantCustomerMeterChangeLog.getInvoiceTel() != null, TenantCustomerMeterChangeLog::getInvoiceTel, tenantCustomerMeterChangeLog.getInvoiceTel()) .set(tenantCustomerMeterChangeLog.getInvoiceTelNew() != null, TenantCustomerMeterChangeLog::getInvoiceTelNew, tenantCustomerMeterChangeLog.getInvoiceTelNew()) .set(tenantCustomerMeterChangeLog.getInvoiceBankCode() != null, TenantCustomerMeterChangeLog::getInvoiceBankCode, tenantCustomerMeterChangeLog.getInvoiceBankCode()) .set(tenantCustomerMeterChangeLog.getInvoiceBankCodeNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankCodeNew, tenantCustomerMeterChangeLog.getInvoiceBankCodeNew()) .set(tenantCustomerMeterChangeLog.getInvoiceBankName() != null, TenantCustomerMeterChangeLog::getInvoiceBankName, tenantCustomerMeterChangeLog.getInvoiceBankName()) .set(tenantCustomerMeterChangeLog.getInvoiceBankNameNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankNameNew, tenantCustomerMeterChangeLog.getInvoiceBankNameNew()) .set(tenantCustomerMeterChangeLog.getInvoiceBankAccountNo() != null, TenantCustomerMeterChangeLog::getInvoiceBankAccountNo, tenantCustomerMeterChangeLog.getInvoiceBankAccountNo()) .set(tenantCustomerMeterChangeLog.getInvoiceBankAccountNoNew() != null, TenantCustomerMeterChangeLog::getInvoiceBankAccountNoNew, tenantCustomerMeterChangeLog.getInvoiceBankAccountNoNew()) .set(tenantCustomerMeterChangeLog.getMeterId() != null, TenantCustomerMeterChangeLog::getMeterId, tenantCustomerMeterChangeLog.getMeterId()) .set(tenantCustomerMeterChangeLog.getPriceTypeId() != null, TenantCustomerMeterChangeLog::getPriceTypeId, tenantCustomerMeterChangeLog.getPriceTypeId()) .set(tenantCustomerMeterChangeLog.getPriceTypeIdNew() != null, TenantCustomerMeterChangeLog::getPriceTypeIdNew, tenantCustomerMeterChangeLog.getPriceTypeIdNew()) .set(tenantCustomerMeterChangeLog.getMeterLastSettlePointer() != null, TenantCustomerMeterChangeLog::getMeterLastSettlePointer, tenantCustomerMeterChangeLog.getMeterLastSettlePointer()) .set(tenantCustomerMeterChangeLog.getMeterLastSettlePointerNew() != null, TenantCustomerMeterChangeLog::getMeterLastSettlePointerNew, tenantCustomerMeterChangeLog.getMeterLastSettlePointerNew()) .set(tenantCustomerMeterChangeLog.getManufactorId() != null, TenantCustomerMeterChangeLog::getManufactorId, tenantCustomerMeterChangeLog.getManufactorId()) .set(tenantCustomerMeterChangeLog.getManufactorIdNew() != null, TenantCustomerMeterChangeLog::getManufactorIdNew, tenantCustomerMeterChangeLog.getManufactorIdNew()) .set(tenantCustomerMeterChangeLog.getMeterType() != null, TenantCustomerMeterChangeLog::getMeterType, tenantCustomerMeterChangeLog.getMeterType()) .set(tenantCustomerMeterChangeLog.getMeterTypeNew() != null, TenantCustomerMeterChangeLog::getMeterTypeNew, tenantCustomerMeterChangeLog.getMeterTypeNew()) .set(tenantCustomerMeterChangeLog.getCaliberId() != null, TenantCustomerMeterChangeLog::getCaliberId, tenantCustomerMeterChangeLog.getCaliberId()) .set(tenantCustomerMeterChangeLog.getCaliberIdNew() != null, TenantCustomerMeterChangeLog::getCaliberIdNew, tenantCustomerMeterChangeLog.getCaliberIdNew()) .set(tenantCustomerMeterChangeLog.getMeterMachineCode() != null, TenantCustomerMeterChangeLog::getMeterMachineCode, tenantCustomerMeterChangeLog.getMeterMachineCode()) .set(tenantCustomerMeterChangeLog.getMeterMachineCodeNew() != null, TenantCustomerMeterChangeLog::getMeterMachineCodeNew, tenantCustomerMeterChangeLog.getMeterMachineCodeNew()) .set(tenantCustomerMeterChangeLog.getMeterIotCode() != null, TenantCustomerMeterChangeLog::getMeterIotCode, tenantCustomerMeterChangeLog.getMeterIotCode()) .set(tenantCustomerMeterChangeLog.getMeterIotCodeNew() != null, TenantCustomerMeterChangeLog::getMeterIotCodeNew, tenantCustomerMeterChangeLog.getMeterIotCodeNew()) .set(tenantCustomerMeterChangeLog.getMeterPeoples() != null, TenantCustomerMeterChangeLog::getMeterPeoples, tenantCustomerMeterChangeLog.getMeterPeoples()) .set(tenantCustomerMeterChangeLog.getMeterPeoplesNew() != null, TenantCustomerMeterChangeLog::getMeterPeoplesNew, tenantCustomerMeterChangeLog.getMeterPeoplesNew()) ; boolean success = tenantCustomerMeterChangeLogService.update(updateWrapperTenantCustomerMeterChangeLog); if (success) { TenantCustomerMeterChangeLog tenantCustomerMeterChangeLogDatabase = tenantCustomerMeterChangeLogService.getById(id); return entity2vo(tenantCustomerMeterChangeLogDatabase); } log.info("partial update TenantCustomerMeterChangeLog fail,{}", ToStringBuilder.reflectionToString(tenantCustomerMeterChangeLog, ToStringStyle.JSON_STYLE)); return null; } @ApiOperation(value = "根据ID删除信息变更") @RequestMapping(value = "/tenant-customer-meter-change-logs/{id}", method = RequestMethod.DELETE) public CommonResult<Object> removeById(@PathVariable("id") Long id) { boolean success = tenantCustomerMeterChangeLogService.removeById(id); return success ? CommonResult.success(success) : CommonResult.failed(); } private TenantCustomerMeterChangeLogVo entity2vo(TenantCustomerMeterChangeLog tenantCustomerMeterChangeLog) { if (tenantCustomerMeterChangeLog == null) { return null; } String jsonString = JSON.toJSONString(tenantCustomerMeterChangeLog); TenantCustomerMeterChangeLogVo tenantCustomerMeterChangeLogVo = JSON.parseObject(jsonString, TenantCustomerMeterChangeLogVo.class); if (StringUtils.isEmpty(tenantCustomerMeterChangeLogVo.getTenantName())) { TenantInfo tenantInfo = tenantInfoService.getById(tenantCustomerMeterChangeLog.getTenantId()); if (tenantInfo != null) { tenantCustomerMeterChangeLogVo.setTenantName(tenantInfo.getTenantName()); } } return tenantCustomerMeterChangeLogVo; } }
true
f1289d1cc6d2b27b2130bd55c00a1a4538cfad62
Java
diogeneszilli12/bowling
/src/main/java/com/alenasoft/application/strategies/StrikeScoreStrategy.java
UTF-8
234
1.9375
2
[]
no_license
package com.alenasoft.application.strategies; class StrikeScoreStrategy extends AllPinesDownScoreStrategy { private static final int strikeNextPointSize = 2; public StrikeScoreStrategy() { super(strikeNextPointSize); } }
true
e869b6f2b480ec49ef2dec357b332282c396d255
Java
RavinduDON/NITA_Project
/src/Hibernate/Entity/TrainingType.java
UTF-8
93
1.84375
2
[]
no_license
package Hibernate.Entity; public enum TrainingType { Basic_Training,Direct_Interview; }
true
3619e10f90a3f76d968ec0a5829e4774b99b8013
Java
ericsonmoreira/peoo_project
/src/br/com/uece/peoo/util/JSONable.java
UTF-8
617
2.90625
3
[]
no_license
package br.com.uece.peoo.util; import org.json.simple.JSONObject; /** * Classe para abistratir qualquer objeto que possa ser manipulado no formato JSON. * * @author Ericson R. Moreira {@link ericson.moreira@aluno.uece.br } * */ public abstract class JSONable { /** * Método para gerar uma String no padrão JSON. * * @return {@link String} no padrão JSON. */ public String toStringJSON() { JSONObject object = this.toJSONObject(); return object.toJSONString(); } /** * Método abistrato para gerar um objeto JSON. * * @return {@link String} no padrão JSON. */ protected abstract JSONObject toJSONObject(); }
true
66d605878cc6ea98dc4c9495282e7a0a4bee4967
Java
ShivaniDegloorkar/IBM_FSD_Assignments
/Java_Strings_9th_May_2019/12. SequenceOfCharInString.java
UTF-8
555
3.921875
4
[]
no_license
import java.util.Scanner; class SequenceOfCharInString{ public static void main(String[] args) { String str1, str2; boolean result; Scanner s = new Scanner(System.in); System.out.println("Enter a string: "); str1 = s.nextLine(); System.out.println("Enter a sequence char"); str2 = s.nextLine(); result = str1.contains(str2); if(result == true){ System.out.println("String Contains specified sequence of char"); } else{ System.out.println("String doesnot contains specified sequence of char"); } } }
true
001e2fa0ae3d8157d334c46ab6e4c5a933cebe2e
Java
CSCI3130-Amadeus/charon
/src/main/java/org/amadeus/charon/data/ReviewManager.java
UTF-8
1,411
2.5625
3
[]
no_license
package org.amadeus.charon.data; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class ReviewManager { public static final String PERSISTENCE_UNIT = "charon_db"; private EntityManagerFactory emFactory; private static ReviewManager instance; private ReviewManager() { emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); } public static ReviewManager getInstance(){ if (instance == null) { instance = new ReviewManager(); } return instance; } public boolean createReview(String comment, User user, Course course, int rating){ if (!comment.equals("") && comment != null){ EntityManager em = emFactory.createEntityManager(); em.getTransaction().begin(); Review review = new Review(comment, user, course, rating); course.getReviews().add(review); em.merge(course); em.persist(review); em.getTransaction().commit(); em.close(); return true; } return false; } protected Review getCourse(long id) { EntityManager em = emFactory.createEntityManager(); Review review = em.find(Review.class, id); em.close(); return review; } }
true
92ef940e6a8de0ec94488d2460f30bafaf4e3c04
Java
RaphaelChevasson/PRI-base-articles-crypto
/server/src/main/java/fr/tse/fise3/pri/p002/server/thread/HalApiRequestThread.java
UTF-8
5,707
2.078125
2
[]
no_license
package fr.tse.fise3.pri.p002.server.thread; import com.fasterxml.jackson.databind.ObjectMapper; import fr.tse.fise3.pri.p002.server.model.Author; import fr.tse.fise3.pri.p002.server.model.DataSource; import fr.tse.fise3.pri.p002.server.model.Keyword; import fr.tse.fise3.pri.p002.server.model.Post; import fr.tse.fise3.pri.p002.server.pojo.HalApiDoc; import fr.tse.fise3.pri.p002.server.pojo.HalApiResponse; import fr.tse.fise3.pri.p002.server.service.AuthorService; import fr.tse.fise3.pri.p002.server.service.DataSourceService; import fr.tse.fise3.pri.p002.server.service.KeywordService; import fr.tse.fise3.pri.p002.server.service.PostService; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Component; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @Component @Scope("prototype") public class HalApiRequestThread implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(HalApiRequestThread.class); private static boolean running = false; private final OkHttpClient okHttpClient; private long start = 0; private long rows = 10000; private long total = 1; @Autowired private PostService postService; @Autowired private AuthorService authorService; @Autowired private KeywordService keywordService; @Autowired private DataSourceService dataSourceService; public HalApiRequestThread() { this.okHttpClient = new OkHttpClient(); } public static boolean isRunning() { return running; } public static void setRunning(boolean running) { HalApiRequestThread.running = running; } private String doRequest(String url) throws IOException { Request request = new Request.Builder().url(url).build(); try (Response response = okHttpClient.newCall(request).execute()) { return response.body().string(); } } @Override public void run() { running = true; try { do { String response = doRequest("http://api.archives-ouvertes.fr/search/?q=*:*&wt=json&fl=uri_s,label_s," + "title_s,authEmail_s,abstract_s,keyword_s,authAlphaLastNameFirstNameIdHal_fs,submittedDate_tdate&" + "sort=docid%20asc&start=" + start + "&rows=" + rows); ObjectMapper objectMapper = new ObjectMapper(); HalApiResponse halApiResponse = objectMapper.readValue(response, HalApiResponse.class); for (HalApiDoc halApiDoc : halApiResponse.getResponse().getDocs()) { saveHalApiDoc(halApiDoc); } total = halApiResponse.getResponse().getNumFound(); start = halApiResponse.getResponse().getStart() + rows; System.out.println("DOING REQUEST FOR START --> " + start + " rows " + rows + " numFound --> " + halApiResponse.getResponse().getNumFound()); updateHalDataSource(start, halApiResponse.getResponse().getNumFound()); } while (start < total); } catch (Exception e) { e.printStackTrace(); } finally { running = false; } } private void saveHalApiDoc(HalApiDoc halApiDoc) { Post post = new Post(); if (postService.postExistsByUrl(halApiDoc.getUri_s())) { System.out.println("POST_ALREADY_EXISTS_BY_URL"); return; } post.setTitle(halApiDoc.getTitle_s().get(0)); post.setDate(halApiDoc.getSubmittedDate_tdate()); post.setUrl(halApiDoc.getUri_s()); if (halApiDoc.getAuthAlphaLastNameFirstNameIdHal_fs() != null) { Map<BigInteger, Author> authorsMap = new HashMap<>(); for (String authorString : halApiDoc.getAuthAlphaLastNameFirstNameIdHal_fs()) { authorString = StringUtils.substringAfter(authorString, "AlphaSep_"); authorString = StringUtils.substringBefore(authorString, "_FacetSep"); Author author = authorService.findOrCreateByName(authorString); authorsMap.put(author.getAuthorId(), author); } post.setAuthors(new ArrayList<>(authorsMap.values())); } if (halApiDoc.getKeyword_s() != null) { Map<BigInteger, Keyword> keywordsMap = new HashMap<>(); for (String keywordString : halApiDoc.getKeyword_s()) { Keyword keyword = keywordService.findOrCreateByName(keywordString); keywordsMap.put(keyword.getKeywordId(), keyword); } post.setKeywords(new ArrayList<>(keywordsMap.values())); } post.setDataSource(dataSourceService.findByName(DataSourceService.SOURCE_HAL).orElseThrow( () -> new ResourceNotFoundException("Hal source doesn't exist") )); try { postService.savePost(post); } catch (Exception e) { e.printStackTrace(); } } private void updateHalDataSource(long offset, long total) { DataSource halDataSource = dataSourceService.getHalDataSource(); halDataSource.setTotal(total); halDataSource.setCurrentOffset(offset); dataSourceService.saveDataSource(halDataSource); } }
true
e7186765b72c09027013fef6df572d2840ddc402
Java
Deepika988/100daysCodeChallange
/Kaprekar.java
UTF-8
792
3.28125
3
[]
no_license
package prgms6; import java.util.*; public class Kaprekar { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s= new Scanner(System.in); System.out.println("Enter a number"); int n=s.nextInt(); int sq=n*n; int count=0; int firstpart=0; int secondpart=0; int sum=0; int temp=sq; while(temp!=0) { count=count+1; temp=temp/10; } for(int i=count-1;i>0;i--) { firstpart= (sq/(int)Math.pow(10, i)); secondpart=(sq%(int)Math.pow(10, i)); if(firstpart!=0 && secondpart!=0 ) { sum=firstpart+secondpart; } if(sum==n) { System.out.println("Kaprekar Number"); break; } } if(sum!=n){ System.out.println("Not Kaprekar Number"); } } }
true
a5961e7888c34b8dea69d68ae79bbd96e981064b
Java
bapleliu/Project
/LaboratoryM/src/main/java/com/org/service/DevTypeService.java
UTF-8
417
1.882813
2
[]
no_license
package com.org.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.org.pojo.DevType; import com.org.repository.DevTypeRepository; @Service public class DevTypeService { @Resource private DevTypeRepository devTypeRepository; //获取设备类型 public List<DevType> selectDevType(){ return devTypeRepository.selectDevType(); } }
true
517d61f9065f4551f7e5ffe48d3e7adbe0417e6a
Java
ViniciusR/genial-android-app
/app/src/main/java/com/silva/vinicius/aplicativogenialjava/activity/LoginActivity.java
UTF-8
3,622
2.265625
2
[]
no_license
package com.silva.vinicius.aplicativogenialjava.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.firebase.ui.auth.AuthUI; import com.firebase.ui.auth.ErrorCodes; import com.firebase.ui.auth.IdpResponse; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.silva.vinicius.aplicativogenialjava.R; import java.util.Arrays; import java.util.Objects; import com.silva.vinicius.aplicativogenialjava.config.FirebaseConfig; import com.silva.vinicius.aplicativogenialjava.models.User; public class LoginActivity extends AppCompatActivity { private static final String TAG = "FBUI_AUTH"; private FirebaseAuth firebaseAuth; private static final int RC_SIGN_IN = 200; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); firebaseAuth = FirebaseConfig.getAuthReference(); startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() //.setLogo(R.drawable.my_great_logo) .setAvailableProviders(Arrays.asList( new AuthUI.IdpConfig.GoogleBuilder().build(), new AuthUI.IdpConfig.EmailBuilder().build())) .build(), RC_SIGN_IN); } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = firebaseAuth.getCurrentUser(); updateUI(currentUser); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { IdpResponse response = IdpResponse.fromResultIntent(data); if (resultCode == RESULT_OK) { FirebaseUser user = firebaseAuth.getCurrentUser(); updateUI(user); } else { // Sign in failed if (response == null) { // User pressed back button return; } if (Objects.requireNonNull(response.getError()).getErrorCode() == ErrorCodes.NO_NETWORK) { Toast.makeText(LoginActivity.this, getString(R.string.no_internet_connection), Toast.LENGTH_SHORT) .show(); return; } Toast.makeText(LoginActivity.this, getString(R.string.fui_error_unknown), Toast.LENGTH_SHORT) .show(); Log.e(TAG, "Sign-in error: ", response.getError()); } updateUI(null); } } private void updateUI(final FirebaseUser user) { if (user != null) { //Only saves if users does not exist already, based on FirebaseUser id. saveUserModel(user); Intent intent = new Intent(LoginActivity.this, AccountDetailsActivity.class); startActivity(intent); } } private void saveUserModel(final FirebaseUser user) { User user_model = new User( user.getUid(), user.getDisplayName(), user.getPhotoUrl() != null ? user.getPhotoUrl().toString() : null, null, null, false); user_model.save(); } }
true
d878d46d7c1b3eaeb7c1c2184bc642aefb080c27
Java
Vaishali-Govind/PopularMovies
/app/src/main/java/com/thirdarm/popularmovies/model/ProductionCompany.java
UTF-8
1,816
2.578125
3
[]
no_license
/* * Copyright (C) 2015 Teddy Rodriguez (TROD) * email: cia.123trod@gmail.com * github: TROD-123 * * For Udacity's Android Developer Nanodegree * P1-2: Popular Movies * * Currently for educational purposes only. */ package com.thirdarm.popularmovies.model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; /** * Created by TROD on 20150913. * * POJO created using jsonschema2pojo (http://www.jsonschema2pojo.org/). May not work for all * JSON data */ public class ProductionCompany implements Parcelable { @Expose private String name; @Expose private Integer id; /** * @return The name */ public String getName() { return name; } /** * @param name The name */ public void setName(String name) { this.name = name; } /** * @return The id */ public Integer getId() { return id; } /** * @param id The id */ public void setId(Integer id) { this.id = id; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeValue(this.id); } public ProductionCompany() { } protected ProductionCompany(Parcel in) { this.name = in.readString(); this.id = (Integer) in.readValue(Integer.class.getClassLoader()); } public static final Creator<ProductionCompany> CREATOR = new Creator<ProductionCompany>() { public ProductionCompany createFromParcel(Parcel source) { return new ProductionCompany(source); } public ProductionCompany[] newArray(int size) { return new ProductionCompany[size]; } }; }
true
a0672cf4f9d701ba002334b0881a319845e9059e
Java
Zakpav1/Sigma710
/app/src/main/java/functions/parsers/FunctionParser.java
UTF-8
19,630
3.015625
3
[]
no_license
package functions.parsers; import functions.Function; import functions.basic.*; import functions.meta.*; import android.util.Pair; import java.lang.reflect.InvocationTargetException; import java.util.*; import static java.lang.Character.isDigit; import static java.lang.Character.isLetter; public class FunctionParser {//TM парсер функции private Map<String, Function > funcNamesMap = new HashMap<>(); private String[] funcNames = new String[] {"arccos", "arcctg", "arcsin", "arctan", "cos", "ch", "ctg", "sin", "sh", "th", "tg", "cth", "abs"}; private char[] ops = new char[]{'+', '-', '*', '/', '^'}; private Map<Character, Function> opsNamesMap = new HashMap<>(); private String expression_; private char variable_; public FunctionParser(String expression, char variable){ expression_=expression; variable_=variable; opsNamesMap.put('+', new Sum(new Const(1), new Const(2))); //добавление в словарь, связвающий названия операций с классами операций opsNamesMap.put('-', new Sub(new Const(1), new Const(2))); opsNamesMap.put('*', new Mult(new Const(1), new Const(2))); opsNamesMap.put('/', new Div(new Const(1), new Const(2))); opsNamesMap.put('^', new Pow(new Const(1), new Const(2))); funcNamesMap.put("arccos", new Acos());//добавление в словарь, связвающий названия функций с классами функций funcNamesMap.put("arcsin", new Asin()); funcNamesMap.put("arcctg", new Acot()); funcNamesMap.put("arctg", new Atan()); funcNamesMap.put("cos", new Cos()); funcNamesMap.put("sin", new Sin()); funcNamesMap.put("tg", new Tan()); funcNamesMap.put("ctg", new Cot()); funcNamesMap.put("ch", new Cosh()); funcNamesMap.put("sh", new Sinh()); funcNamesMap.put("th", new Tanh()); funcNamesMap.put("cth", new Coth()); funcNamesMap.put("abs", new Abs()); } public Function parseFunction(){//вызов этой функции вызывается из main checkSpaces(); expression_ = expression_.replaceAll(" ", ""); checkCorrect(expression_); Function f = parse(expression_); return f; } private Function parse(String expression){//разбиение на функции List<Function> funcs = new ArrayList<>(); List<Character> ops = new ArrayList<>(); int wasAnOp = 1; //переменная состояний знака - (необходимо для корректной работы напр. -9) for (int i = 0; i < expression.length(); ++i){ if (expression.charAt(i)=='(') {//если встретил (, запуск parse от (...) if (wasAnOp==2) { funcs.add(new Sub(new Const(0), parse(expression.substring(i, findBracket(expression, i + 1) - 1)))); wasAnOp=0; } else { funcs.add(parse(expression.substring(i+1, findBracket(expression, i + 1)))); wasAnOp=0; } i=findBracket(expression, i+1); } else if (inOps(expression.charAt(i))!=-1){ //если встретил операцию if (expression.charAt(i)=='-'&&wasAnOp==1){ wasAnOp=2; } else { wasAnOp = 1; ops.add(expression.charAt(i)); } } else{ Pair<Function, Integer> val = recognizeFunc(expression, i); // распознавание функции if (wasAnOp==2) {//проверка для выражения типа +-function(замена на +(0-function)) funcs.add(new Sub(new Const(0), val.first)); wasAnOp=0; } else{ funcs.add(val.first); wasAnOp = 0; } i=val.second; } } return buildFunc(funcs, ops);//запуск построения выражения на основе имеющихся списков } private Function buildFunc(List<Function> funcs, List<Character> ops){ Class[] params = {Function.class, Function.class}; while (funcs.size()>1) {//выходим если размер = 0, ответ в funcs[0] if (funcs.size() == 2) {//если 2 функции в списке try { funcs.add(getOp(ops.get(0)).getClass().getConstructor(params).newInstance(funcs.get(0), funcs.get(1))); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { System.err.println("Error after split"); } funcs.remove(0); funcs.remove(0); ops.remove(0); } else { if (inOps(ops.get(0)) >= inOps(ops.get(1))) {//если 0 операция главнее 1-й в списке то соединяем 1-е две функции Function fresh = new Sin(); try { fresh = getOp(ops.get(0)).getClass().getConstructor(params).newInstance(funcs.get(0), funcs.get(1)); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { System.err.println("Error after split"); } funcs.remove(0); funcs.set(0, fresh); ops.remove(0); } else {//если 1-я операция главнее 0-й то ищем 1-ю операцию, равную по статусу 0-й и запуск buildFunc // от части списка от 0 до найденного Function fresh = new Sin(); fresh = buildFunc(funcs.subList(1, 1+findEqualOp(ops, ops.get(1))), ops.subList(1, findEqualOp(ops, ops.get(1)))); funcs.set(1, fresh);//установка найденной функции на 1-ю позицию } } } return funcs.get(0); } private int findEqualOp(List<Character> ops, char op){//поиск равной по статусу операции int status = inOps(op); if (op=='+'||op=='*'){ ++status; } for (int i =2; i < ops.size(); ++i){ if (inOps(ops.get(i))<=status){ return i; } } return ops.size(); } private Function getOp(char c){//возврат экземпляра функции операции равной по смыслу символу c на входе for (Map.Entry entry : opsNamesMap.entrySet()) { char op = (char) entry.getKey(); if (op == c){ return (Function)entry.getValue(); } } return opsNamesMap.get('+'); } private Pair<Function, Integer> recognizeFunc(String expression, int i) {//распознавание типа функции if (isLetter(expression.charAt(i)) && expression.charAt(i) != 'e' && logCheck(expression, i) == 0 && (expression.charAt(i) != variable_ || expression.length() - 1 != i && isLetter(expression.charAt(i + 1))) && (expression.length() - i >= 2 && !expression.substring(i, i + 2).equals("pi") || expression.length() - i < 2)) { for (Map.Entry entry : funcNamesMap.entrySet()) {//проверка на функции из словаря String str = (String) entry.getKey(); Function function = (Function) entry.getValue(); if (str.length() < expression.length() - i && str.equals(expression.substring(i, i + str.length()))) { i += str.length(); int temp = findBracket(expression, i); try { return new Pair<Function, Integer>(new Comp((Function) entry.getValue().getClass().newInstance(), parse(expression.substring(i + 1, temp))), temp); } catch (InstantiationException | IllegalAccessException e) { System.err.println("Exception in returning function"); } } } } else if (expression.length() - i >= 2 && expression.substring(i, i + 2).equals("pi"))// проверка на пи { return new Pair<Function, Integer>(new Const(Math.PI), i+1); } else if (expression.charAt(i) == 'e') {//проверка на е return new Pair<Function, Integer>(new Const(Math.E), i); } else if (expression.charAt(i) == variable_) {//проверка на переменную return new Pair<Function, Integer>(new Polynomial(new double[]{1, 0}), i); } else if (isDigit(expression.charAt(i))) {//проверка на число StringBuilder num = new StringBuilder(); while (i < expression.length() && (isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) { num.append(expression.charAt(i)); ++i; } double d = Double.parseDouble(num.toString()); --i; return new Pair<Function, Integer>(new Const(d), i); } else {//проверка на логарифм return getLog(expression, i); } return new Pair<Function, Integer>(new Const(0), i); } private void checkSpaces(){//проверка на пробелы напр. 2 + 1 2 int s =0; for (int i = 0; i < expression_.length(); ++i){ if (isDigit(expression_.charAt(i))&&s == 2){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } else if (isDigit(expression_.charAt(i))) { s = 1; } else if (expression_.charAt(i)==' '&&s==1){ s=2; } else{ s =0 ; } } } private void checkCorrect(String expression){ //проверка на правильность выражения if (!checkBrackets()){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } boolean isLastAnOp = true; boolean isLastANum = false; for (int i = 0; i < expression.length(); ++i){//проход по символам if (expression.charAt(i)=='('){ checkCorrect(expression.substring(i+1, findBracket(expression, i))); i=findBracket(expression, i)+1; if (i>=expression.length()){ return; } } else if (!isLetter(expression.charAt(i))&&!isDigit(expression.charAt(i))&&inOps(expression.charAt(i))==-1){//если ! или тп throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } if (isLetter(expression.charAt(i)) && expression.charAt(i)!='e' && logCheck(expression, i)==0 && (expression.charAt(i)!=variable_||expression.length()-1!=i&&isLetter(expression.charAt(i+1))) &&(expression.length()-i>=2&&!expression.substring(i, i+2).equals("pi")||expression.length()-i<2)){//блок для проверки функций if(isLastAnOp==false){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } int j =0; for (; j < funcNames.length; ++j){ if (funcNames[j].length()<expression.length()-i && funcNames[j].equals(expression.substring(i, i+funcNames[j].length()))){ i+=funcNames[j].length(); if (expression.charAt(i)!='('){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } else { checkCorrect(expression.substring(i+1, findBracket(expression, i))); i=findBracket(expression, i); if (i>=expression.length()){ return; } j = 20; } } if (j==funcNames.length-1){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } } } else if(expression.length()-i>=2&&expression.substring(i, i+2).equals("pi"))// проверка на пи { if(isLastAnOp==false){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } isLastAnOp=false; isLastANum=false; i+=1; if (i>=expression.length()) { return; } } else if (inOps(expression.charAt(i))!=-1){//проверка на операции if (i<expression.length()-1&&(i!=0||expression.charAt(i)=='-')){ isLastAnOp=true; isLastANum=false; checkCorrect(expression.substring(i+1, expression.length())); return; } else{ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } } else if (expression.charAt(i)=='e'||expression.charAt(i)==variable_){ if(isLastAnOp==false){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } isLastAnOp = false; isLastANum=false; } else if (isDigit(expression.charAt(i))){ if(isLastANum!=true &&isLastAnOp!=true){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } StringBuilder num = new StringBuilder(); while (i<expression.length()&&(isDigit(expression.charAt(i))||expression.charAt(i)=='.')){ num.append(expression.charAt(i)); ++i; } try { double d = Double.parseDouble(num.toString()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } isLastAnOp = false; isLastANum=true; --i; } else if (logCheck(expression, i)==0){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } else{ i+=logCheck(expression, i)-1; if (i>=expression.length()){ return; } } } return; } private Pair<Function, Integer> getLog(String expression, int i){// получение логарифма double d; i+=4; if (expression.charAt(i)=='e'){ i+=2; d = Math.E; } else if (expression.charAt(i)=='p'&&expression.charAt(i+1)=='i'){ i+=3; d = Math.PI; } else{ StringBuilder num = new StringBuilder(); while (i<expression.length()&&expression.charAt(i)!='('){ num.append(expression.charAt(i)); ++i; } d = Double.parseDouble(num.toString()); ++i; } return new Pair<Function, Integer>(new Comp(new Log(d), parse(expression.substring(i, findBracket(expression, i)))), findBracket(expression, i)); } private int logCheck(String expression, int i){ //проверка на логарифм if (expression.length()-i>=8&&expression.substring(i, i+4).equals("log_")){ i+=4; if (expression.charAt(i)=='e'&&expression.charAt(i+1)=='('){ i+=2; } else if (expression.charAt(i)=='p'&&expression.charAt(i+1)=='i'&&expression.charAt(i+2)=='('){ i+=3; } else if (!isDigit(expression.charAt(i))){ throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } else{ StringBuilder num = new StringBuilder(); while (i<expression.length()&&expression.charAt(i)!='('){ num.append(expression.charAt(i)); ++i; } try { double d = Double.parseDouble(num.toString()); } catch (NumberFormatException e) { throw new IllegalArgumentException("Недопустимая функция! (Wrong function!)"); } ++i; } checkCorrect(expression.substring(i, findBracket(expression, i))); return findBracket(expression, i)+1; } else { return 0; } } private int inOps(char s){ // проверка на принадлежность массиву операций for (int i =0; i<ops.length; ++i){ if (s==ops[i]){ return i; } } return -1; } private boolean checkBrackets(){ //проверка на корректное кол-во скобок int brackets = 0; int lastInd = 0; for (int i = 0; i < expression_.length() && brackets>=0; ++i){ if (expression_.charAt(i)=='('){ ++brackets; lastInd = i; } if (expression_.charAt(i)==')'){ --brackets; if (i-lastInd==1){ brackets=-1; } } } if (brackets==0){ return true; } return false; } private int findBracket(String expression, int index){ // возвращает индекс закрывающей скобки, принимает индекс следующий после открывающей int brackets = 0; int i =1; for (; i < expression.length()-index && brackets>=0; ++i){ if (expression.charAt(i+index)=='('){ ++brackets; } if (expression.charAt(i+index)==')'){ --brackets; } } return i+index-1; } }//\TM
true
db11073ed295a179316a141b05879fa129f48adc
Java
MathisHermann/Mezzago
/src/mezzago/commonClasses/channels/Mezzago_DirectMessage.java
UTF-8
1,936
2.4375
2
[ "BSD-3-Clause" ]
permissive
package mezzago.commonClasses.channels; import java.io.Serializable; import java.time.LocalDate; import mezzago.appClasses.Mezzago_Model; public class Mezzago_DirectMessage implements Serializable { /** * */ private static final long serialVersionUID = 1286743677073159992L; boolean isTesting; Mezzago_Model model; private String username; private boolean userOnline; private String localUser; private LocalDate lastInteractionDate; private boolean blocked; private String tempMessage = ""; private String allMessages = ""; private String lastMessage = ""; public Mezzago_DirectMessage(String username, boolean isOnline, String localUser) { this.username = username; this.userOnline = isOnline; this.localUser = localUser; // Date of the last interaction with this channel. Is needed for cleanup. lastInteractionDate = LocalDate.now(); blocked = false; } public LocalDate getLastInteractionDate() { return lastInteractionDate; } public boolean getBlocked() { return blocked; } public void setBlocked(boolean blocked) { this.blocked = blocked; } public String getAllMessages() { return allMessages; } public String getLastMessage() { return lastMessage; } public void addMessage(String message) { this.lastMessage = message; allMessages += lastMessage; lastInteractionDate = LocalDate.now(); } public String getUserName() { return username; } public boolean getOnline() { return userOnline; } public void setOnline(boolean userOnline) { this.userOnline = userOnline; } public void setTempMessage(String tempMessage) { lastInteractionDate = LocalDate.now(); if (tempMessage.length() != 0) this.tempMessage = tempMessage; } public String getTempMessage() { lastInteractionDate = LocalDate.now(); String m = tempMessage; tempMessage = ""; return m; } public void clearTempMessage() { tempMessage = ""; } }
true
05cbed395fc4781c1139422f14288ba4626b8ba3
Java
moutainhigh/shiyi
/shiyi-order/shiyi-order-service/src/main/java/com/baibei/shiyi/order/web/admin/AdminOrderSettingFeignController.java
UTF-8
1,500
1.992188
2
[]
no_license
package com.baibei.shiyi.order.web.admin; import com.baibei.shiyi.common.tool.api.ApiResult; import com.baibei.shiyi.common.tool.utils.BeanUtil; import com.baibei.shiyi.order.feign.base.dto.AdminOrderSettingDto; import com.baibei.shiyi.order.feign.base.vo.AdminOrderSettingVo; import com.baibei.shiyi.order.feign.client.IAdminOrderSettingFeign; import com.baibei.shiyi.order.model.OrderSetting; import com.baibei.shiyi.order.service.IOrderSettingService; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/admin/orderSetting") public class AdminOrderSettingFeignController implements IAdminOrderSettingFeign { private final IOrderSettingService orderSettingService; public AdminOrderSettingFeignController(IOrderSettingService orderSettingService) { this.orderSettingService = orderSettingService; } @Override public ApiResult setting(@RequestBody AdminOrderSettingDto adminOrderSettingDto) { orderSettingService.setting(adminOrderSettingDto); return ApiResult.success(); } @Override public ApiResult<AdminOrderSettingVo> findBySetting() { OrderSetting orderSetting = orderSettingService.findAll().get(0); AdminOrderSettingVo result = BeanUtil.copyProperties(orderSetting, AdminOrderSettingVo.class); return ApiResult.success(result); } }
true
fe4d9922b7a23a9a1f05ecc4eca203533cb8aebf
Java
joelmswearingen/MovieInfoDb
/src/main/java/movieDatabase/MovieListGUI.java
UTF-8
8,266
3.09375
3
[]
no_license
package movieDatabase; /** Created by Joel Swearingen May 2021 * This file manages a secondary GUI and all of it's buttons and displays */ import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MovieListGUI extends JFrame { private JPanel mainPanel; private JTable movieListTable; private JButton refreshListButton; private JButton updateMovieRatingButton; private JButton deleteMovieButton; private JLabel averageRatingLabel; private JButton closeButton; private DefaultTableModel defaultTableModel; private MovieController controller; MovieListGUI(MovieController controller) { this.controller = controller; // set basic functionality setTitle("Review and Update"); setContentPane(mainPanel); setPreferredSize(new Dimension(800, 450)); pack(); setVisible(true); setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); // take user ability away to close from windows constants - must use Close button // table setup defaultTableModel = new DefaultTableModel(0, 0) { public boolean isCellEditable(int row, int column) { return false; } }; movieListTable.setModel(defaultTableModel); movieListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); movieListTable.setRowSelectionAllowed(true); movieListTable.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 14)); movieListTable.getTableHeader().setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14)); movieListTable.setShowGrid(false); movieListTable.setShowHorizontalLines(true); movieListTable.setGridColor(Color.GRAY); // set column headers for the table in list and loop through list to set column headers String[] columns = {"Id", "Movie Title", "Release Year", "Metacritic Score", "My Rating"}; for ( String column : columns ) { defaultTableModel.addColumn(column); } // set column px width for each table column in list and loop through list to set each width TableColumnModel columnModel = movieListTable.getColumnModel(); int[] columnWidths = {56, 330, 120, 140, 120}; // total is 766, which is width of JTable for ( int i = 0; i < columnWidths.length; i++) { columnModel.getColumn(i).setPreferredWidth(columnWidths[i]); } // upon launch, populate movie list from db and get user stats getTableData(); setUserStats(); // call event listeners for button clicks eventListeners(); } private void eventListeners() { refreshListButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getTableData(); setUserStats(); } }); updateMovieRatingButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ensure a line is selected int row = movieListTable.getSelectedRow(); if (row == -1) { errorDialog("Please select a movie to update rating"); return; } try { int columns = movieListTable.getColumnCount(); row = movieListTable.getSelectedRow(); // gives you row index ArrayList<String> movieRecord = new ArrayList<>(); for (int i = 0; i < columns; i++) { String movieElement = movieListTable.getModel().getValueAt(row, i).toString(); movieRecord.add(movieElement); } // all fields in table are text, get data from each column by index String idAsString = movieRecord.get(0); String title = movieRecord.get(1); String year = movieRecord.get(2); String metascoreAsString = movieRecord.get(3); String userRatingAsString = movieRecord.get(4); // parse string to int as needed int id = Integer.parseInt(idAsString); int metascore = Integer.parseInt(metascoreAsString); double userRating = Double.parseDouble(userRatingAsString); // create date variable to update dateUpdated Date date = new Date(); Movie updateMovieRating = new Movie(id, title, year, metascore, userRating, date); Main.rateMovieGUI = new RateMovieGUI(controller, updateMovieRating); } catch (NumberFormatException nfe) { System.out.println("Error: " + nfe); } } }); deleteMovieButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ensure a line is selected int row = movieListTable.getSelectedRow(); if (row == -1) { errorDialog("Please select a movie to remove"); return; } try { row = movieListTable.getSelectedRow(); String movieIdAsString = movieListTable.getModel().getValueAt(row, 0).toString(); int movieId = Integer.parseInt(movieIdAsString); boolean deleted = controller.deleteMovieFromDatabase(movieId); if (deleted) { getTableData(); setUserStats(); JOptionPane.showMessageDialog(MovieListGUI.this, "Movie has been deleted"); } else { errorDialog("Movie was not deleted. Please try again."); } } catch (NumberFormatException nfe) { System.out.println("Error: " + nfe); } } }); closeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); Main.movieGUI.enableShowAllMoviesButton(); } }); } public void getTableData() { // query db to populate movie table. send results to setTableData method to populate table List<Movie> allMovies = controller.getAllMoviesFromDatabase(); setTableData(allMovies); } // set table with data from getTableData() method private void setTableData(List<Movie> movies) { defaultTableModel.setRowCount(0); for (Movie movie : movies) { String id = String.valueOf(movie.getId()); String title = movie.getTitle(); String year = movie.getYear(); String metascore = String.valueOf(movie.getMetascore()); String userRating = String.valueOf(movie.getUserRating()); String[] record = {id, title, year, metascore, userRating}; defaultTableModel.addRow(record); movieListTable.setRowSelectionInterval(0,0); } } public void setUserStats() { double avgRating = controller.getAverageMovieRating(); // if movie table is empty, query will return 0.0 as avgRating averageRatingLabel.setText("My Average Rating is " + avgRating + " stars"); } // word wrap in JOptionPane code found here: https://stackoverflow.com/questions/7861724/is-there-a-word-wrap-property-for-jlabel/7861833#7861833 private void errorDialog(String errorMessage) { String html = "<html><body style='width: %1spx'>%1s"; JOptionPane.showMessageDialog( MovieListGUI.this, String.format(html, 200, errorMessage), "Error", JOptionPane.ERROR_MESSAGE); } }
true
c29c427c451dec562b44802e732c859e9cbf2338
Java
detroitmatt/jMinesweeper
/src/util/Point.java
UTF-8
539
3.1875
3
[]
no_license
package util; /** * Created with IntelliJ IDEA. * User: Matt * Date: 5/17/12 * Time: 5:56 PM */ public class Point { public int x, y; public Point( int x, int y ) { this.x = x; this.y = y; } @Override public boolean equals( Object o ) { if(this == o){ return true; } if(o == null || getClass() != o.getClass()){ return false; } Point point = (Point) o; return (x != point.x) && (y != point.y); } @Override public int hashCode() { return 31 * (x + y); } }
true
30ede999c0b01f96a9e6de316b119e44400d7be7
Java
Java2AWD/Java2
/tests/dao/UserDAOHibernateImplTest.java
UTF-8
1,917
2.828125
3
[]
no_license
package dao; import java.sql.SQLException; import java.util.Date; import junit.framework.Assert; import org.junit.Test; import domain.User; public class UserDAOHibernateImplTest { @Test public void createUserTest(){ User testUser = new User(); testUser.setName("volk"); testUser.setPassword("les"); testUser.setEmail("volk@begilesbegi.com"); testUser.setUserDescription("Run! Forest! Run!"); UserDAOHibernateImpl dao = new UserDAOHibernateImpl(); try { dao.createUser(testUser); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertNotNull(dao.getUserByEmail("volk@begilesbegi.com")); } @Test public void getUserByIdTest(){ UserDAOHibernateImpl dao = new UserDAOHibernateImpl(); Assert.assertNotNull(dao.getUserById(1)); } @Test public void getUserByEmailTest(){ UserDAOHibernateImpl dao = new UserDAOHibernateImpl(); Assert.assertNotNull(dao.getUserByEmail("volk@begilesbegi.com")); } @Test public void removeUserTest(){ UserDAOHibernateImpl dao = new UserDAOHibernateImpl(); User user = new User(); user.setName("Vasilij"); user.setPassword("Pupkin"); user.setEmail("user@to.remove"); String user_description = new Date().toString(); user.setUserDescription(user_description); try { dao.createUser(user); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertTrue(dao.removeUser(dao.getUserByEmail("user@to.remove").getUserId())); } @Test public void updateUserTest(){ UserDAOHibernateImpl dao = new UserDAOHibernateImpl(); User user = dao.getUserById(1); // Update record with current time to make sure there is a difference. String user_description = new Date().toString(); user.setUserDescription(user_description); dao.updateUser(user); User newUser = dao.getUserById(1); Assert.assertTrue(newUser.getUserDescription().equals(user_description.toString())); } }
true
57e5682f6166e30822e445f0d992cb5b108a6088
Java
Abdul-Wasiy/MarketManagmentSystem
/src/main/java/hu/cs/se/service/UserServiceImp.java
UTF-8
1,038
2.4375
2
[]
no_license
package hu.cs.se.service; import hu.cs.se.model.User; import hu.cs.se.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class UserServiceImp implements UserService{ @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private UserRepository userRepository; @Override public void saveUser(User user) { userRepository.save(user); } @Override public Object findAll() { return userRepository.findAll(); } @Override public User findUserById(Long id) { return userRepository.getOne(id); } @Override public void deleteUserById(Long id) { userRepository.deleteById(id); } @Override public void createUser(User user) { user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); userRepository.save(user); } }
true
61c5d14732b696f46021656ac5c1e1060b1ae462
Java
LucasDiasRodrigues/Clima01Digital
/app/src/main/java/com/apps/lucas/clima01d/Adapters/RecyclerViewPlacesAdapter.java
UTF-8
2,601
2.34375
2
[]
no_license
package com.apps.lucas.clima01d.Adapters; import android.app.Activity; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.apps.lucas.clima01d.Activities.DetalhesActivity; import com.apps.lucas.clima01d.Modelo.Place; import com.apps.lucas.clima01d.R; import java.util.List; /** * Created by Lucas on 22/02/2017. */ public class RecyclerViewPlacesAdapter extends RecyclerView.Adapter<RecyclerViewPlacesAdapter.MyViewHolder> { private static List<Place> places; private static Context context; private LayoutInflater layoutInflater; public RecyclerViewPlacesAdapter(List<Place> places, Context context) { this.places = places; this.context = context; layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = layoutInflater.inflate(R.layout.item_list_cidades, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.txtCapital.setText(places.get(position).getNomeCidade()); } @Override public int getItemCount() { return places.size(); } public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView txtCapital; public MyViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); txtCapital = (TextView) itemView.findViewById(R.id.txtCapital); } @Override public void onClick(View view) { Place placeSelecionado = places.get(getAdapterPosition()); Intent intent = new Intent(context, DetalhesActivity.class); intent.putExtra("place", placeSelecionado); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation((Activity)context, txtCapital, "place"); context.startActivity(intent, options.toBundle()); } else { context.startActivity(intent); } } } }
true
c3c40a39406e099e5a296b4803c383fe05c0da2f
Java
gggdwdn/hzhg
/src/main/java/com/aptech/business/companyDynamic/dao/CompanyDynamicDaoImpl.java
UTF-8
608
1.765625
2
[]
no_license
package com.aptech.business.companyDynamic.dao; import org.springframework.stereotype.Repository; import com.aptech.business.companyDynamic.domain.CompanyDynamicEntity; import com.aptech.framework.orm.AncestorDao; /** * * 公告应用数据类 * * @author * @created 2017-10-10 17:20:46 * @lastModified * @history * */ @Repository("companyDynamicDao") public class CompanyDynamicDaoImpl extends AncestorDao<CompanyDynamicEntity> implements CompanyDynamicDao{ @Override public String getNameSpace() { // TODO Auto-generated method stub return "com.aptech.business.companyDynamic"; } }
true
6e0cdcc1c5a3b673bc54f79357169b6528363a4c
Java
adamturski/TrakGps
/src/main/java/pl/com/turski/gps/listener/LocationListenerImpl.java
UTF-8
1,026
2.0625
2
[]
no_license
package pl.com.turski.gps.listener; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import pl.com.turski.gps.App; /** * User: Adam */ public class LocationListenerImpl implements LocationListener { public void onLocationChanged(Location location) { Context appCtx = App.getAppContext(); double latitude, longitude; latitude = location.getLatitude(); longitude = location.getLongitude(); Intent filterRes = new Intent(); filterRes.setAction("pl.com.turski.trak.gps.intent.action.LOCATION"); filterRes.putExtra("latitude", latitude); filterRes.putExtra("longitude", longitude); appCtx.sendBroadcast(filterRes); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }
true
03554252e7b212eea87cdb55bd74ba0d6c7c4e7f
Java
xiejames/pointunion
/pointunion/src/com/pointunion/dao/MerchantAccountDao.java
UTF-8
547
1.695313
2
[]
no_license
package com.pointunion.dao; import org.springframework.dao.DataAccessException; import com.pointunion.domain.dto.MerchantAccount; public interface MerchantAccountDao { public MerchantAccount getMerchantAccountByPK(String maNo) throws DataAccessException; public void insertMerchantAccount(MerchantAccount merchantAccount) throws DataAccessException; public void updateMerchantAccount(MerchantAccount merchantAccount) throws DataAccessException; public void deleteMerchantAccount(String maNo) throws DataAccessException; }
true
f020274f3b8036fcff3291513b31464e1e4d985c
Java
OresytO/MyPrograms
/Workspace/SoftServe_Task/lv-098_task/Ekkel/src/operators/Exercise10.java
UTF-8
585
3.203125
3
[]
no_license
/** * */ package operators; /** * @author orecto * */ public class Exercise10 { public static void main(String[] args) { int i1 = 0b1010101010; int i2 = 0b0101011101; System.out.println("i1 => " + Integer.toBinaryString(i1)); System.out.println("i2 => " + Integer.toBinaryString(i2)); System.out.println("i1 & i2 => " + Integer.toBinaryString(i1 & i2)); System.out.println("i1 | i2 => " + Integer.toBinaryString(i1 | i2)); System.out.println("i1 ^ i2 => " + Integer.toBinaryString(i1 ^ i2)); System.out.println("~i2 => " + Integer.toBinaryString(~i2)); } }
true
5598aa60b54722e6f7db125c5d6c68b0eb83164d
Java
serrapos/prueba-tecnica
/back/src/test/java/es/serrapos/pruebatecnica/model/mappers/CourseMapperTest.java
UTF-8
2,752
2.609375
3
[]
no_license
package es.serrapos.pruebatecnica.model.mappers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.List; import java.util.stream.Collectors; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringRunner; import es.serrapos.pruebatecnica.model.entities.Course; import es.serrapos.pruebatecnica.model.entities.Teacher; import es.serrapos.pruebatecnica.model.enums.CourseLevel; @RunWith(SpringRunner.class) @MybatisTest public class CourseMapperTest { @Autowired private CourseMapper courseMapper; @Test public void fullProcess() { List<Course> allCourseInit = courseMapper.getAll(); // Insert test Course course = inicializarCourseValido(); course.setId(null); courseMapper.insert(course); assertNotNull(course.getId()); // Get By Id test Course courseGet = courseMapper.getById(course.getId()); assertEquals(course.getId(), courseGet.getId()); // GetAll test List<Course> allCourseAfterInsert = courseMapper.getAll(); assertEquals(allCourseInit.size() + 1, allCourseAfterInsert.size()); // Update tets course.setTitle("Test Update"); courseMapper.update(course); assertEquals("Test Update", course.getTitle()); // Find by title test Course courseByTitle = courseMapper.getByTitle("Test Update"); assertEquals("Test Update", courseByTitle.getTitle()); // Title not found test Course courseNotFound = courseMapper.getByTitle("Courese Not Found"); assertNull(courseNotFound); assertEquals("Test Update", courseByTitle.getTitle()); // Exist by title test boolean existsByTitle = courseMapper.checkCourseExistsByTitle("Test Update"); assertEquals(true, existsByTitle); boolean existsByTitleNotFound = courseMapper.checkCourseExistsByTitle("Courese Not Found"); assertEquals(false, existsByTitleNotFound); // Filter by Active List<Course> coursesNoActive = courseMapper.getAllActive(); List<Course> courseAfterFilter = coursesNoActive.stream().filter(c -> !c.getState()) .collect(Collectors.toList()); assertEquals(0, courseAfterFilter.size()); } public static Course inicializarCourseValido() { try { Course course = new Course(); Teacher teacher = new Teacher(); teacher.setId(1l); course.setId(50L); course.setFileId(null); course.setLevel(CourseLevel.BASICO); course.setNumberOfHours(5); course.setState(true); course.setTeacher(teacher); course.setTitle("Curso Mockito"); return course; } catch (Throwable e) { return null; } } }
true
d9810908a0d5900f5e8ebccf1157f703535fb564
Java
hundun000/theater-engine
/src/main/java/theaterengine/entity/Role.java
UTF-8
3,826
2.546875
3
[]
no_license
package theaterengine.entity; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.imageio.ImageIO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import theaterengine.StageApplication; import theaterengine.core.World; import theaterengine.entity.component.MoveComponent; import theaterengine.gui.StagePanel; import theaterengine.script.tool.ScalaTool; import theaterengine.task.ConditionTask; import theaterengine.task.DelayTask; /** * * @author hundun * Created on 2019/04/01 */ public class Role extends BaseItem implements IGameObject{ private static final Logger logger = LoggerFactory.getLogger(Role.class); private String speaking = ""; private int currentSpeakEndIndex; public static final int radius = (int) ScalaTool.meterToPixel(0.3); private static BufferedImage talkBubbleImage; static { try { talkBubbleImage = ImageIO.read(new File("./data/images/talk_bubble.png")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Role(String name, double x, double y) { super(name, x, y); this.moveComponent = new MoveComponent(this); } public void setSpeaking(String speaking) { this.currentSpeakEndIndex = 0; this.speaking = speaking; logger.debug("{}.speaking set to {}", name, speaking); } public void setCurrentSpeakEndIndex(int currentSpeakEndIndex) { this.currentSpeakEndIndex = currentSpeakEndIndex; } public String getCompletedSpeaking() { return speaking; } public String getCurrentSpeaking() { return speaking.substring(0, Math.min(currentSpeakEndIndex, speaking.length())); } public void moveToTarget(double additionX, double additionY) { // TODO Auto-generated method stub super.move(additionX, additionY); } @Override public void updateGame(World world) { for (ConditionTask conditionTask : this.conditionTasks) { conditionTask.clockArrive(); } } @Override public void renderGame(Graphics2D g2d, World world) { Role role = this; Font fontItemName = StagePanel.fontItemName; Font speakFont = StagePanel.speakFont; g2d.setColor(Color.BLACK); g2d.drawOval((int)role.getX() - Role.radius, (int)role.getY() - Role.radius, 2 * Role.radius, 2 * Role.radius); g2d.setColor(Color.GRAY); g2d.fillOval((int)role.getX() - Role.radius, (int)role.getY() - Role.radius, 2 * Role.radius, 2 * Role.radius); int roleX = (int) (role.getX() - Role.radius + 0.2 * fontItemName.getSize()); int roleY = (int) (role.getY() + 0.5 * fontItemName.getSize()); if (role.getCompletedSpeaking().length() != 0) { String text = role.getName() + " : " + role.getCurrentSpeaking(); g2d.setColor(Color.BLACK); g2d.setFont(speakFont); int speakX = StageApplication.stagePanelWidth / 2 - text.length() * speakFont.getSize() / 2; int speakY = StageApplication.stagePanelHeight - speakFont.getSize() + 20; g2d.drawString(text, speakX, speakY); g2d.drawImage(talkBubbleImage, roleX + Role.radius, roleY - Role.radius - talkBubbleImage.getHeight(), null); } g2d.setColor(Color.BLACK); g2d.setFont(fontItemName); g2d.drawString(role.getName(), roleX, roleY); } public void clearSpeaking() { this.speaking = ""; logger.debug("{}.speaking cleared", name); } }
true
d079a8ab67563bea0d4b694e2d80d15fd5cc904f
Java
taipingli666/myrs
/src/main/java/com/choice/domain/entity/external/MessageInfo.java
UTF-8
1,987
2.140625
2
[]
no_license
package com.choice.domain.entity.external; public class MessageInfo { private int id; //短信唯一标识 private String msgId; //短信内容 private String msgContent; private String tel; //状态 1未发送 2已发送 private int status; private String msgKey; //预约类型 1 住院 2门诊 private int externalType; //预约门诊/住院id private String externalId; private String createTime; private String updateTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId; } public String getMsgContent() { return msgContent; } public void setMsgContent(String msgContent) { this.msgContent = msgContent; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getExternalType() { return externalType; } public void setExternalType(int externalType) { this.externalType = externalType; } public String getExternalId() { return externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getMsgKey() { return msgKey; } public void setMsgKey(String msgKey) { this.msgKey = msgKey; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getUpdateTime() { return updateTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } }
true
3060457fc5c7c0b7605ed5778c18b85ae8238421
Java
morylee/sc-learn
/main-service/user-service/src/main/java/com/mm/user/hystrix/OauthFeignServiceImpl.java
UTF-8
425
1.710938
2
[]
no_license
package com.mm.user.hystrix; import com.mm.user.feign.OauthFeignService; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.stereotype.Component; import java.util.Map; /** * @author mory.lee */ @Component public class OauthFeignServiceImpl implements OauthFeignService { @Override public OAuth2AccessToken oauthToken(Map<String, String> parameters) { return null; } }
true
06ad418b6fcdcc2edefbad956e6e4fc25681aa22
Java
zhangliuyang1/testJava
/src/com/nggirl/test/thinkinjva/IO/InputFromConsole.java
UTF-8
412
2.59375
3
[]
no_license
package com.nggirl.test.thinkinjva.IO; import java.io.IOException; import java.util.Scanner; /** * @author zhangliuyang * @email zhangliuyang@nggirl.com.cn * @date 2016/8/31 15:08 */ public class InputFromConsole { public static void main(String[] args) throws IOException { byte[] input = new byte[1024]; System.in.read(input); System.out.println("your input is:" + new String(input)); } }
true
6ed97841edc56561d6a2135c9cf827c334d97582
Java
Talend/apache-camel
/components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/MessageResponse.java
UTF-8
1,849
1.960938
2
[ "Apache-2.0" ]
permissive
/* * 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.camel.component.whatsapp.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class MessageResponse { @JsonProperty("messaging_product") private String messagingProduct = "whatsapp"; private List<Contact> contacts; private List<Message> messages; private String id; public MessageResponse() { } public String getMessagingProduct() { return messagingProduct; } public void setMessagingProduct(String messagingProduct) { this.messagingProduct = messagingProduct; } public List<Contact> getContacts() { return contacts; } public void setContacts(List<Contact> contacts) { this.contacts = contacts; } public List<Message> getMessages() { return messages; } public void setMessages(List<Message> messages) { this.messages = messages; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
true
9d1735642e9f9e6153aa02006a5a62171a3babfc
Java
cdowding-sl/datahelix
/generator/src/main/java/com/scottlogic/deg/generator/generation/grouped/FieldSpecGroupDateHelper.java
UTF-8
2,714
2.234375
2
[ "ICU", "EPL-1.0", "EPL-2.0", "CDDL-1.0", "Apache-2.0", "MIT", "BSD-2-Clause", "BSD-3-Clause", "CC0-1.0", "LicenseRef-scancode-generic-cla" ]
permissive
package com.scottlogic.deg.generator.generation.grouped; import com.scottlogic.deg.common.profile.Field; import com.scottlogic.deg.generator.fieldspecs.FieldSpec; import com.scottlogic.deg.generator.fieldspecs.FieldSpecGroup; import com.scottlogic.deg.generator.fieldspecs.FieldSpecMerger; import com.scottlogic.deg.generator.fieldspecs.FieldWithFieldSpec; import com.scottlogic.deg.generator.fieldspecs.relations.FieldSpecRelations; import com.scottlogic.deg.generator.restrictions.linear.Limit; import com.scottlogic.deg.generator.restrictions.linear.LinearRestrictions; import com.scottlogic.deg.generator.restrictions.linear.LinearRestrictionsFactory; import java.time.OffsetDateTime; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class FieldSpecGroupDateHelper { public static FieldSpecGroup adjustBoundsOfDate(Field field, OffsetDateTime value, FieldSpecGroup group) { Limit<OffsetDateTime> limit = new Limit<>(value, true); LinearRestrictions<OffsetDateTime> restrictions = LinearRestrictionsFactory.createDateTimeRestrictions(limit,limit); FieldSpec newSpec = FieldSpec.fromRestriction(restrictions).withNotNull(); return adjustBoundsOfDateFromFieldSpec(field, newSpec, group); } private static FieldSpecGroup adjustBoundsOfDateFromFieldSpec(Field field, FieldSpec newSpec, FieldSpecGroup group) { Map<Field, FieldSpec> specs = new HashMap<>(group.fieldSpecs()); specs.replace(field, newSpec); Set<FieldSpecRelations> relations = group.relations().stream() .filter(relation -> relation.main().equals(field) || relation.other().equals(field)) .collect(Collectors.toSet()); Stream<FieldWithFieldSpec> relationsOrdered = relations.stream() .map(relation -> relation.main().equals(field) ? relation : relation.inverse()) .map(relation -> new FieldWithFieldSpec(relation.other(), relation.reduceToRelatedFieldSpec(newSpec))); relationsOrdered.forEach( wrapper -> applyToFieldSpecMap( specs, specs.get(wrapper.field()), wrapper.fieldSpec(), wrapper.field())); return new FieldSpecGroup(specs, relations); } private static void applyToFieldSpecMap(Map<Field, FieldSpec> map, FieldSpec left, FieldSpec right, Field field) { FieldSpecMerger merger = new FieldSpecMerger(); FieldSpec newSpec = merger.merge(left, right) .orElseThrow(() -> new IllegalArgumentException("Failed to create field spec from value")); map.put(field, newSpec); } }
true
22df1b1db609e8aefa27262f4c07a3e542f52b99
Java
NaveenAdmin/EpmsCodeShare
/src/main/java/com/hpcl/dao/SocketDao.java
UTF-8
357
1.796875
2
[]
no_license
package com.hpcl.dao; import java.util.List; import com.hpcl.persistence.AppParameters; public interface SocketDao { public void saveDeviceDetails(AppParameters twoFieldPersistence,String tableName ); public void saveAlertDetails(AppParameters twoFieldPersistence,String tableName ); public List<AppParameters> getAllDeviceDetails(String deviceID); }
true
4bb1c9f43dcaa72907702f92438647e0b29f2376
Java
sushovankarmakar/cricky
/src/main/java/com/cricket/cricky/model/common/Statistics.java
UTF-8
210
1.679688
2
[]
no_license
package com.cricket.cricky.model.common; import java.time.LocalDateTime; import lombok.Data; @Data public abstract class Statistics { private LocalDateTime createdAt; private LocalDateTime updatedAt; }
true
2e7f7b941da69f7e16cad1ba631247263f8c0d7d
Java
IndrakantiPraveenKalyan/Project-2
/SumOfSquares.java
UTF-8
587
3.640625
4
[]
no_license
package Assignment2; import java.util.*; public class SumOfSquares { public static void main(String[] args) { int sum=0,sum1=0,sum2=0; Scanner input=new Scanner(System.in); System.out.println("Enter value of n: "); int n=input.nextInt(); for(int i=1;i<=n;i++) { int square=i*i; sum1+=square; } System.out.println(sum1); for(int i=1;i<=n;i++) { sum+=i; } sum2=sum*sum; System.out.println(sum2); int difference=0; if(sum1>sum2) { difference=sum1-sum2; } else { difference=sum2-sum1; } System.out.println(difference); } }
true
bee6cc21a31a19bc77bb96af24ecb4e4b12f0da0
Java
singhaniatanay/Competitive-Programming
/MakeMyTrip/isMirror_n_ary_tree.java
UTF-8
1,598
3.375
3
[ "MIT" ]
permissive
import java.io.*; import java.util.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int V = sc.nextInt(); NTree ntree1 = new NTree(V); NTree ntree2 = new NTree(V); int e = sc.nextInt(); for(int i = 0; i < e; i++){ ntree1.addEdge(sc.nextInt(),sc.nextInt()); } for(int i = 0; i < e; i++){ ntree2.addEdge(sc.nextInt(),sc.nextInt()); } boolean isMirror = true; for(int j = 0; j < V&&isMirror; j++){ int n1Size = ntree1.adj.get(j).size(); int n2Size = ntree2.adj.get(j).size(); if(n1Size==n2Size){ for(int i = 0; i< n1Size && isMirror; i++ ){ int n1 = ntree1.adj.get(j).get(i); int n2 = ntree2.adj.get(j).get(n1Size-i-1); if(n1!=n2){ isMirror = false; } } }else{ isMirror = false; } } if(isMirror){ System.out.println(1); }else{ System.out.println(0); } t--; } } static class NTree { int V ; ArrayList<LinkedList<Integer>> adj; NTree(int V){ this.V = V; adj = new ArrayList<>(); for(int i = 0 ; i < V; i++){ adj.add(new LinkedList<>()); } } public void addEdge(int u, int v){ adj.get(u-1).add(v-1); } } }
true
20de880aede6a4350331f0d6072deefded7dcdd4
Java
NexThoughts/Rohit-Team
/src/main/java/com/nexthoughts/tracker/model/Milestone.java
UTF-8
1,773
2.359375
2
[]
no_license
package com.nexthoughts.tracker.model; import javax.persistence.*; import java.util.Date; import java.util.UUID; @Entity @Table(name = "milestone") public class Milestone { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String startDate; private String endDate; private Date dateCreated = new Date(); private Date lastUpdated; private String uuid = UUID.randomUUID().toString(); @ManyToOne(fetch = FetchType.LAZY) private User createdBy; public Milestone() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public User getCreatedBy() { return createdBy; } public void setCreatedBy(User createdBy) { this.createdBy = createdBy; } }
true
5637d248e2c4d8e532988bbdfdfd476cd9c97bd0
Java
shidobecker/RetrofitGson
/app/src/main/java/julio/com/br/retrofitgson/api/Controller.java
UTF-8
2,043
2.3125
2
[]
no_license
package julio.com.br.retrofitgson.api; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.List; import julio.com.br.retrofitgson.model.Change; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by Shido on 05/03/2017. */ public class Controller { static final String BASE_URL = "https://git.eclipse.org/r/"; public void start(){ Gson gson = new GsonBuilder().setLenient().create(); Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build(); GerritAPI gerritAPI = retrofit.create(GerritAPI.class); // Call<List<Change>> call = gerritAPI.loadChangeList("status:open"); Call<List<Change>> call = gerritAPI.loadChangeList(null); call.enqueue(new Callback<List<Change>>() { @Override public void onResponse(Call<List<Change>> call, Response<List<Change>> response) { if(response.isSuccessful()){ List<Change> changeList = response.body(); for (Change g: changeList ) { Log.e("TAG", g.getSubject()); } } } @Override public void onFailure(Call<List<Change>> call, Throwable t) { t.printStackTrace(); } }); } /*@Override public void onResponse(Call<List<Change>> call, Response<List<Change>> response) { if(response.isSuccessful()){ List<Change> changeList = response.body(); for (Change g: changeList ) { Log.e("TAG", g.getSubject()); } } } @Override public void onFailure(Call<List<Change>> call, Throwable t) { t.printStackTrace(); }*/ }
true
55fd4f5c04bb2616a3438e40d7485803bc3241c7
Java
shanhelin/webwork
/src/main/java/com/webwork/entity/Department.java
UTF-8
1,479
2.484375
2
[]
no_license
package com.webwork.entity; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import javax.persistence.*; import java.util.Set; @Entity @Table(name = "department", schema = "curricula") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "department_name") private String departmentName; @OneToMany(mappedBy = "department") @LazyCollection(LazyCollectionOption.EXTRA) private Set<Clas> classes; @OneToMany(mappedBy = "department") @LazyCollection(LazyCollectionOption.TRUE) private Set<Teacher> teachers; public Department() { super(); } public Department(int id, String departmentName) { super(); this.id = id; this.departmentName = departmentName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public Set<Clas> getClasses() { return classes; } public void setClasses(Set<Clas> classes) { this.classes = classes; } public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } @Override public String toString() { return "Department [id=" + id + ", departmentName=" + departmentName + "]"; } }
true
bb013391440b19a0cc79d1bef3bb95c56240deb4
Java
Fighter-zzp/OneZeroTowFour
/one-four-travel-user/src/main/java/com/travel/one/four/controller/NavController.java
UTF-8
744
2.1875
2
[]
no_license
package com.travel.one.four.controller; import com.travel.one.four.domain.Nav; import com.travel.one.four.service.NavService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/nav") public class NavController { @Autowired private NavService navService; @GetMapping("/findNavAll") public List<Nav> findNavAll(){ List<Nav> navAll = navService.findNavAll(); for(Nav n:navAll){ System.out.println(n); } return navAll; } }
true
c84f8ed334c716f9e5be8ca6e94f2da110e3e9fc
Java
snkey-todo/MobileshopForBook
/MobileShop/src/com/huatec/edu/mobileshop/controller/backbone/BrandController2.java
UTF-8
4,625
2.078125
2
[]
no_license
package com.huatec.edu.mobileshop.controller.backbone; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.huatec.edu.mobileshop.service.BrandService; import com.huatec.edu.mobileshop.util.MSUtil; import com.huatec.edu.mobileshop.util.Result; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; import net.sf.json.JSONObject; @Controller @RequestMapping("/backbone/brand") public class BrandController2 { @Resource private BrandService brandService; //新增品牌 @RequestMapping(method=RequestMethod.POST) @ResponseBody @ApiOperation(value="新增品牌") public Result add(HttpServletRequest request){ Map jmap=MSUtil.getParam(request); String name=(String) jmap.get("name"); String logo=(String) jmap.get("logo"); String keywords=(String) jmap.get("keywords"); String description=(String) jmap.get("description"); String url=(String) jmap.get("url"); Result result=brandService.addBrand(name, logo, keywords, description, url); return result; } //加载所有品牌(分页) @RequestMapping(value="/page/{pageId}",method=RequestMethod.GET) @ResponseBody @ApiOperation(value="加载所有品牌(分页)") public Result loadAllByPage(@PathVariable("pageId") int pageId){ Result result=brandService.loadAllBrandsByPage(pageId); return result; } //根据id加载品牌 @RequestMapping(value="/{brandId}",method=RequestMethod.GET) @ResponseBody @ApiOperation(value="加载品牌信息") public Result loadById(@PathVariable("brandId") int brandId){ Result result=brandService.loadBrandById(brandId); return result; } //根据id更新 @RequestMapping(value="/{brandId}",method=RequestMethod.PUT) @ResponseBody @ApiOperation(value="更新品牌信息") public Result updateById(@ApiParam(value="品牌编号")@PathVariable("brandId") int brandId, HttpServletRequest request){ Map jmap=MSUtil.getParam(request); String name=(String) jmap.get("name"); String logo=(String) jmap.get("logo"); String keywords=(String) jmap.get("keywords"); String description=(String) jmap.get("description"); String url=(String) jmap.get("url"); Result result=brandService.updateBrand(brandId, name, logo, keywords, description, url); return result; } //根据id删除 @RequestMapping(value="/{brandId}",method=RequestMethod.DELETE) @ResponseBody @ApiOperation(value="删除品牌") public Result deleteById(@PathVariable("brandId") int brandId){ Result result=brandService.deleteBrandById(brandId); return result; } //根据id更新是否可用 @RequestMapping(value="/disabled/{brandId}",method=RequestMethod.PUT) @ResponseBody @ApiOperation(value="更新品牌状态(是否可用)") public Result updateDisabled(@ApiParam(value="品牌编号")@PathVariable("brandId") int brandId, HttpServletRequest request){ Map jmap=MSUtil.getParam(request); int disabled=Integer.parseInt((String) jmap.get("disabled")); Result result=brandService.updateDisabled(brandId, disabled); return result; } //加载所有可用的品牌 @RequestMapping(value="/disabled",method=RequestMethod.GET) @ResponseBody @ApiOperation(value="加载所有可用的品牌") public Result loadByDisabled(){ Result result=brandService.loadBrandByDisabled(); return result; } /*//通过request流获取参数 public Map getParam(HttpServletRequest request){ BufferedReader br; try { br = new BufferedReader(new InputStreamReader( (ServletInputStream) request.getInputStream())); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } String appParam=sb.toString(); System.out.println(appParam); JSONObject jsonParam=JSONObject.fromObject(appParam); Map jmap=jsonParam; return jmap; } catch (IOException e) { e.printStackTrace(); } return null; }*/ }
true
ed5f5dd9f0a4bc43de18c2b60d70154838ea1749
Java
js-lib-com/commons
/src/main/java/com/jslib/format/ShortDate.java
UTF-8
349
2.53125
3
[ "Zlib", "EPL-1.0", "CDDL-1.0", "LZMA-exception", "bzip2-1.0.6", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "CPL-1.0" ]
permissive
package com.jslib.format; import java.text.DateFormat; import java.util.Locale; /** * Short date format - 3/15/64. * * @author Iulian Rotaru */ public final class ShortDate extends DateTimeFormat { @Override protected DateFormat createDateFormat(Locale locale) { return DateFormat.getDateInstance(DateFormat.SHORT, locale); } }
true
df641d3457da6a6778e82bf8c86195cb90118206
Java
nim5023/DungeonCrawl
/src/dungeoncrawler/Abilities/DragonBreath.java
UTF-8
1,955
2.828125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dungeoncrawler.Abilities; import dungeoncrawler.Abilities.Animations.MissileAnimation; import dungeoncrawler.Characters.Hero; import dungeoncrawler.DungeonCrawler; import dungeoncrawler.Characters.Monster; import dungeoncrawler.ImageHandler; import dungeoncrawler.StateHandlers.BattleHandler; /** * * @author Nick */ public class DragonBreath extends Ability{ public double Fury; public DragonBreath(){ super(); name = "DragonBreath"; } public void BurnHero(Monster monster, Hero hero, double numAlive,double Fury,double Strength){ if(hero.isAlive){ double ratio = Math.pow(monster.Magic,2) / (Math.pow(monster.Magic,2) + Math.pow(hero.Magic,2)); int damage = (int)(ratio * monster.Power*Strength*(Fury+1.0)/numAlive); damage = monster.reducedDamage(damage,hero); DungeonCrawler.AnimationList.push(new MissileAnimation(monster.X,monster.Y,hero.X,hero.Y,ImageHandler.ImgFireBall,45)); BattleHandler.addBattleText(" "+hero.name+" takes "+damage+" Damage"); hero.TakeDamage( damage); } } public void ActivateAbility(Hero hero, Monster monster,Hero heroTarget,double fury,double Strength){ BattleHandler.addBattleText(monster.name+" uses Incinerate "); int numALive = 0; if(DungeonCrawler.War.isAlive) numALive++; if(DungeonCrawler.Blm.isAlive) numALive++; if(DungeonCrawler.Ftr.isAlive) numALive++; BurnHero(monster,DungeonCrawler.Ftr,numALive,fury,Strength); BurnHero(monster,DungeonCrawler.War,numALive,fury,Strength); BurnHero(monster,DungeonCrawler.Blm,numALive,fury,Strength); } }
true
6fce5bb7eeace0afd66777755bd8f80bb340e8ea
Java
shroff-kandarp/EcommarceApp
/app/src/main/java/com/fragment/SignInFragment.java
UTF-8
6,047
2.03125
2
[]
no_license
package com.fragment; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.ecommarceapp.AppLoginActivity; import com.ecommarceapp.MainActivity; import com.ecommarceapp.R; import com.general.files.ExecuteWebServerUrl; import com.general.files.GeneralFunctions; import com.general.files.StartActProcess; import com.utils.Utils; import com.view.CreateRoundedView; import com.view.MButton; import com.view.MTextView; import com.view.MaterialRippleLayout; import com.view.editBox.MaterialEditText; import java.util.HashMap; /** * A simple {@link Fragment} subclass. */ public class SignInFragment extends Fragment { View view; GeneralFunctions generalFunc; MaterialEditText emailBox; MaterialEditText passwordBox; MButton btn_type2; MTextView forgetPassTxt; MTextView goToRegisterTxtView; AppLoginActivity appLoginAct; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_sign_in, container, false); appLoginAct = (AppLoginActivity) getActivity(); generalFunc = appLoginAct.generalFunc; emailBox = (MaterialEditText) view.findViewById(R.id.emailBox); passwordBox = (MaterialEditText) view.findViewById(R.id.passwordBox); forgetPassTxt = (MTextView) view.findViewById(R.id.forgetPassTxt); goToRegisterTxtView = (MTextView) view.findViewById(R.id.goToRegisterTxtView); btn_type2 = ((MaterialRippleLayout) view.findViewById(R.id.btn_type2)).getChildView(); setLabels(); btn_type2.setId(Utils.generateViewId()); passwordBox.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); passwordBox.setTypeface(generalFunc.getDefaultFont(getActContext())); emailBox.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS | InputType.TYPE_CLASS_TEXT); btn_type2.setOnClickListener(new setOnClickList()); forgetPassTxt.setOnClickListener(new setOnClickList()); goToRegisterTxtView.setOnClickListener(new setOnClickList()); new CreateRoundedView(Color.parseColor("#FFFFFF"), Utils.dipToPixels(getActContext(), 5), Utils.dipToPixels(getActContext(), 1), getResources().getColor(R.color.appThemeColor_1), goToRegisterTxtView); return view; } public void setLabels() { emailBox.setBothText("Email", "Enter your email"); passwordBox.setBothText("Password", "Enter your password"); btn_type2.setText("SignIn"); appLoginAct.headerTxtView.setText("Sign in to access your orders, wishlist and your account."); } public Context getActContext() { return appLoginAct; } public class setOnClickList implements View.OnClickListener { @Override public void onClick(View view) { int i = view.getId(); if (i == R.id.goToRegisterTxtView) { SignUpFragment signUpFrag = new SignUpFragment(); appLoginAct.signUpFrag = signUpFrag; appLoginAct.loadFragment(signUpFrag); } else if (i == btn_type2.getId()) { checkData(); } } } public void checkData() { boolean emailEntered = Utils.checkText(emailBox) ? (generalFunc.isEmailValid(Utils.getText(emailBox)) ? true : Utils.setErrorFields(emailBox, "Invalid email")) : Utils.setErrorFields(emailBox, "Required"); boolean passwordEntered = Utils.checkText(passwordBox) ? (Utils.getText(passwordBox).contains(" ") ? Utils.setErrorFields(passwordBox, "Password should not contain whitespace.") : (Utils.getText(passwordBox).length() >= Utils.minPasswordLength ? true : Utils.setErrorFields(passwordBox, "Password must be" + " " + Utils.minPasswordLength + " or more character long."))) : Utils.setErrorFields(passwordBox, "Required"); if (emailEntered == false || passwordEntered == false) { return; } signInUser(); } public void signInUser() { HashMap<String, String> parameters = new HashMap<>(); parameters.put("type", "signIn"); parameters.put("password", Utils.getText(passwordBox)); parameters.put("email", Utils.getText(emailBox)); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setIsDeviceTokenGenerate(true, "vDeviceToken"); exeWebServer.setDataResponseListener(new ExecuteWebServerUrl.SetDataResponse() { @Override public void setResponse(final String responseString) { Utils.printLog("ResponseData", "Data::" + responseString); if (responseString != null && !responseString.equals("")) { boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail) { generalFunc.storeUserData(generalFunc.getJsonValue(Utils.message_str, responseString)); (new StartActProcess(getActContext())).startAct(MainActivity.class); ActivityCompat.finishAffinity((Activity) getActContext()); } else { generalFunc.showGeneralMessage("", generalFunc.getJsonValue(Utils.message_str, responseString)); } } else { generalFunc.showError(); } } }); exeWebServer.execute(); } }
true
f930ce78f9cde906fe1e719261d4c99c11d24354
Java
DiegoDigo/control-erp
/src/main/java/br/com/control/controlEAD/model/News.java
UTF-8
576
1.75
2
[]
no_license
package br.com.control.controlEAD.model; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Getter @Setter @ToString @Document(collection = "news") public class News { @Id private String id; @Indexed private String title; private String body; @DBRef private List<Company> companies; }
true
3b159d8adecf63bee9a8da807390426f98c94d8b
Java
zhongxingyu/Seer
/Diff-Raw-Data/19/19_de0909fd00d93bfac899c772f2df1a89799423a2/CachoPropioMaker/19_de0909fd00d93bfac899c772f2df1a89799423a2_CachoPropioMaker_t.java
UTF-8
804
2.328125
2
[]
no_license
package plan; import models.User; import models.UserChunk; import models.UserChunks; import models.Video; public class CachoPropioMaker { private final User planRequester; private final Video video; public CachoPropioMaker(User planRequester, Video video) { super(); this.planRequester = planRequester; this.video = video; } public UserChunks makeCacho(int from, UserChunks planRequesterChunks) { play.Logger.info("CachoPropioMaker.makeCacho()"); UserChunks uc = new UserChunks(planRequester); for(int i = from; i<video.chunks.size();i++){ if(planRequesterChunks.hasChunk(i)){ uc.chunks.add(new UserChunk(i)); } else { return uc; } } /* * si el requester tiene todo el video... */ return uc; } }
true
c65b7e31e5e3faf6110daca704c920f55c770b2a
Java
EchoXuxiaoqian/learnjava1.8
/javatravel/src/main/java/cn/echo/learn/basic/ProcessControl.java
UTF-8
1,267
3.765625
4
[]
no_license
package cn.echo.learn.basic; public class ProcessControl { public static void main(String[] args) { ifState(); whileState(); forState(); switchState(); } public static void ifState() { int age = 20; if (age < 10) { System.out.println("Children"); } else if (age >= 10 && age < 20) { System.out.println("Teenage"); } else { System.out.println("Adult"); } } public static void whileState() { int balance = 10; int goal = 100; int year = 0; while (balance < goal) { balance = balance + 5; year++; } System.out.println(year); } public static void forState() { for (int i = 0; i < 10; i++) { System.out.print(i); } } public static void switchState() { int num = 1; switch (num) { case 1: System.out.print("Low"); break; case 2: System.out.print("Middle"); break; case 3: System.out.print("High"); break; } } }
true
87b1c672baa0ee525baf9ba6040f4f97afebb3dd
Java
Magos/octo-ninja
/src/octo_ninja/player/TournamentPlayer.java
UTF-8
4,141
3.203125
3
[]
no_license
package octo_ninja.player; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; import java.util.regex.Pattern; import octo_ninja.model.Board; import octo_ninja.model.GameState; import octo_ninja.model.Move; import octo_ninja.model.Piece; import octo_ninja.model.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /**An infrastructure for using a Player as a process which communicates its moves over STDIN/STDOUT. Intended for tournament use. */ public abstract class TournamentPlayer implements Player { private static final Pattern COORDINATES_PATTERN = Pattern.compile("[0123] [0123]"); private static Logger logger = LoggerFactory.getLogger(TournamentPlayer.class); protected int turn; public void runGame(){ Board board = new Board(); Set<Piece> remainingPieces = Piece.getPieceSet(); GameState state = new GameState(board, null,remainingPieces); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String first = null; try { first = readLine(reader); } catch (IOException e) { logger.debug("IOException", e); } if(first.equalsIgnoreCase(".")){ turn = 0; Move move = chooseMove(state); Piece piece = move.getChosenPiece(); remainingPieces.remove(piece); state = new GameState(board,piece,remainingPieces); output(piece.toString()); }else{ turn = 1; Piece opponentsChoice = Piece.PieceFromString(first); if(opponentsChoice == null){ throw new RuntimeException("Opponent chose invalid piece."); } remainingPieces.remove(opponentsChoice); state = new GameState(board, opponentsChoice,remainingPieces); } while(state.getTurn() < 16 && !state.getBoard().isWon() && !state.getPieces().isEmpty()){ Move move = null; logger.trace("Player {} starting turn {}.",turn,state.getTurn()); if(state.getTurn() % 2 == turn){ logger.trace("Player {} choosing move, state is {}.", turn, state); move = chooseMove(state); logger.trace("Player {} chose {}. Attempting to output.",turn, move); outputMove(move); }else{ logger.trace("Player {} trying to read opponent's move.",turn); move = getOpponentMove(reader); } logger.trace("Player {} updating state, state is {}", turn,state); state = state.applyMove(move); logger.trace("Player {} finished updating after move, state is {}.", turn, state); } if(turn == 0 && state.getPieces().isEmpty() && state.getBoard().getUnoccupiedCount() == 1){ //Make sure we output our last move even when we can't do anything else. logger.trace("Player {} outputting final move.", turn); int[] position = state.getBoard().getUnoccupiedPositions()[0]; output((position[0]-1) + " " + (position[1]-1)); output(null); } try { String last = readLine(reader); if(last != null && last.equals("Victory")){ gameEnded(true); }else{ gameEnded(false); } } catch (IOException e) { logger.warn("Could not read final game master message.",e); } } private void outputMove(Move move) { output((move.getX()-1) + " " + (move.getY()-1)); //Subtract 1 because tournament uses 0-indexed X/Y output(move.getChosenPiece().toString()); } private Move getOpponentMove(BufferedReader reader){ String pieceLine = null; String coordinatesLine = null; try{ coordinatesLine = readLine(reader); pieceLine = readLine(reader); }catch(IOException e){ logger.warn("IOException",e); } int x = -1; int y = -1; if(COORDINATES_PATTERN.matcher(coordinatesLine).matches()){ //The tournament uses 0-indexed coordinates, not 1-indexed ones. x = Integer.parseInt(coordinatesLine.substring(0,1)) + 1; y = Integer.parseInt(coordinatesLine.substring(2,3)) + 1; } Piece piece = Piece.PieceFromString(pieceLine); return new Move(piece,x,y); } private String readLine(BufferedReader reader) throws IOException { String ret = reader.readLine(); logger.trace("Player {} received: {}", turn,ret); return ret; } private void output(String s){ logger.trace("Player {} output: {}",turn,s); System.out.println(s); } }
true
dfa484aa226a523d9034b2f462eb62b907c2858d
Java
Nehaghate285/IoTEnabledPetCare
/Project_1/src/userinterface/ProcessingJPanel/PetTakerProcessJPanel.java
UTF-8
11,270
2.125
2
[]
no_license
/* * 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 userinterface.ProcessingJPanel; import Business.SendSMS; import Business.Validator.Validator; import Business.WorkQueue.PetTakerWorkRequest; import Business.WriteToFile; import java.awt.CardLayout; import java.awt.Component; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.JPanel; import userinterface.PetAdoptionRoles.PetTakerWorkAreaJPanel; /** * * @author Neha Ghate */ public class PetTakerProcessJPanel extends javax.swing.JPanel { /** * Creates new form PetGiverProcessJPanel */ JPanel userProcessContainer; PetTakerWorkRequest request; public PetTakerProcessJPanel( JPanel userProcessContainer,PetTakerWorkRequest request) { initComponents(); this.userProcessContainer = userProcessContainer; this.request = request; showDetails(); } private void showDetails(){ petBreedJText1.setText(request.getPetBreed()); numberofPetsJText.setText(Integer.toString(request.getNumberOfPets())); reasonJText.setText(request.getMessage()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { backJButton = new javax.swing.JButton(); submitJButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); resultJTextField = new javax.swing.JTextArea(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); petBreedJText1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); numberofPetsJText = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); reasonJText = new javax.swing.JTextArea(); setBackground(new java.awt.Color(204, 255, 204)); backJButton.setText("Back"); backJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backJButtonActionPerformed(evt); } }); submitJButton.setText("Submit Result"); submitJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { submitJButtonActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 102, 102)); jLabel1.setText("Result"); jLabel2.setText("Pet Taker Work Area"); resultJTextField.setColumns(20); resultJTextField.setRows(5); jScrollPane1.setViewportView(resultJTextField); jLabel5.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(0, 102, 102)); jLabel5.setText("Reason:"); jLabel6.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 102, 102)); jLabel6.setText("Pet Breed:"); petBreedJText1.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N petBreedJText1.setForeground(new java.awt.Color(0, 102, 102)); petBreedJText1.setText("Pet Breed"); jLabel3.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 102, 102)); jLabel3.setText("Number of pets:"); numberofPetsJText.setFont(new java.awt.Font("Segoe UI Semilight", 0, 14)); // NOI18N numberofPetsJText.setForeground(new java.awt.Color(0, 102, 102)); numberofPetsJText.setText("numofPets"); reasonJText.setEditable(false); reasonJText.setColumns(20); reasonJText.setRows(5); jScrollPane2.setViewportView(reasonJText); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(112, 112, 112) .addComponent(jLabel2) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(130, 130, 130) .addComponent(submitJButton)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel6)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(petBreedJText1) .addComponent(numberofPetsJText))) .addComponent(backJButton) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5) .addGap(31, 31, 31) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(42, 42, 42) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(76, 342, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(petBreedJText1)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(numberofPetsJText)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(57, 57, 57) .addComponent(jLabel5)) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(62, 62, 62))) .addComponent(submitJButton) .addGap(2, 2, 2) .addComponent(backJButton) .addGap(26, 26, 26)) ); }// </editor-fold>//GEN-END:initComponents private void backJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backJButtonActionPerformed userProcessContainer.remove(this); Component[] componentArray = userProcessContainer.getComponents(); Component component = componentArray[componentArray.length - 1]; PetTakerWorkAreaJPanel dwjp = (PetTakerWorkAreaJPanel) component; dwjp.populateTable(); CardLayout layout = (CardLayout) userProcessContainer.getLayout(); layout.previous(userProcessContainer); }//GEN-LAST:event_backJButtonActionPerformed private void submitJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitJButtonActionPerformed String name = resultJTextField.getText(); if(Validator.isStringValid(name)){ request.setTestResult(name); request.setStatus("Completed"); request.setResolveDate(new Date()); WriteToFile.getData(request.getReceiver()+" accepted the request on "+new Date()); JOptionPane.showMessageDialog(null, "Result is added","Result Addition",JOptionPane.INFORMATION_MESSAGE); SendSMS.sendNotificationMessage(request.getSender(), request); } else { JOptionPane.showMessageDialog(null, "Test result cannot be empty","Empty text field",JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_submitJButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backJButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JLabel numberofPetsJText; private javax.swing.JLabel petBreedJText1; private javax.swing.JTextArea reasonJText; private javax.swing.JTextArea resultJTextField; private javax.swing.JButton submitJButton; // End of variables declaration//GEN-END:variables }
true
cce1a8db6deea31cce1e7bb670466f394129c51f
Java
t0lia/pool
/dessign_pattern/src/main/java/com/t0lia/design_pattern/II_structural/adapter/client/solar/Sun.java
UTF-8
226
2.421875
2
[]
no_license
package com.t0lia.design_pattern.II_structural.adapter.client.solar; public class Sun { public static final Sun INSTANCE = new Sun(); private Sun() { } void shine(){ System.out.println("shine"); } }
true