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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b6decd71f7b49ad3fa3ff540e8ba332562a87ee2
|
Java
|
hatemnuman/javaclasses
|
/src/com/class6/ScannerSwitch.java
|
UTF-8
| 639
| 3.359375
| 3
|
[] |
no_license
|
package com.class6;
import java.util.Scanner;
public class ScannerSwitch {
public static void main(String[] args) {
// TODO Auto-generated method stub
String country, foodName;
Scanner scan = new Scanner(System.in);
System.out.println("PLease enter your Country");
country = scan.nextLine();
//boolean=scan.nextBoolean()
switch (country) {
case "Turky":
foodName = "Kebab";
break;
case "Ethioia":
foodName = "Tibas";
break;
case "Palistain":
foodName = "Mansaf";
break;
default:
foodName="UnKnown";
} System.out.println("YOu are from "+country+ " and your food is "+foodName);
}
}
| true
|
e0657416e9364a754ebf02f427ee0b799a547f53
|
Java
|
manishesprit/ChatApp
|
/app/src/main/java/com/rs/timepass/Ui/FeedDetailActivity.java
|
UTF-8
| 13,514
| 1.59375
| 2
|
[] |
no_license
|
package com.rs.timepass.Ui;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.rs.timepass.Adapter.CommentRecyclerAdapter;
import com.rs.timepass.Backend.AddCommentAPI;
import com.rs.timepass.Backend.FeedDetailAPI;
import com.rs.timepass.Backend.LikeUnlikeAPI;
import com.rs.timepass.Backend.ResponseListener;
import com.rs.timepass.Bean.CommentBean;
import com.rs.timepass.Bean.PostBean;
import com.rs.timepass.R;
import com.rs.timepass.Uc.AlertDailogView;
import com.rs.timepass.Uc.OnPopUpDialogButoonClickListener;
import com.rs.timepass.Utils.Config;
import com.rs.timepass.Utils.Pref;
import com.rs.timepass.Utils.Utils;
import java.util.ArrayList;
public class FeedDetailActivity extends AppCompatActivity implements View.OnClickListener, OnPopUpDialogButoonClickListener {
private Intent intent;
private Toolbar toolbar;
private Context context;
private FeedDetailAPI feedDetailAPI;
private LikeUnlikeAPI likeUnlikeAPI;
private RecyclerView recyclerView;
private CommentRecyclerAdapter commentRecyclerAdapter;
private ArrayList<CommentBean> commentBeanArrayList;
private LinearLayout myprogressBar;
private PostBean postBean;
private ImageView imgAvatar;
private TextView txtUserName;
private TextView txtFeedTime;
private TextView txtCaption;
private ImageView imgFeed;
private ImageView imgLikeUnlike;
private TextView txtNoComment;
private TextView txtNolike;
private LinearLayout llComment;
private LinearLayout llLike;
private EditText edtComment;
private ImageView imgAdd;
private AddCommentAPI addCommentAPI;
private TextView txtNooflikes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_detail);
context = this;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Feed");
myprogressBar = (LinearLayout) findViewById(R.id.myprogressBar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
txtNooflikes = (TextView) findViewById(R.id.txtNooflikes);
imgAvatar = (ImageView) findViewById(R.id.imgAvatar);
txtUserName = (TextView) findViewById(R.id.txtUserName);
txtFeedTime = (TextView) findViewById(R.id.txtFeedTime);
txtCaption = (TextView) findViewById(R.id.txtCaption);
imgFeed = (ImageView) findViewById(R.id.imgFeed);
imgLikeUnlike = (ImageView) findViewById(R.id.imgLikeUnlike);
txtNoComment = (TextView) findViewById(R.id.txtNoComment);
txtNolike = (TextView) findViewById(R.id.txtNolike);
llComment = (LinearLayout) findViewById(R.id.llComment);
llLike = (LinearLayout) findViewById(R.id.llLike);
edtComment = (EditText) findViewById(R.id.edtComment);
imgAdd = (ImageView) findViewById(R.id.imgAddComment);
Utils.setDefaultRoundImage(context, imgAvatar, R.drawable.default_user);
Call_Detail();
myprogressBar.setOnClickListener(this);
txtUserName.setOnClickListener(this);
imgAvatar.setOnClickListener(this);
imgLikeUnlike.setOnClickListener(this);
imgFeed.setOnClickListener(this);
llLike.setOnClickListener(this);
imgAdd.setOnClickListener(this);
edtComment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() > 0) {
imgAdd.setImageResource(R.drawable.send_light);
} else {
imgAdd.setImageResource(R.drawable.send_dark);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void Call_Detail() {
if (Utils.isOnline(context)) {
myprogressBar.setVisibility(View.VISIBLE);
feedDetailAPI = new FeedDetailAPI(context, responseListener, getIntent().getIntExtra("feedid", 0));
feedDetailAPI.execute();
} else {
AlertDailogView.showAlert(context, "Internet Error", "Internet not available", "Cancel", true, "Try again", this, 0).show();
}
}
private ResponseListener responseListener = new ResponseListener() {
public void onResponce(String tag, int result, Object obj, Object obj1) {
myprogressBar.setVisibility(View.GONE);
if (result == Config.API_SUCCESS) {
if (tag.equals(Config.TAG_LIKEUNLIKE)) {
postBean.islike = (int) obj == 0 ? false : true;
postBean.noOflike = (int) obj1;
txtNolike.setText("" + postBean.noOflike);
imgLikeUnlike.setImageResource(postBean.islike == true ? R.drawable.love_white_filled : R.drawable.love_gray);
}
} else {
}
}
public void onResponce(String tag, int result, Object obj) {
myprogressBar.setVisibility(View.GONE);
if (result == Config.API_SUCCESS) {
if (tag == Config.TAG_FEED_DETAIL) {
postBean = (PostBean) obj;
setdata();
}
if (tag == Config.TAG_ADD_COMMENT) {
edtComment.setText("");
imgAdd.setImageResource(R.drawable.send_dark);
postBean.commentBeanArrayList = (ArrayList<CommentBean>) obj;
txtNoComment.setText("" + postBean.commentBeanArrayList.size());
if (postBean.commentBeanArrayList.size() > 0) {
txtNooflikes.setVisibility(View.VISIBLE);
txtNooflikes.setText(postBean.commentBeanArrayList.size() + " People comment");
commentRecyclerAdapter = new CommentRecyclerAdapter(context, postBean.commentBeanArrayList);
recyclerView.setAdapter(commentRecyclerAdapter);
} else {
txtNooflikes.setVisibility(View.GONE);
}
}
} else {
}
}
};
private void setdata() {
if (!postBean.avatar.toString().trim().equalsIgnoreCase("")) {
Glide.with(context).load(Config.IMAGE_PATH_WEB_AVATARS + postBean.avatar)
.asBitmap()
.error(R.drawable.default_user).placeholder(R.drawable.default_user).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
imgAvatar.setImageDrawable(circularBitmapDrawable);
}
});
}
txtUserName.setText(postBean.name);
txtUserName.setTag(postBean);
txtFeedTime.setText(postBean.posttime);
txtNolike.setText("" + postBean.noOflike);
txtNoComment.setText("" + postBean.commentBeanArrayList.size());
if (postBean.caption.trim().toString().equalsIgnoreCase("")) {
txtCaption.setVisibility(View.GONE);
} else {
txtCaption.setVisibility(View.VISIBLE);
txtCaption.setText(postBean.caption);
}
if (!postBean.image_url.toString().equals("")) {
imgFeed.setVisibility(View.VISIBLE);
Glide.with(context).load(Config.IMAGE_PATH_WEB_FEED + postBean.image_url).asBitmap().error(R.drawable.default_user).placeholder(R.drawable.default_user).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
imgFeed.setImageBitmap(resource);
}
});
} else {
imgFeed.setVisibility(View.GONE);
}
imgLikeUnlike.setSoundEffectsEnabled(false);
imgLikeUnlike.setImageResource(postBean.islike == true ? R.drawable.love_white_filled : R.drawable.love_gray);
if (postBean.commentBeanArrayList.size() > 0) {
txtNooflikes.setVisibility(View.VISIBLE);
txtNooflikes.setText(postBean.commentBeanArrayList.size() + " People comment");
commentRecyclerAdapter = new CommentRecyclerAdapter(context, postBean.commentBeanArrayList);
recyclerView.setAdapter(commentRecyclerAdapter);
} else {
txtNooflikes.setVisibility(View.GONE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void OnButtonClick(int tag, int buttonIndex, String input) {
if (tag == 0) {
if (buttonIndex == 2) {
Call_Detail();
}
if (buttonIndex == 1) {
finish();
}
}
if (tag == 1) {
if (buttonIndex == 2) {
imgLikeUnlike.performClick();
}
}
}
@Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.myprogressBar:
break;
case R.id.imgFeed:
intent = new Intent(context, PhotoViewActivity.class);
intent.putExtra("beanData", (PostBean) txtUserName.getTag());
context.startActivity(intent);
break;
case R.id.txtUserName:
if (((PostBean) txtUserName.getTag()).userid != Pref.getValue(context, Config.PREF_USER_ID, 0)) {
intent = new Intent(context, ProfileActivity.class);
intent.putExtra("beanData", (PostBean) txtUserName.getTag());
context.startActivity(intent);
}
break;
case R.id.imgAvatar:
if (((PostBean) txtUserName.getTag()).userid != Pref.getValue(context, Config.PREF_USER_ID, 0)) {
intent = new Intent(context, ProfileActivity.class);
intent.putExtra("beanData", (PostBean) txtUserName.getTag());
context.startActivity(intent);
}
break;
case R.id.imgLikeUnlike:
if (Utils.isOnline(context)) {
myprogressBar.setVisibility(View.VISIBLE);
likeUnlikeAPI = new LikeUnlikeAPI(context, responseListener, ((PostBean) txtUserName.getTag()).feedid);
likeUnlikeAPI.execute();
} else {
AlertDailogView.showAlert(context, "Internet Error", "Internet not available", "Cancel", true, "Try again", this, 1).show();
}
break;
case R.id.llLike:
if (((PostBean) txtUserName.getTag()).noOflike > 0) {
intent = new Intent(context, LikeListActivity.class);
intent.putExtra("feedid", ((PostBean) txtUserName.getTag()).feedid);
context.startActivity(intent);
}
break;
case R.id.imgAddComment:
if (edtComment.getText().toString().trim().length() > 0) {
if (Utils.isOnline(context)) {
myprogressBar.setVisibility(View.VISIBLE);
addCommentAPI = new AddCommentAPI(context, responseListener, ((PostBean) txtUserName.getTag()).feedid, Uri.encode(edtComment.getText().toString().trim()));
addCommentAPI.execute();
}
}
break;
}
}
@Override
public void onBackPressed() {
if (myprogressBar.getVisibility() == View.GONE)
super.onBackPressed();
}
}
| true
|
e85c856a058c25f490de834f6a9bac48542a79ae
|
Java
|
avisi/jongo
|
/src/main/java/org/jongo/marshall/jackson/JongoAnnotationIdSelector.java
|
UTF-8
| 1,285
| 1.507813
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2011 Benoit GUEROUT <bguerout at gmail dot com> and Yves AMSELLEM <amsellem dot yves at gmail dot com>
*
* 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.jongo.marshall.jackson;
import com.fasterxml.jackson.databind.introspect.Annotated;
import org.jongo.marshall.jackson.oid.Id;
import org.jongo.marshall.jackson.oid.MongoId;
import org.jongo.marshall.jackson.oid.MongoObjectId;
public class JongoAnnotationIdSelector implements IdSelector<Annotated> {
public boolean isId(Annotated a) {
return a.hasAnnotation(MongoId.class) || a.hasAnnotation(Id.class);
}
public boolean isObjectId(Annotated a) {
return a.hasAnnotation(MongoObjectId.class) || a.hasAnnotation(org.jongo.marshall.jackson.oid.ObjectId.class);
}
}
| true
|
38a4cfb646cb09a67f17e75909ec3867dcdc0167
|
Java
|
cristovantamayo/ubsvoce
|
/src/main/java/com/cristovantamayo/ubsvoce/services/exceptions/GeocodingServiceException.java
|
UTF-8
| 372
| 2
| 2
|
[] |
no_license
|
package com.cristovantamayo.ubsvoce.services.exceptions;
public class GeocodingServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public GeocodingServiceException(String message) {
super(message);
}
public GeocodingServiceException(String message, Throwable cause) {
super(message, cause);
}
}
| true
|
3307223a77f33a28bfa1bb3a71fb6b38e765d8e5
|
Java
|
yu132/leetcode-solution
|
/src/main/java/old/_0200_0299/_277.java
|
UTF-8
| 840
| 3.015625
| 3
|
[] |
no_license
|
package old._0200_0299;
/**
* @ClassName: _277
*
* @Description: TODO(这里用一句话描述这个类的作用)
*
* @author 余定邦
*
* @date 2020年4月9日
*
*/
public class _277 {
class Relation {
public boolean knows(int a, int b) {
return false;
}
}
public class Solution extends Relation {
public int findCelebrity(int n) {
int i = 0;
for (int j = 0; j < n; ++j) {
if (knows(i, j)) {
i = j;
}
}
for (int k = 0; k < n; ++k) {
if (i == k) {
continue;
}
if (knows(i, k) || !knows(k, i)) {
return -1;
}
}
return i;
}
}
}
| true
|
e80428c7986f40dc7c203b83582dd8befa4c1814
|
Java
|
lishijie0520/generator
|
/src/main/java/com/genertech/lcm/biz/dao/DdmProcMapper.java
|
UTF-8
| 885
| 1.921875
| 2
|
[] |
no_license
|
package com.genertech.lcm.biz.dao;
import com.genertech.lcm.biz.dto.DdmProc;
import com.genertech.lcm.biz.dto.DdmProcExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface DdmProcMapper {
int countByExample(DdmProcExample example);
int deleteByExample(DdmProcExample example);
int deleteByPrimaryKey(String id);
int insert(DdmProc record);
int insertSelective(DdmProc record);
List<DdmProc> selectByExample(DdmProcExample example);
DdmProc selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") DdmProc record, @Param("example") DdmProcExample example);
int updateByExample(@Param("record") DdmProc record, @Param("example") DdmProcExample example);
int updateByPrimaryKeySelective(DdmProc record);
int updateByPrimaryKey(DdmProc record);
}
| true
|
51102285f859e58819f1f8282e3a88142b329bd4
|
Java
|
yx-slamdunk/DataX
|
/ddbreader/src/main/java/com/netease/mail/stat/datax/plugin/reader/ddbreader/DdbReader.java
|
UTF-8
| 3,790
| 1.882813
| 2
|
[] |
no_license
|
/**
* @(#)DdbReader.java, 2017年3月17日.
*
* Copyright 2017 Netease, Inc. All rights reserved.
* NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.netease.mail.stat.datax.plugin.reader.ddbreader;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.datax.common.spi.Reader;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.plugin.rdbms.reader.CommonRdbmsReader;
import com.alibaba.datax.plugin.rdbms.reader.Constant;
import com.alibaba.datax.plugin.rdbms.util.DataBaseType;
/**
* Datax用于读取DDB数据的Plugin。 插件参考mysqlreader开发,通过在 {@link DataBaseType}
* 中添加DDB驱动实现支持。
* <p>
* ddb的jdbc url格式参考:
* <ul>
* <h1>${ip}:${port}?key=conf/secret.key&logdir=logs/ddb/oms</h1>
* </ul>
*
* @author hzyangxiong2014@corp.netease.com
*/
public class DdbReader extends Reader {
private static final DataBaseType DATABASE_TYPE = DataBaseType.DDB;
private static final int FETCHSIZE_DEFA = 10;
public static class Job extends Reader.Job {
private static final Logger LOG = LoggerFactory.getLogger(Job.class);
private Configuration originalConfig = null;
private CommonRdbmsReader.Job commonRdbmsReaderJob;
@Override
public void init() {
this.originalConfig = super.getPluginJobConf();
Integer userConfigedFetchSize = this.originalConfig
.getInt(Constant.FETCH_SIZE);
if (userConfigedFetchSize == null) {
LOG.warn("ddbreader 配置默认fetchSize: " + FETCHSIZE_DEFA);
this.originalConfig.set(Constant.FETCH_SIZE, FETCHSIZE_DEFA);
}
this.commonRdbmsReaderJob = new CommonRdbmsReader.Job(DATABASE_TYPE);
this.commonRdbmsReaderJob.init(this.originalConfig);
}
@Override
public void preCheck() {
init();
this.commonRdbmsReaderJob.preCheck(this.originalConfig,
DATABASE_TYPE);
}
@Override
public List<Configuration> split(int adviceNumber) {
return this.commonRdbmsReaderJob.split(this.originalConfig,
adviceNumber);
}
@Override
public void post() {
this.commonRdbmsReaderJob.post(this.originalConfig);
}
@Override
public void destroy() {
this.commonRdbmsReaderJob.destroy(this.originalConfig);
}
}
public static class Task extends Reader.Task {
private Configuration readerSliceConfig;
private CommonRdbmsReader.Task commonRdbmsReaderTask;
@Override
public void init() {
this.readerSliceConfig = super.getPluginJobConf();
this.commonRdbmsReaderTask = new CommonRdbmsReader.Task(
DATABASE_TYPE, super.getTaskGroupId(), super.getTaskId());
this.commonRdbmsReaderTask.init(this.readerSliceConfig);
}
@Override
public void startRead(RecordSender recordSender) {
int fetchSize = this.readerSliceConfig.getInt(Constant.FETCH_SIZE);
this.commonRdbmsReaderTask.startRead(this.readerSliceConfig,
recordSender, super.getTaskPluginCollector(), fetchSize);
}
@Override
public void post() {
this.commonRdbmsReaderTask.post(this.readerSliceConfig);
}
@Override
public void destroy() {
this.commonRdbmsReaderTask.destroy(this.readerSliceConfig);
}
}
}
| true
|
0749ee6b4a61166ddcdaeb6ea5b35ae349295db3
|
Java
|
rossetti1983/lint
|
/src/dfs/FlattenListWORecursion22.java
|
UTF-8
| 1,727
| 3.5625
| 4
|
[] |
no_license
|
package dfs;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Created by zhizha on 8/19/17.
*/
public class FlattenListWORecursion22 {
// @param nestedList a list of NestedInteger
// @return a list of integer
public List<Integer> flatten(List<NestedInteger> nestedList) {
// Write your code here
List<Integer> list = new ArrayList<>();
if(nestedList == null){
return list;
}else{
Stack<NestedInteger> stack = new Stack<>();
for(int i = 0; i< nestedList.size(); i++){
stack.push(nestedList.get(i));
}
while(stack.size()>0){
NestedInteger ni = stack.peek();
if(ni.isInteger()){
list.add(ni.getInteger());
}else{
ni = stack.pop();
for(NestedInteger nii : ni.getList()){
stack.push(nii);
}
}
}
}
return list;
}
}
interface NestedInteger {
// @return true if this NestedInteger holds a single integer,
// rather than a nested list.
public boolean isInteger();
// @return the single integer that this NestedInteger holds,
// if it holds a single integer
// Return null if this NestedInteger holds a nested list
public Integer getInteger();
// @return the nested list that this NestedInteger holds,
// if it holds a nested list
// Return null if this NestedInteger holds a single integer
public List<NestedInteger> getList();
}
| true
|
25d91839877663b724a84733a34edd1789f1e4b7
|
Java
|
akraxx/Genetic-Algorithms-resolution
|
/src/main/java/solver/SolverState.java
|
UTF-8
| 228
| 1.617188
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package solver;
/**
*
* @author group12
*/
public enum SolverState {
START,
STOP,
PAUSE,
STEP,
RESET
}
| true
|
7e32907973cf92aca10759a286671ae8c9c55321
|
Java
|
Diffblue-benchmarks/user-management
|
/src/main/java/io/pockid/backend/usermanagement/persistence/model/PUserModel.java
|
UTF-8
| 993
| 2.171875
| 2
|
[] |
no_license
|
package io.pockid.backend.usermanagement.persistence.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.time.LocalDate;
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
@Table(name = "auth_user")
public class PUserModel extends BaseModel {
@Column(name = "uid", unique = true)
private String uid;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "nick_name")
private String nickName;
@Column(name = "date_of_birth", nullable = false)
private LocalDate dateOfBirth;
@Column(name = "gender", nullable = false)
private String gender;
@Column(name = "active", nullable = false)
private boolean active = true;
@Column(name = "is_parent", nullable = false)
private boolean isParent = false;
}
| true
|
315ff2b282f1161e8bd0d7d02992881cc4d1c6ee
|
Java
|
ayiii769/SunnyWeather
|
/app/src/main/java/com/example/sunnyweather/logic/model/DailyResponse.java
|
UTF-8
| 1,004
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.sunnyweather.logic.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.List;
public class DailyResponse {
public DailyResponse.Result result;
public String status;
public static class Result {
public DailyResponse.Daily daily;
}
public static class Temperature{
public Float max;
public Float min;
}
public static class Skycon{
public String value;
public Date date;
}
public static class LifeIndex{
public List<LifeDescription> coldRisk;
public LifeDescription carWashing;
public LifeDescription ultraviolet;
public LifeDescription dressing;
}
public static class LifeDescription{
public String desc;
}
public static class Daily{
public List<Skycon> skycon;
public List<Temperature> temperature;
@SerializedName("life_index")
public LifeIndex lifeIndex;
}
}
| true
|
4b72ca592fdcd0d8d1da5e23ee6c799b410f69e3
|
Java
|
bharat-kadchha/tutorials
|
/core-java/Core_Java/src/javafeatures/Assertionex.java
|
UTF-8
| 377
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
package javafeatures;
import java.util.Scanner;
public class Assertionex {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter your age : ");
Scanner s = new Scanner(System.in);
int a = s.nextInt();
assert a <= 18 : "Not Valid" ;
System.out.println("Age is : "+a);
s.close();
}
}
| true
|
284c1a043ffaf1af5024284f0d7556c7ceefa6da
|
Java
|
grzesiakmarcin/HomeExcercises
|
/src/refleksje/Shape.java
|
UTF-8
| 1,055
| 3.125
| 3
|
[] |
no_license
|
package refleksje;
class Shape {}
class Shape2D extends Shape {}
class Kolo extends Shape2D {}
class Kwadrat extends Shape2D {}
class Main {
public static void main(String[] args) {
Shape2D rzeczoneKolo = new Kolo();
boolean r1 = rzeczoneKolo instanceof Shape;
boolean r2 = rzeczoneKolo instanceof Shape2D;
boolean r3 = rzeczoneKolo instanceof Kolo;
System.out.println(" instance of " + r1 + " " + r2 + " " + r3);
boolean r4 = rzeczoneKolo.getClass().isInstance(Shape.class);
boolean r5 = rzeczoneKolo.getClass().isInstance(Shape2D.class);
boolean r6 = rzeczoneKolo.getClass().isInstance(Kolo.class);
System.out.println(" getClass().isInstance " + r4 + " " + r5 + " " + r6);
// boolean r7 = rzeczoneKolo.getClass() == Shape.class; //incomparable types:
boolean r8 = rzeczoneKolo.getClass() == Shape2D.class;
boolean r9 = rzeczoneKolo.getClass() == Kolo.class;
System.out.println(" getClass()== ***.class " + r8 + " " + r9);
}
}
| true
|
79b5a0f3909755910608566e8c4d17e3563edb39
|
Java
|
srook12/BootcampHardDrive
|
/WS/default/AdvancedJavaProject/src/mywork/io/myex/ConfigInitializer.java
|
UTF-8
| 1,222
| 2.625
| 3
|
[] |
no_license
|
package mywork.io.myex;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class ConfigInitializer {
private static Properties p;
// So we load the properties file only once
static {
FileInputStream fis = null;
p = new Properties();
p.setProperty("letter.a", "0");
p.setProperty("letter.b", "0");
p.setProperty("letter.c", "0");
p.setProperty("letter.d", "0");
p.setProperty("letter.e", "0");
p.setProperty("letter.f", "0");
p.setProperty("letter.g", "0");
p.setProperty("letter.h", "0");
p.setProperty("letter.i", "0");
p.setProperty("letter.j", "0");
p.setProperty("letter.w", "0");
p.setProperty("letter.x", "0");
try {
fis = new FileInputStream(System.getProperty("config.file.location"));
p.load(fis);
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void persist() throws IOException {
FileOutputStream fos = new FileOutputStream(System.getProperty("config.file.location"));
p.store(fos, "This is my comment for this store.");
}
public static Properties loadProperties() {
return p;
}
}
| true
|
3fc4e8934d91dfef2d58cc7c09da6bb37462e738
|
Java
|
nancyuzunova/finance_tracker
|
/src/main/java/ittalents/javaee/model/pojo/Account.java
|
UTF-8
| 1,718
| 2.453125
| 2
|
[] |
no_license
|
package ittalents.javaee.model.pojo;
import ittalents.javaee.model.dto.AccountDto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.time.LocalDateTime;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@Entity
@DynamicUpdate
@Table(name = "accounts")
public class Account extends AbstractPojo<AccountDto, AccountDto> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private long id;
@NotBlank
private String name;
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false)
private User user;
@NotNull
private LocalDateTime createdOn;
@Positive
private double balance;
@NotNull
@Enumerated(EnumType.STRING)
private Currency currency;
@OneToMany(orphanRemoval = true, cascade = CascadeType.REMOVE, mappedBy = "account")
private List<Transaction> transactions;
@Override
public void fromDto(AccountDto dto) {
this.balance = dto.getBalance();
this.name = dto.getName().trim();
if (dto.getCurrency() != null) {
this.currency = dto.getCurrency();
}
}
@Override
public AccountDto toDto() {
AccountDto accountDto = new AccountDto();
accountDto.setId(id);
accountDto.setName(name);
accountDto.setBalance(balance);
accountDto.setCurrency(currency);
return accountDto;
}
}
| true
|
179793c2b57ca599e44a8eeb9b8e2c194966cd51
|
Java
|
MaxHastings/VeriMobile
|
/app/src/main/java/info/vericoin/verimobile/BitcoinService.java
|
UTF-8
| 5,598
| 2.0625
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
package info.vericoin.verimobile;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.core.listeners.NewBestBlockListener;
import org.bitcoinj.kits.WalletAppKit;
import org.bitcoinj.params.RegTestParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener;
import java.util.concurrent.Executor;
public class BitcoinService extends Service {
public final static String BROADCAST_ESTABLISHED_CONNECTION = "BitcoinService.Connection.Established";
protected static int mStartMode = Service.START_STICKY;
protected static NetworkParameters params = TestNet3Params.get();
protected static String filePrefix = "forwarding-service-testnet";
protected WalletAppKit kit;
protected Executor executorService = MoreExecutors.newDirectExecutorService();
protected Intent establishedConnectionIntent = new Intent().setAction(BROADCAST_ESTABLISHED_CONNECTION);
public static Intent createIntent(Context context){
return new Intent(context, BitcoinService.class);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
BriefLogFormatter.init();
// Start up a basic app using a class that automates some boilerplate. Ensure we always have at least one key.
kit = new WalletAppKit(params, getFilesDir(), filePrefix) {
@Override
protected void onSetupCompleted() {
// Send broadcast to Service Receivers that the WalletAppKit set up is complete, and is ready to be used.
LocalBroadcastManager.getInstance(BitcoinService.this).sendBroadcast(establishedConnectionIntent);
// This is called in a background thread after startAndWait is called, as setting up various objects
// can do disk and network IO that may cause UI jank/stuttering in wallet apps if it were to be done
// on the main thread.
if (wallet().getKeyChainGroupSize() < 1)
wallet().importKey(new ECKey());
final Executor runInUIThread = new Executor() {
@Override public void execute(Runnable runnable) {
Handler handler = new Handler(Looper.getMainLooper());
// For Android: handler was created in an Activity.onCreate method.
handler.post(runnable);
}
};
wallet().addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() {
@Override
public void onCoinsReceived(final Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) {
// Runs in the dedicated "user thread".
//
// The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
// Wait until it's made it into the block chain (may run immediately if it's already there).
//
// For this dummy app of course, we could just forward the unconfirmed transaction. If it were
// to be double spent, no harm done. Wallet.allowSpendingUnconfirmedTransactions() would have to
// be called in onSetupCompleted() above. But we don't do that here to demonstrate the more common
// case of waiting for a block.
Futures.addCallback(tx.getConfidence().getDepthFuture(1), new FutureCallback<TransactionConfidence>() {
@Override
public void onSuccess(TransactionConfidence result) {
// "result" here is the same as "tx" above, but we use it anyway for clarity.
}
@Override
public void onFailure(Throwable t) {
}
}, executorService);
}
});
chain().addNewBestBlockListener(new NewBestBlockListener() {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
}
});
}
};
if (params == RegTestParams.get()) {
// Regression test mode is designed for testing and development only, so there's no public network for it.
// If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance.
kit.connectToLocalHost();
}
// Download the block chain.
kit.startAsync();
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| true
|
45e79fc7082c54d6d709e200b60744f1d89bb580
|
Java
|
atalatian/dataStructure_problemSet5_tamrin4
|
/src/Question1.java
|
UTF-8
| 1,255
| 3.609375
| 4
|
[] |
no_license
|
public class Question1 {
static boolean evaluation(String string){
char[] stack1 = new char[100];
char[] stack2 = new char[100];
int top1 = -1;
int top2 = -1;
for (int i=0; i<string.length(); i++){
top1 += 1;
top2 += 1;
stack1[top1] = string.charAt(i);
stack2[top2] = string.charAt(string.length()-1-i); //reverse of string
if (stack1[top1] == ')'){
for (int j=top1-1; j>=-1; j--){
if (j == -1){
return false;
}
if (stack1[j] == '('){
top1 = j-1;
break;
}
}
}
if (stack2[top2] == '('){
for (int j=top2-1; j>=-1; j--){
if (j == -1){
return false;
}
if (stack2[j] == ')'){
top2 = j-1;
break;
}
}
}
}
return true;
}
public static void main(String[] args) {
System.out.println(evaluation("(A+B^D)/(E-F)+G"));
}
}
| true
|
f40cbb8ba45037854102c8395d1d913c6be79c77
|
Java
|
thomqq/MetalMathsApp
|
/src/test/java/tq/arxsoft/metalmaths/services/LessonServiceDirectoryTest.java
|
UTF-8
| 4,210
| 2.609375
| 3
|
[] |
no_license
|
package tq.arxsoft.metalmaths.services;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tq.arxsoft.metalmaths.conf.MainConfiguration;
import tq.arxsoft.metalmaths.model.Lesson;
import tq.arxsoft.metalmaths.model.LessonInfo;
import tq.arxsoft.metalmaths.operation.Addition;
import tq.arxsoft.metalmaths.operation.Exercise;
import tq.arxsoft.metalmaths.operation.ExerciseType;
import tq.arxsoft.metalmaths.operation.FlashCard;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class LessonServiceDirectoryTest {
private LessonServiceDirectory lessonServiceDirectory;
@BeforeEach
void init() {
MainConfiguration mainConfiguration = new MainConfiguration();
lessonServiceDirectory= new LessonServiceDirectory("src\\test\\java\\tq\\arxsoft\\metalmaths\\services\\lessons", mainConfiguration.getParsers());
}
@Test
void ShouldGet4LessonInfosFromDirectory() {
//when
//given
List<LessonInfo> lessonInfos = lessonServiceDirectory.getLessonsInfo();
//then
assertEquals(4, lessonInfos.size());
}
@Test
void ShouldCreateMathExerciseForLessonId1() {
//when
//given
Lesson lesson = lessonServiceDirectory.getLesson(1);
List<Exercise> exerciseList = lesson.getExerciseList();
//then
assertEquals(1, lesson.getExerciseList().size());
assertEquals(exerciseList.get(0), new Addition(10, 10, ExerciseType.MathInput));
}
@Test
void shouldCreateExercise() {
//when
String[] items = new String[]{"id: 1|type: MathAnswer|operation: L1 + L2|L1: 100|L2: 100",
"id: 1|type: MathAnswer|operation: L1 + L2|L1: 22|L2: 13"};
Addition[] additions = new Addition[]{new Addition(100, 100, ExerciseType.MathAnswer),
new Addition(22, 13, ExerciseType.MathAnswer)};
for (int i = 0; i < items.length; i++) {
//given
HashMap<String, List<String>> lineItems = new HashMap<>();
prepare(items[i], lineItems);
Exercise exercise = lessonServiceDirectory.createExercise(lineItems).get(0);
//then
assertEquals(additions[i], exercise);
}
}
@Test
void shouldCreateSpellingExercise() {
//when
String[] items = new String[]{"id: 1|type: CardSpelling|word: {EN}RUN",
"id: 1|type: CardSpelling|word: {PL}AVAILABLE"};
FlashCard[] card = new FlashCard[]{new FlashCard("R,U,N,", "RUN", "EN"),
new FlashCard("A,V,A,I,L,A,B,L,E,", "AVAILABLE", "PL")};
for (int i = 0; i < items.length; i++) {
//given
HashMap<String, List<String>> lineItems = new HashMap<>();
prepare(items[i], lineItems);
Exercise exercise = lessonServiceDirectory.createExercise(lineItems).get(0);
//then
assertEquals(card[i], exercise);
}
}
@Test
void shouldCreateFlashExercise() {
//when
String[] items = new String[]{"id: 1|type: CardFlash|word: RUN",
"id: 1|type: CardFlash|word: AVAILABLE"};
FlashCard[] card = new FlashCard[]{new FlashCard("RUN", "RUN"),
new FlashCard("AVAILABLE", "AVAILABLE")};
for (int i = 0; i < items.length; i++) {
//given
HashMap<String, List<String>> lineItems = new HashMap<>();
prepare(items[i], lineItems);
Exercise exercise = lessonServiceDirectory.createExercise(lineItems).get(0);
//then
assertEquals(card[i], exercise);
}
}
private void prepare(String item, HashMap<String, List<String>> map) {
HashMap<String, List<String>> result = new HashMap<>();
String[] items1 = item.split("\\|");
for (String tmp : items1) {
String[] tmp2 = tmp.split(":");
List<String> keys = map.get(tmp2[0].trim().toLowerCase());
if( keys == null ) {
keys = new ArrayList<>();
map.put(tmp2[0].trim().toLowerCase(), keys);
}
keys.add(tmp2[1].trim());
}
}
}
| true
|
6a805eae2072a2d3c349f8c11a122e5836dc0b1a
|
Java
|
hackfengJam/LeetCode
|
/src/leetcode/algo/tree/leet_zh_572/Solution.java
|
UTF-8
| 1,233
| 3.484375
| 3
|
[] |
no_license
|
package leetcode.algo.tree.leet_zh_572;
import leetcode.algo.tree.base.TreeNode;
import leetcode.algo.tree.leet_zh_1167.Codec;
public class Solution {
/*
* 572. 另一个树的子树
*
* 执行用时 : 15 ms, 在Subtree of Another Tree的Java提交中击败了79.90% 的用户
* 内存消耗 : 40.5 MB, 在Subtree of Another Tree的Java提交中击败了93.99% 的用户
* */
private boolean isEqual(TreeNode s, TreeNode t) {
if (s == null || t == null)
return s == t;
if (s.val == t.val) {
return isEqual(s.left, t.left) && isEqual(s.right, t.right);
} else return false;
}
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null || t == null)
return s == t;
if (s.val == t.val && isEqual(s, t)) {
return true;
} else {
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
}
public static void main(String[] args) {
Solution ss = new Solution();
Codec codec = new Codec();
TreeNode s = codec.deserialize("[3,4,5,1,2]");
TreeNode t = codec.deserialize("[4,1,2]");
System.out.println(ss.isSubtree(s, t));
}
}
| true
|
361275917252b9a89b162b71c989b041f1f566f0
|
Java
|
MariyaBystrova/CheckPointTask_Bystrova
|
/CyclingGoods/src/by/epam/tr/cg/entity/ReportLine.java
|
UTF-8
| 2,064
| 2.609375
| 3
|
[] |
no_license
|
package by.epam.tr.cg.entity;
public class ReportLine {
private String category;
private int productsCount;
private int minPrice;
private int maxPrice;
public ReportLine() {
}
public ReportLine(String category, int productsCount, int minPrice, int maxPrice) {
this.category = category;
this.productsCount = productsCount;
this.minPrice = minPrice;
this.maxPrice = maxPrice;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(ReportLine.class.getSimpleName());
sb.append(": <category = ");
sb.append(category);
sb.append(">, <productsCount = ");
sb.append(productsCount);
sb.append(">, <minPrice = ");
sb.append(minPrice);
sb.append(">, <maxPrice = ");
sb.append(maxPrice);
sb.append(">.");
return sb.toString();
}
@Override
public int hashCode() {
return 7 * ((category == null) ? 0 : category.hashCode()) + 13 * productsCount + 17 * minPrice + 29 * maxPrice;
}
@Override
public boolean equals(Object obj) {
if (this == obj){
return true;
}
if (obj == null){
return false;
}
if (getClass() != obj.getClass()){
return false;
}
ReportLine other = (ReportLine) obj;
if (category == null) {
if (other.category != null){
return false;
}
} else if (!category.equals(other.category)){
return false;
}
if (maxPrice != other.maxPrice){
return false;
}
if (minPrice != other.minPrice){
return false;
}
if (productsCount != other.productsCount){
return false;
}
return true;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getProductsCount() {
return productsCount;
}
public void setProductsCount(int productsCount) {
this.productsCount = productsCount;
}
public int getMinPrice() {
return minPrice;
}
public void setMinPrice(int minPrice) {
this.minPrice = minPrice;
}
public int getMaxPrice() {
return maxPrice;
}
public void setMaxPrice(int maxPrice) {
this.maxPrice = maxPrice;
}
}
| true
|
71d465b372609df6d87bddafa3ba70a5dcbbfcee
|
Java
|
leejh903/algorithm-programmers
|
/programmers-intellij/src/test/java/kakaogroundx_1/SolutionTest.java
|
UTF-8
| 729
| 2.328125
| 2
|
[] |
no_license
|
package kakaogroundx_1;
import org.junit.Test;
import java.util.Queue;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.assertThat;
public class SolutionTest {
Solution problem = new Solution();
@Test
public void init() {
int[] openA = {3, 5, 7};
Queue<Integer> queue = problem.init(openA);
}
@Test
public void test() {
int[] openA = {3, 5, 7};
int[] closeB = {4, 10, 12};
assertThat(problem.solution(openA, closeB)).isEqualTo(6);
}
@Test
public void test2() {
int[] openA = {4, 7, 9, 16};
int[] closeB = {2, 5, 12, 14, 20};
assertThat(problem.solution(openA, closeB)).isEqualTo(10);
}
}
| true
|
d51df5c5e5fbb37cc7694c7b6d65043a5849aab0
|
Java
|
gbarte/Snake
|
/src/main/java/entities/snake/BodyPart.java
|
UTF-8
| 1,086
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
package entities.snake;
import models.Coordinate;
public class BodyPart {
private Coordinate coordinate;
public BodyPart(int coordinateX, int coordinateY) {
this.coordinate = new Coordinate(coordinateX, coordinateY);
}
/**
* Moves body part to new coordinate.
* @param x - New x coordinate of position of bodypart.
* @param y - New y coordinate of position of bodypart.
*/
public void updateBodyPartPos(int x, int y) {
this.coordinate.setCoordinateX(x);
this.coordinate.setCoordinateY(y);
}
/**
* Update body part's position to a new coordinate.
* @param coordinate Coordinate object with the new coordinates.
*/
public void updateBodyPartPos(Coordinate coordinate) {
int x = coordinate.getCoordinateX();
int y = coordinate.getCoordinateY();
this.coordinate = new Coordinate(x, y);
}
public Coordinate getCoordinate() {
return coordinate;
}
public void setCoordinate(Coordinate coordinate) {
this.coordinate = coordinate;
}
}
| true
|
60d1ba8c0a573400b6733f693663375c689e0e06
|
Java
|
yaraht17/Project
|
/app/src/main/java/com/fourlines/data/Var.java
|
UTF-8
| 3,565
| 1.734375
| 2
|
[] |
no_license
|
package com.fourlines.data;
import com.fourlines.doctor.R;
public class Var {
public static final int PAGE = 20;
public static final String MY_PREFERENCES = "PRE_LOGIN";
public static final String ACCESS_TOKEN = "access_token";
public static final String EMAIL = "email";
public static final String PASSWORD = "password";
public static final String FULLNAME = "fullname";
public static final String TOKEN = "token";
public static final String AVATAR = "avatar";
public static final String ID = "_id";
public static final String SICK_NAME = "name";
public static final String SICK_TYPE = "type";
public static final String SICK_REASON = "reason";
public static final String SICK_FOODS = "foods";
public static final String SICK_BAN_FOODS = "banfoods";
public static final String SICK_SYMPTOMS = "symptoms";
public static final String SICK_TREATMENT = "treatment";
public static final String SICK_DESCRIPTION = "description";
public static final String SICK_PREVENTION = "prevention";
public static final String NOTIF_TITLE = "title";
public static final String NOTIF_TOPIC = "topic";
public static final String NOTIF_CONTENT = "content";
public static final String SICKS = "sicks";
public static final String URL_HOST = "http://54.148.158.218:8888";
public static final String URL_LOGIN = URL_HOST + "/api/v1/login";
public static final String URL_REGISTER = URL_HOST + "/api/v1/register";
public static final String URL_GET_ALL_SICK = URL_HOST + "/api/v1/sicks";
public static final String URL_GET_SICK_BY_NAME = URL_HOST + "/api/v1/sicks/name?sickName=";
public static final String URL_GET_SICK_BY_TYPE = URL_HOST + "/api/v1/sicks/type?sickType=";
public static final String URL_GET_DATA_ACCOUNT = URL_HOST + "/api/v1/user";
public static final String URL_LOGOUT = URL_HOST + "/api/v1/logout";
public static final String URL_GET_TIPS = URL_HOST + "/api/v1/tips?page=";
public static final String URL_SEND_QUESTION = URL_HOST + "/api/v1/question?question=";
public static final String URL_SEND_SICK = URL_HOST + "/api/v1/sicks/push";
public static final String URL_VALIDATE_TOKEN = URL_HOST + "/api/v1/token/valid";
public static final String CHAT_STATUS = "status";
public static final String CHAT_TYPE = "type";
public static final String CHAT_DATA = "data";
public static final String CHAT_RESULT = "result";
public static final String SICK_KEY = "SICK_KEY";
public static final String SICK_TYPE_KEY = "SICK_TYPE_KEY";
public static final String[] SICKTYPE = {"Tuần hoàn", "Xương khớp", "Tiêu hóa", "Ngoài da", "Hô hấp", "Thần kinh"};
public static int drawList[] = {R.drawable.avatar, R.drawable.avatar1, R.drawable.avatar2,
R.drawable.avatar4, R.drawable.avatar5, R.drawable.avatar3};
public static final String[] TRUE = {"có", "vâng", "đúng", "chuẩn", "ừ", "hơi hơi", "thỉnh thoảng", "hay bị"};
public static final String[] FALSE = {"không", "chưa"};
public static final String[] QUESTION_RADOM = {"bạn có bị", "bạn bị", "bạn thấy", "bạn cảm thấy"};
public static final String[] ANSWER_RADOM = {"Bạn đang nói gì vậy? Tôi chẳng hiểu", "tôi chẳng hiểu bạn đang nói gì",
"Tôi không biết đâu", "Nói chuyện khác đi bạn"};
public static final String INTERNET_CHECK = "internet_check";
public static final String SICKNAMETOSERVER = "sickName";
}
| true
|
e18837547503c37c52140a357478068ffab4a0aa
|
Java
|
JuliandresCanon/MISION_TIC_2022
|
/2. Java/Recursos/Retos/Avance_Reto1.java
|
UTF-8
| 3,340
| 3.609375
| 4
|
[] |
no_license
|
import java.util.Arrays;
public class POS {
Object [][] articulos = new Object [][] {};
/*
(variable "articulos")
OBJETIVO: Almacenar los articulos que se desean facturar para un cliente individual.
FORMATO:
articulos = [
[nombre_articulo1, cantidad1],
[nombre_articulo2, cantidad2],
.
.
.
]
Ejemplo:
articulos = [
["Honey", 3],
["Negra", 2]
]
*/
int [] ventas = new int[] {};
/*
(variable "ventas")
OBJETIVO: Almacenar el total de cada venta individual
FORMATO:
ventas = [
total1,
total2,
.
.
.
]
Ejemplo:
ventas = [
49000, //Equivalente al total de las 3 Honey y las 2 Negra
.
.
.
]
*/
Object [][] productos = new Object [][] {
{"Honey", 10000},
{"Malta", 8000},
{"Negra", 9500}
};
public void Factura() {
String mensaje = "\t\tFACTURA\n";
mensaje += "Articulo\t\t\tCantidad\t\t\t\t\tValor unitario\t\t\tValor total\n";
int total = 0; //Valor total de la venta individual
//---Tu desarrollo (debes emplear la variable "articulos")--
/*
articulos = [
[nombre_articulo1, cantidad1], [Object, Object]
[nombre_articulo2, cantidad2],
.
.
.
]
*/
for (Object [] articulo: articulos) {
//Informacion usuario
String nombre = (String)(articulo[0]);
int cantidad = (int)(articulo[1]);
//Valor unitario
int valor_unitario = 0;
for (Object [] producto: productos) {
String nombre_cerveza = (String)(producto[0]);
if (nombre.equals(nombre_cerveza)) {
valor_unitario = (int)(producto[1]);
}
}
//Valor total
int valor_total = valor_unitario*cantidad;
total = total + valor_total;
//Mensaje
mensaje += nombre + "\t\t\t" + cantidad + "\t\t\t\t\t" + valor_unitario + "\t\t\t" + valor_total + "\n";
}
mensaje += "TOTAL = " + total;
System.out.println(mensaje);
this.nuevaVenta(total); //Registro de la venta
}
public void ResumenVentas() {
int total = 0;
//----Calcula el valor total (debes emplear la variable "ventas")----
for (int venta: ventas ) {
System.out.println("El valor de la venta fue: " + venta);
}
String mensaje = "El resumen de ventas del dia de hoy es: $" + total;
System.out.println(mensaje);
}
public void nuevoProducto(String art, int cant) {
articulos = Arrays.copyOf(articulos, articulos.length+1) ;
articulos[articulos.length-1] = new Object[] {art, cant};
}
public void nuevaVenta(int total) {
ventas = Arrays.copyOf(ventas, ventas.length+1);
ventas[ventas.length-1] = total;
}
}
| true
|
ab09d48c0e84b6f446f515dd7fa46d63425b0a52
|
Java
|
nimaaj93/MyEcommerce
|
/src/main/java/com/nimaaj/ecommerce/domain/ProductMediaRel.java
|
UTF-8
| 690
| 2
| 2
|
[] |
no_license
|
package com.nimaaj.ecommerce.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.*;
@Entity
@Table(name = "product_media_rel")
@NamedEntityGraph(name = "ProductMediaRel.full",
attributeNodes = {
@NamedAttributeNode("product"), @NamedAttributeNode("media")})
@Data
@EqualsAndHashCode(callSuper = true)
public class ProductMediaRel extends BaseEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer orderVal;
private boolean main;
@ManyToOne
private Product product;
@ManyToOne
private Media media;
}
| true
|
6fd03b27a8778c5f408b4c616c2532a554687b2b
|
Java
|
TawanRodrigues/poo-1
|
/src/main/java/br/edu/ifpi/capar/poo/oracle/academy/Teste.java
|
UTF-8
| 1,328
| 2.59375
| 3
|
[] |
no_license
|
package br.edu.ifpi.capar.poo.oracle.academy;
import jdk.nashorn.internal.codegen.CompilerConstants;
/**
*
* @author Denylson Melo
*/
public class Teste {
double variavel = 1.0;
public void imprimirVariavel(String nomeInstancia) {
byte irineu = 127;
byte irineu2 = 0;
byte irineu3 = -128;
int inteiroMaximo = 2147483647;
long inteiroAlemMaximo = 2147483648L;
int idadeEstudante;
int idade_estudante;
//estudante.nome
//estudante.nomePai
int nome;
//int 1nome;
int nome1;
int no1me;
/*int if;
int iF;
int for;
int continue;
int break;
int public;*/
int variavelInteira = 2;
int valorA, valorB, valorC;
valorA = valorB = valorC = 3;
System.out.println("valorA " + valorA);
System.out.println("valorB " + valorB);
System.out.println("valorC " + valorC);
valorC =4;
System.out.println("valorA " + valorA);
System.out.println("valorB " + valorB);
System.out.println("valorC " + valorC);
System.out.println(nomeInstancia + " imprimiu -> " + this.variavel);
}
}
| true
|
2aa00435176fdb5123c0e2890ea12f5b53b30c3d
|
Java
|
art84parthu/ukpostcode
|
/WCCPostalCode/src/com/wcc/interview/postal/code/distance/core/logic/error/handling/AuthenticationException.java
|
UTF-8
| 600
| 2.453125
| 2
|
[] |
no_license
|
package com.wcc.interview.postal.code.distance.core.logic.error.handling;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
* Custom Exception class
* Will be thrown if authentication fails.
*/
public class AuthenticationException extends WebApplicationException {
private static final long serialVersionUID = 1L;
/**
* Sets response code as HTTP status code 401
* @param message
*/
public AuthenticationException(String message) {
super(Response.status(Response.Status.UNAUTHORIZED).
entity(message).type("text/plain").build());
}
}
| true
|
859132eebff91ec070c14245ab98683d77744061
|
Java
|
ajaytunk/UrbanLadderCompProject
|
/src/test/java/com/UrbanLadderCompProject/runner/HomePageRunner.java
|
UTF-8
| 8,322
| 2.203125
| 2
|
[] |
no_license
|
package com.UrbanLadderCompProject.runner;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.UrbanLadderCompProject.pageObjects.HomePageObjects;
import com.UrbanLadderCompProject.reusableComponents.Base;
import com.UrbanLadderCompProject.reusableComponents.ReusableMethods;
import com.UrbanLadderCompProject.utilities.ExcelReader;
import com.UrbanLadderCompProject.utilities.PropertyFileReader;
//import jdk.internal.org.jline.utils.Log;
public class HomePageRunner extends Base {
@Test(priority=5)
public void CountOfItem() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hp= new HomePageObjects(driver);
hp.ClosingPopUp().click();
Thread.sleep(5000);
hp.Search().sendKeys("Dining Table");
hp.SearchButtonClick().click();
String totalcount=hp.GetProductsCount().getText();
System.out.println("Total items count : "+totalcount);
hp.GetCheckBox().click();
Thread.sleep(5000);
if(hp.GetCheckBox().isSelected())
{
System.out.println("Check box selected");
String InstockCount=hp.GetProductsCount().getText();
System.out.println("Items Instock Count : "+InstockCount);
logger.info("Count items Instock and out of stock");
}
}
@Test(priority=1)
public void ShoeRackProps() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.Sheos().click();
System.out.println("shoe Rack Name : "+hpo.ShoeRackName().getAttribute("title"));
System.out.println("sheo Rack Price : "+hpo.RackPrice().getText());
logger.info("Printing item name and price");
}
@Test(priority=2)
public void ClickingCheckBoxes() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.Search().sendKeys("Study table");
hpo.SearchButtonClick().click();
Actions action = new Actions(driver);
action.moveToElement(hpo.SizeDrop()).perform();
action.moveToElement(hpo.clicCab()).click().perform();
Thread.sleep(5000);
action.moveToElement(hpo.HoverPrice()).click().perform();
action.moveToElement(hpo.SelectPriceRange()).click().perform();
if(hpo.clicCab().isSelected())
{
System.out.println("Checkbox Got selected");
logger.info("To sort the items check box got selected");
}
}
@Test(dataProvider="getData",priority=0)
public void Subskribe(String mail) throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.EnterSubMail().sendKeys(mail);
//hpo.Subscribe().click();
logger.info("To subscribe to page");
}
@DataProvider
public Object[][] getData() throws IOException
{
prop=PropertyFileReader.LoadFile();
String p=prop.getProperty("path");
String file=prop.getProperty("fileName");
String sheet=prop.getProperty("sheetname1");
Object[][] data=ExcelReader.readExcel(p,file,sheet);
return data;
}
@Test(priority=4)
public void GiftCards() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.GiftCards().click();
hpo.voucher().click();
hpo.EnterAmount().sendKeys("1000");
hpo.ClickNext().click();
}
@Test(priority=3)
public void YouTubeViewsCount() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.ClickYt().click();
String mainWindowHandle = driver.getWindowHandle();
Set<String> allWindowHandles = driver.getWindowHandles();
Iterator<String> iterator = allWindowHandles.iterator();
for(String handle: allWindowHandles)
{
if(!handle.equals(mainWindowHandle))
{
driver.switchTo().window(handle);
hpo.ClkAbout().click();
System.out.println(driver.getTitle());
Thread.sleep(5000);
System.out.println("Youtube Total views count: "+hpo.Ytviews().getText());
logger.info("Youtube views printed sucessfully");
}
}
}
@Test(priority=7)
public void CheckOut() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.Search().sendKeys("Study chair");
hpo.SearchButtonClick().click();
hpo.SearchItem().click();
String mainWindowHandle = driver.getWindowHandle();
Set<String> allWindowHandles = driver.getWindowHandles();
Iterator<String> iterator = allWindowHandles.iterator();
for(String handle: allWindowHandles)
{
if(!handle.equals(mainWindowHandle))
{
driver.switchTo().window(handle);
hpo.Addtocart().click();
int n=3;
for(int i=1;i<n;i++) {
hpo.SelectQuantity().sendKeys(Keys.ARROW_DOWN);
}
hpo.SelectQuantity().sendKeys(Keys.ENTER);
System.out.println("Final Price For"+n+" +chairs+ :"+hpo.FinalPrice().getText());
hpo.CheckOutProduct().click();
logger.info("total price printed and checkout");
}
}
}
@Test(priority=6)
public void ChatBox() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
driver.switchTo().frame(hpo.Chat());
Thread.sleep(5000);
hpo.ChatFrame().click();
Thread.sleep(5000);
hpo.ChatBot().click();
hpo.ChattBox().sendKeys("Hello");
hpo.ChattBox().sendKeys(Keys.ENTER);
driver.switchTo().defaultContent();
}
@Test(dataProvider="GetData",priority=8)
public void OrderCheck(String ordi,String Phno) throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.TrackOrder().click();
hpo.Orderid().sendKeys(ordi);
hpo.PhoneNumber().sendKeys(Phno);
}
@DataProvider
public Object[][] GetData() throws IOException
{
prop=PropertyFileReader.LoadFile();
String p=prop.getProperty("path");
String file=prop.getProperty("fileName");
String sheet=prop.getProperty("sheetName");
Object[][] data=ExcelReader.readExcel(p,file,sheet);
return data;
}
@Test(priority=9)
public void Warranty() throws IOException, InterruptedException
{
driver=initializedriver();
ReusableMethods.Implicitwait(driver);
OpenUrl();
HomePageObjects hpo= new HomePageObjects(driver);
hpo.ClosingPopUp().click();
Thread.sleep(5000);
hpo.GetHelp().click();
hpo.GetHelpSearch().sendKeys("warranty");
hpo.GetHelpSearch().sendKeys(Keys.ARROW_DOWN.ENTER);
int s=hpo.GetHelpSearchQuestions().size();
System.out.println("Total questions related to warranty : "+s);
List<WebElement> allLinks=hpo.GetHelpSearchQuestions();
for(WebElement link:allLinks)
{
System.out.println(link.getText());
logger.info("To print questions");
}
}
@AfterMethod
public void DriverClose()
{
logger.info("driver closed");
driver.quit();
}
}
| true
|
c8f0150f5d854414f92aa5a26f2c0c5294f356fd
|
Java
|
hyodonglee/Algorithm_Solve_Alone
|
/Programmers/programmers_60057_문자열압축.java
|
UTF-8
| 1,251
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
//programmers_60057_문자열압축
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
String s = "a";
System.out.println(solution(s));
}
public static int solution(String s) {
int answer = s.length();
for(int i=1;i<=s.length()/2;i++){
int result = check(s, i);
if(result<answer)answer = result;
}
return answer;
}
private static int check(String s, int size){
String result="";
List<String> words = new ArrayList<>();
int exist = s.length()%size;
for(int i=0;i<=s.length()-size;i+=size){
words.add(s.substring(i, i+size));
}
int cnt = 1;
for(int i=0;i<words.size()-1;i++){
if(words.get(i).equals(words.get(i+1))){
cnt++;
}else{
if(cnt>1)result = result+String.valueOf(cnt)+words.get(i);
else result+=words.get(i);
cnt=1;
}
}
if(cnt>1) result = result + String.valueOf(cnt) + words.get(words.size()-1);
else result += words.get(words.size()-1);
return result.length()+exist;
}
}
| true
|
573f40e3a7e80d704257cec6e46f7ea60942830e
|
Java
|
kavyamayya/CodingPractice
|
/general/src/com/general/stack/StackUsingLinkedList.java
|
UTF-8
| 3,207
| 3.953125
| 4
|
[] |
no_license
|
package com.general.stack;
import com.general.linkedlist.SinglePointerNode;
import java.util.Scanner;
/**
* @author kavya k on 01-Feb-2020
*/
public class StackUsingLinkedList {
private SinglePointerNode top = null;
public static void main(String[] args) {
StackUsingLinkedList stack = new StackUsingLinkedList();
Scanner scanner = new Scanner(System.in);
System.out.println("Select one of the options from below:");
System.out.println("1 - push\n" + "2 - pop\n" + "3 - top element\n" + "4 - stack empty check\n" +
"5 - number of elements in the stack\n"
+ "6 - print the elements in the stack\n"+"Press any other key to exit ");
boolean run = true;
while (run) {
System.out.println("enter one of the options");
int argument = scanner.nextInt();
int value;
switch (argument) {
case 1:
System.out.println("enter the element to be pushed : ");
stack.push(scanner.nextInt());
break;
case 2:
value = stack.pop();
System.out.println((value == -1) ? "No element to pop" : String.format("pop element : %d", value));
break;
case 3:
value = stack.top();
System.out.println("Top element :" + (value==-1?"No element in the stack.":value));
break;
case 4:
System.out.println(stack.isEmpty()?"stack is empty.":"stack is not empty");
break;
case 5:
System.out.println("Size : " + stack.numberOfElements());
break;
case 6:
stack.display();
break;
default:
run = false;
break;
}
}
scanner.close();
}
public void push(int element) {
SinglePointerNode newNode = new SinglePointerNode(element);
if (top == null) {
top = newNode;
} else {
newNode.setNext(top);
top = newNode;
}
}
public int pop() {
if (top != null) {
int ele = top.getData();
top = top.getNext();
return ele;
} else {
return -1;
}
}
public int top(){
return top !=null?top.getData():-1;
}
public boolean isEmpty(){
return top == null;
}
public int numberOfElements(){
int count = 0;
if(top != null) {
SinglePointerNode traversalNode = top;
count++;
while (traversalNode.getNext() != null) {
traversalNode = traversalNode.getNext();
count++;
}
}
return count;
}
public void display(){
SinglePointerNode traversalNode = top;
while(traversalNode != null){
System.out.println("Node element : " + traversalNode.getData());
traversalNode = traversalNode.getNext();
}
}
}
| true
|
00a135ea1da8e9195b9f434898d6e38f185f7c47
|
Java
|
calibur-tv/Innocence
|
/app/src/main/java/com/riuir/calibur/ui/home/Drama/DramaSeasonVideoFragment.java
|
UTF-8
| 11,103
| 1.867188
| 2
|
[] |
no_license
|
package com.riuir.calibur.ui.home.Drama;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.riuir.calibur.R;
import com.riuir.calibur.ui.common.BaseFragment;
import com.riuir.calibur.ui.view.MyPagerSlidingTabStrip;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import calibur.core.http.models.anime.AnimeShowVideosInfo;
import calibur.core.http.observer.ObserverWrapper;
import calibur.foundation.rxjava.rxbus.Rx2Schedulers;
import retrofit2.Call;
/**
* A simple {@link Fragment} subclass.
*/
public class DramaSeasonVideoFragment extends BaseFragment {
@BindView(R.id.drama_video_pager_tab)
MyPagerSlidingTabStrip dramaVideoPagerTab;
@BindView(R.id.drama_video_view_pager)
ViewPager dramaVideoViewPager;
@BindView(R.id.drama_video_pager_refresh_layout)
SwipeRefreshLayout refreshLayout;
@BindView(R.id.drama_video_pager_empty_view_layout)
LinearLayout emptyLayout;
@BindView(R.id.drama_video_pager_empty_view_icon)
ImageView emptyIcon;
@BindView(R.id.drama_video_pager_empty_view_text)
TextView emptyText;
private int animeID;
List<AnimeShowVideosInfo.AnimeShowVideosInfoVideos> animeShowVideosInfoVideos;
//viewpager Tab标题
private List<String> titles = new ArrayList<>();
private DramaVideoEpisodesFragment episodesFragment1;
private DramaVideoEpisodesFragment episodesFragment2;
private DramaVideoEpisodesFragment episodesFragment3;
private DramaVideoEpisodesFragment episodesFragment4;
private DramaVideoEpisodesFragment episodesFragment5;
private DramaVideoEpisodesFragment episodesFragment6;
private DramaVideoEpisodesFragment episodesFragment7;
private DramaVideoEpisodesFragment episodesFragment8;
private DramaVideoEpisodesFragment episodesFragment9;
private DramaVideoEpisodesFragment episodesFragment10;
private DramaVideoPagerAdapter pagerAdapter;
/**
* 获取当前屏幕的密度
*/
private DisplayMetrics dm;
private Call<AnimeShowVideosInfo> videosInfoCall;
@Override
protected int getContentViewID() {
return R.layout.fragment_drama_video;
}
@Override
protected void onInit(@Nullable Bundle savedInstanceState) {
dm = getResources().getDisplayMetrics();
DramaActivity dramaActivity = (DramaActivity) getActivity();
animeID = dramaActivity.getAnimeID();
refreshLayout.setRefreshing(true);
if (animeShowVideosInfoVideos != null) {
animeShowVideosInfoVideos.clear();
}
setNet();
setListener();
}
private void setListener() {
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
setNet();
}
});
}
@Override
public void onDestroy() {
if (videosInfoCall != null) {
videosInfoCall.cancel();
}
super.onDestroy();
}
private void setNet() {
apiService.getCallAnimeShowVideos(animeID)
.compose(Rx2Schedulers.applyObservableAsync())
.subscribe(new ObserverWrapper<AnimeShowVideosInfo>() {
@Override
public void onSuccess(AnimeShowVideosInfo animeShowVideosInfo) {
animeShowVideosInfoVideos = animeShowVideosInfo.getVideos();
if (dramaVideoViewPager != null && refreshLayout != null) {
setViewPager();
refreshLayout.setRefreshing(false);
refreshLayout.setEnabled(false);
}
setEmptyView();
}
@Override
public void onFailure(int code, String errorMsg) {
super.onFailure(code, errorMsg);
if (refreshLayout != null) {
refreshLayout.setRefreshing(false);
setFailedView();
}
}
});
}
private void setEmptyView() {
if (animeShowVideosInfoVideos.size() == 0) {
emptyLayout.setVisibility(View.VISIBLE);
emptyIcon.setImageResource(R.mipmap.ic_no_content_empty_view);
emptyText.setText("这里空空如也");
}
}
private void setFailedView() {
emptyLayout.setVisibility(View.VISIBLE);
emptyIcon.setImageResource(R.mipmap.ic_failed_empty_view);
emptyText.setText("加载失败,下拉重试");
}
private void setHideEmptyView() {
if (animeShowVideosInfoVideos.size() != 0) {
emptyLayout.setVisibility(View.GONE);
}
}
private void setViewPager() {
titles.clear();
if (animeShowVideosInfoVideos.size() == 1) {
titles.add("番剧列表");
} else {
for (AnimeShowVideosInfo.AnimeShowVideosInfoVideos videos : animeShowVideosInfoVideos) {
titles.add(videos.getName());
}
}
pagerAdapter = new DramaVideoPagerAdapter(getChildFragmentManager());
dramaVideoViewPager.setAdapter(pagerAdapter);
dramaVideoPagerTab.setViewPager(dramaVideoViewPager);
dramaVideoViewPager.setOffscreenPageLimit(3);
setDramaTabs();
setHideEmptyView();
}
private void setDramaTabs() {
// 设置Tab是自动填充满屏幕的
dramaVideoPagerTab.setShouldExpand(false);
// 设置Tab的分割线是透明的
dramaVideoPagerTab.setDividerColor(Color.TRANSPARENT);
dramaVideoPagerTab.setBackgroundResource(R.color.color_FFFFFFFF);
//设置underLine
dramaVideoPagerTab.setUnderlineHeight(0);
dramaVideoPagerTab.setUnderlineColorResource(R.color.color_FFFFFFFF);
//设置Tab Indicator的高度
dramaVideoPagerTab.setIndicatorColorResource(R.color.theme_magic_sakura_primary);
// 设置Tab Indicator的高度
dramaVideoPagerTab.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, dm));
// 设置Tab标题文字的大小
dramaVideoPagerTab.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, dm));
//设置textclolo
dramaVideoPagerTab.setTextColorResource(R.color.color_FF5B5B5B);
// 设置选中Tab文字的颜色 (这是我自定义的一个方法)
dramaVideoPagerTab.setSelectedTextColorResource(R.color.theme_magic_sakura_primary);
//设置滚动条圆角(这是我自定义的一个方法,同时修改了滚动条长度,使其与文字等宽)
dramaVideoPagerTab.setRoundRadius(2.5f);
// 取消点击Tab时的背景色
dramaVideoPagerTab.setTabBackground(0);
}
public class DramaVideoPagerAdapter extends FragmentPagerAdapter {
public DramaVideoPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
@Override
public int getCount() {
return titles.size();
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if (episodesFragment1 == null) {
episodesFragment1 = new DramaVideoEpisodesFragment();
episodesFragment1.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment1;
case 1:
if (episodesFragment2 == null) {
episodesFragment2 = new DramaVideoEpisodesFragment();
episodesFragment2.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment2;
case 2:
if (episodesFragment3 == null) {
episodesFragment3 = new DramaVideoEpisodesFragment();
episodesFragment3.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment3;
case 3:
if (episodesFragment4 == null) {
episodesFragment4 = new DramaVideoEpisodesFragment();
episodesFragment4.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment4;
case 4:
if (episodesFragment5 == null) {
episodesFragment5 = new DramaVideoEpisodesFragment();
episodesFragment5.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment5;
case 5:
if (episodesFragment6 == null) {
episodesFragment6 = new DramaVideoEpisodesFragment();
episodesFragment6.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment6;
case 6:
if (episodesFragment7 == null) {
episodesFragment7 = new DramaVideoEpisodesFragment();
episodesFragment7.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment7;
case 7:
if (episodesFragment8 == null) {
episodesFragment8 = new DramaVideoEpisodesFragment();
episodesFragment8.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment8;
case 8:
if (episodesFragment9 == null) {
episodesFragment9 = new DramaVideoEpisodesFragment();
episodesFragment9.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment9;
case 9:
if (episodesFragment10 == null) {
episodesFragment10 = new DramaVideoEpisodesFragment();
episodesFragment10.setData(animeShowVideosInfoVideos, position);
}
return episodesFragment10;
default:
return null;
}
}
}
}
| true
|
fd6289f97d9f2afcdeeae1b27a4106d5fdfbb282
|
Java
|
dineshk2406/Repo-1
|
/Arithmetic.java
|
UTF-8
| 212
| 3.046875
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.Scanner;
public class Arithmetic
{
public static void main(String[] args)
{
int a=5;
int b=4;
int c;
c= a+b;
System.out.println("Sum of two numbers a+b: " +c);
}
}
| true
|
c013c177af88ae9f429e0e827c1973bdac2d04d4
|
Java
|
Mingda-Rui/LeetCodePractise
|
/src/main/java/pers/mingda/crackingcodinginterview/chapter2linkedlists/_2_5SumLists.java
|
UTF-8
| 5,995
| 4
| 4
|
[] |
no_license
|
package pers.mingda.crackingcodinginterview.chapter2linkedlists;
import java.util.Stack;
/**
* 2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single
* digit. THe digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a
* function that adds the two numbers and returns the sum as a linked list.
* EXAMPLE:
* Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295.
* Output: 2 -> 1 -> 9. That is, 912.
* FOLLOW UP
* Suppose the digits are stored in forward order. Repeat the above problem.
* Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295.
* Output: 9 -> 1 -> 2. That is, 912.
*/
public class _2_5SumLists {
public static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) {
return null;
}
public static LinkedListNode sumLists(LinkedListNode l1, LinkedListNode l2) {
int carry = 0;
LinkedListNode sum = new LinkedListNode(null, carry);
LinkedListNode sumHead = sum;
while (l1 != null || l2 != null) {
int l1Data = (l1 == null) ? 0 : l1.data;
int l2Data = (l2 == null) ? 0 : l2.data;
carry = (sum.data + l1Data + l2Data) / 10;
sum.data = (sum.data + l1Data + l2Data) % 10;
l1 = (l1 == null) ? l1 : l1.next;
l2 = (l2 == null) ? l2 : l2.next;
if (l1 != null || l2 != null || carry != 0) {
sum.next = new LinkedListNode(null, carry);
sum = sum.next;
}
}
return sumHead;
}
public static LinkedListNode sumListsRecursive(LinkedListNode l1, LinkedListNode l2) {
return sumListsRecursive(l1, l2, 0);
}
public static LinkedListNode sumListsRecursive(LinkedListNode l1, LinkedListNode l2, int carry) {
if (l1 == null && l2 == null && carry == 0)
return null;
int l1Data = (l1 == null) ? 0 : l1.data;
int l2Data = (l2 == null) ? 0 : l2.data;
int currentSum = l1Data + l2Data + carry;
LinkedListNode result = new LinkedListNode(null, currentSum % 10);
LinkedListNode l1Next = (l1 == null) ? null : l1.next;
LinkedListNode l2Next = (l2 == null) ? null : l2.next;
result.next = sumListsRecursive(l1Next, l2Next, currentSum / 10);
return result;
}
public static LinkedListNode sumListsFollowUpReverse(LinkedListNode l1, LinkedListNode l2) {
LinkedListNode reversedL1 = reverse(l1);
LinkedListNode reversedL2 = reverse(l2);
LinkedListNode result = sumLists(reversedL1, reversedL2);
return reverse(result);
}
private static LinkedListNode reverse(LinkedListNode list) {
return reverse(list, null);
}
private static LinkedListNode reverse(LinkedListNode list, LinkedListNode previous) {
if (list == null) {
return previous;
}
LinkedListNode next = list.next;
list.next = previous;
return reverse(next, list);
}
public static LinkedListNode sumListsFollowUp(LinkedListNode l1, LinkedListNode l2) {
Stack<Integer> l1Stack = convertToStack(l1);
Stack<Integer> l2Stack = convertToStack(l2);
int carry = 0;
LinkedListNode list = new LinkedListNode(null, carry);
while (!l1Stack.empty() || !l2Stack.empty()) {
int data1 = l1Stack.empty() ? 0 : l1Stack.pop();
int data2 = l2Stack.empty() ? 0 : l2Stack.pop();
int sum = data1 + data2 + carry;
list.data = sum % 10;
carry = sum / 10;
if (!l1Stack.empty() || !l2Stack.empty() || carry != 0) {
LinkedListNode head = new LinkedListNode(list, carry);
list = head;
}
}
return list;
}
private static Stack<Integer> convertToStack(LinkedListNode list) {
Stack<Integer> stack = new Stack<>();
pushStack(stack, list);
return stack;
}
private static void pushStack(Stack<Integer> stack, LinkedListNode list) {
while (list != null) {
stack.push(list.data);
list = list.next;
}
}
public static LinkedListNode sumListsFollowUpRecursion(LinkedListNode l1, LinkedListNode l2) {
int l1Size = getListSize(l1);
int l2Size = getListSize(l2);
LinkedListNode list = sumListsFollowUpRecursion(l1, l1Size, l2, l2Size);
if (list.data >= 10) {
LinkedListNode head = new LinkedListNode(list, list.data / 10);
list.data = list.data % 10;
list = head;
}
return list;
}
public static LinkedListNode sumListsFollowUpRecursion(LinkedListNode l1, int l1Size, LinkedListNode l2, int l2Size) {
// termination condition
if (l1.next == null && l2.next == null) {
return new LinkedListNode(null, l1.data + l2.data);
}
// recursion body
LinkedListNode l1Next = (l1Size >= l2Size) ? l1.next : l1;
int l1NextSize = (l1Size >= l2Size) ? l1Size - 1 : l1Size;
LinkedListNode l2Next = (l2Size >= l1Size) ? l2.next : l1;
int l2NextSize = (l2Size >= l1Size) ? l2Size - 1 : l2Size;
LinkedListNode previous = sumListsFollowUpRecursion(l1Next, l1NextSize, l2Next, l2NextSize);
int l1CurrentData = (l1Size >= l2Size) ? l1.data : 0;
int l2CurrentData = (l2Size >= l1Size) ? l2.data : 0;
LinkedListNode current = new LinkedListNode(previous, l1CurrentData + l2CurrentData + previous.data / 10);
previous.data = previous.data % 10;
// return
return current;
}
private static int getListSize(LinkedListNode list) {
int size = 0;
while (list != null) {
list = list.next;
size++;
}
return size;
}
}
| true
|
c0fd6f318da4ba9e9247111dc8f64f18192288d9
|
Java
|
SDemero/A3
|
/A3.java
|
UTF-8
| 2,870
| 3.453125
| 3
|
[] |
no_license
|
package a3;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author samueldemero
*/
public class A3 {
public static void main(String[] args) throws Exception {
ArrayList<Movie> L = new ArrayList<Movie>();
library(L);
Movie temp;
Node root;
int n = L.size();
// Sorting using bubble sort
for (int j = 0; j < n - 1; j++)
{
for (int i = j + 1; i < n; i++)
{
if (L.get(j).getTitle().compareTo(L.get(i).getTitle()) > 0)
{
temp = L.get(j);
L.set(j, L.get(i));
L.set(i, temp);
}
}
}
//end
MovieBST tree = new MovieBST();
root = tree.sortedArrayToBST(L, 0, n - 1);
tree.preOrder(root);
}
public static void library(ArrayList L)throws Exception{
Scanner sc = new Scanner(new File(""
+ "/Users/samueldemero/Desktop/NetBeansProjects/A3/movies.csv"));
int i = 0;
while (sc.hasNext()){
String line = sc.nextLine();
String[] tokens = line.split(",");
if (tokens.length>3){
String[] smoke = line.split("\"");
int end = smoke[1].length();
//System.out.println(smoke[1].substring(0, end-6));
String title = smoke[1].substring(0, end-6);
i++;
String[] p2 = line.split("\\(");
if (p2.length > 1){
StringBuffer year = new StringBuffer(p2[p2.length-1]);
year.replace( 4 ,year.length()+1 ,"");
//System.out.println(year.toString());
Movie mov1 = new Movie (title,Integer.parseInt(year.toString()));
L.add(mov1);
}
}
else{
String pop = tokens[1];
String[] p2 = pop.split("\\(");
String title = tokens[1].substring(0, tokens[1].length()-6);
if (p2.length > 1){
StringBuffer year = new StringBuffer(p2[p2.length-1]);
year.replace( 4 ,year.length()+1 ,"");
//System.out.println(title);
i++;
// System.out.println(year);
int Year = Integer.parseInt(year.toString());
Movie mov1 = new Movie (title,Year);
L.add(mov1);
}
}
} System.out.println("There are "+i+" movies in the library");
}
}
| true
|
891c29b8a1e980f1ccf59b37abad85194a5fda80
|
Java
|
tinalenguyen/IntegerSequence
|
/Range.java
|
UTF-8
| 891
| 3.578125
| 4
|
[] |
no_license
|
import java.util.NoSuchElementException;
public class Range implements IntegerSequence{
private int start,end,current;
public Range(int start, int end){
current = start;
this.start = start;
this.end = end;
if (start>end) {
throw new IllegalArgumentException("Start can't be larger than the end");
}
}
public void reset(){
//start over from the start of the sequence
current = start;
}
public int length() {
//returns total length of sequence
return end-start+1;
}
public boolean hasNext(){
//does this sequence have more elements?
return current <= end;
}
public int next(){
//has a throw NoSuchElementException
//returns current value of sequence and advances
if (current > end){
throw new NoSuchElementException("There are no more values");
}
else {
current++;
return current-1;
}
}
}
| true
|
f47df037b5ba51a2e0c456e8d9b8fb99b066e56d
|
Java
|
dark-matter-org/dark-matter-snmp
|
/src/org/dmd/snmp/parser/MibLocation.java
|
UTF-8
| 6,195
| 2.40625
| 2
|
[] |
no_license
|
// ---------------------------------------------------------------------------
// dark-matter-data
// Copyright (c) 2012 dark-matter-data committers
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
// more details.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package org.dmd.snmp.parser;
import java.io.File;
import org.dmd.util.exceptions.DebugInfo;
/**
* The MibLocation simply indicates the name of a MIB file and its location on the file system
* or in a JAR.
*/
public class MibLocation {
// The name of the MIB
String mibName;
// The full name of the directory where the MIB file exists for example:
// mibs/ietf
String directory;
// The full name of the directory where the MIB folder resides
String mibParentDirectory;
// The full name of the MIB file, for example:
// /mibs/ietf/VDSL-LINE-EXT-MCM-MIB
String fileName;
// FOR JAR LOCATIONS
// If the MIB was found in a JAR, this is the name of the JAR, for example:
// /Users/joe/softdev/dark-matter-snmp/extjars/mibble-mibs-2.9.3.jar
String jarFileName;
// The directory in the JAR file where the .xxx file exists, for example:
// /com/example/schema. NOTE: the file separators are ALWAYS forward slash "/"
String jarDirectory;
// Just the jar file name. If jarFileName is: file:F:\AASoftDev\workspace\dark-matter-data\extjars\exampleDMSchema.jar
// This will be just: exampleDMSchema.jar
String justJarName;
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("MibLocation\n");
sb.append(" MIB name: " + mibName + "\n");
sb.append(" directory: " + directory + "\n");
sb.append("configParentDirectory: " + mibParentDirectory + "\n");
sb.append(" fileName: " + fileName + "\n");
sb.append(" jarFileName: " + jarFileName + "\n");
sb.append(" jarDirectory: " + jarDirectory + "\n");
sb.append(" justJarName: " + justJarName + "\n\n");
return(sb.toString());
}
public MibLocation(String fn){
fileName = fn.replace('\\', '/');
int lastSlash = fileName.lastIndexOf("/");
if (lastSlash == -1){
mibName = fileName;
directory = null;
}
else{
mibName = fileName.substring(lastSlash+1);
directory = fileName.substring(0, lastSlash);
}
DebugInfo.debug("mibName: " + mibName + " directory: " + directory + " fileName: " + fileName);
// Not used in this case
jarFileName = null;
jarDirectory = null;
justJarName = null;
}
/**
* Constructs a new DmsSchemaLocation.
* @param n The name of the MIB file
* @param dir The directory where this file was found.
*/
public MibLocation(String n, String dir){
int lastSlash = -1;
mibName = n;
directory = dir;
fileName = directory + File.separatorChar + n;
lastSlash = directory.lastIndexOf(File.separatorChar);
mibParentDirectory = directory.substring(0,lastSlash);
// Not used in this case
jarFileName = null;
jarDirectory = null;
justJarName = null;
}
/**
* @return true if the config was found in a jar and false otherwise.
*/
public boolean isFromJAR(){
if (jarFileName == null)
return(false);
return(true);
}
/**
* Constructs a new schema location that's located in a JAR file.
* @param j The JAR file name.
* @param n The name of the possible MIB file.
* @param dir The sub directory in the JAR where the schema is found.
*/
public MibLocation(String j, String n, String dir){
int lastSlash = -1;
mibName = n;
directory = dir;
lastSlash = directory.lastIndexOf("/");
mibParentDirectory = directory.substring(0,lastSlash);
jarFileName = j;
jarDirectory = dir;
String tmp = "/" + jarDirectory + "/" + mibName;
fileName = tmp.replace('\\', '/');
lastSlash = jarFileName.lastIndexOf("/");
justJarName = jarFileName.substring(lastSlash+1);
}
/**
* @return The name of the schema (i.e. the name of the .dms file without the .dms extension).
*/
public String getMibName(){
return(mibName);
}
/**
* @return The name of the directory where the config file resides.
*/
public String getDirectory(){
return(directory);
}
/**
* The complete file name of this config file OR When the file is found in a JAR file,
* it's the URL of the file, for example <BR>
* "jar:file:" + jarFileName + "!/" + jarDirectory + "/" + configName + ".xxx" <BR>
* URL url = new URL(fileName);
* @return The file name.
*/
public String getFileName(){
return(fileName);
}
/**
* @return The parent directory where the config subfolder lives.
*/
public String getConfigParentDirectory(){
return(mibParentDirectory);
}
/**
* If the schema was in a JAR, this is the fully qualified name of the JAR.
* @return The JAR file name.
*/
public String getJarFilename(){
return(jarFileName);
}
/**
* If the schema was in a JAR, this is the name of the directory within the
* JAR where it was found.
* @return The directory path segment - the file separators in this are forward slashes.
*/
public String getJarDirectory(){
return(jarDirectory);
}
/**
* If the schema was in a JAR, this is just the name of the JAR.
* @return The JAR file name.
*/
public String getJustJarFilename(){
return(justJarName);
}
}
| true
|
84f4451bd63745fc04a5b9193e329de340526da3
|
Java
|
JetBrains/intellij-community
|
/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after3.java
|
UTF-8
| 238
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
// "Create class 'MyInteger'" "true-preview"
public class Test {
public static void main() {
int xxx = 3;
Integer i = new MyInteger(xxx);
}
}
public class MyInteger {
public MyInteger(int xxx) {<caret>
}
}
| true
|
51e965d3b768200bd8a2c8a3d5a0be20d4e5eabb
|
Java
|
xiaohesdu/learn
|
/src/main/java/com/learn/collection/ConcurrentHashMapExample1.java
|
UTF-8
| 1,067
| 3.109375
| 3
|
[] |
no_license
|
package com.learn.collection;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
/**
* @author gonghe.hogan
*/
@Slf4j
public class ConcurrentHashMapExample1 {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap<String, Integer > map = new ConcurrentHashMap<>();
int sameTime = 200;
int totalCount = 200;
final ExecutorService executorService = Executors.newCachedThreadPool();
Semaphore semaphore = new Semaphore(sameTime);
CountDownLatch countDownLatch = new CountDownLatch(totalCount);
for (int i = 0; i < totalCount;i++){
semaphore.acquire();
final int count = i;
executorService.submit(() -> {
map.put(count+"", count);
countDownLatch.countDown();
});
semaphore.release();
}
countDownLatch.await();
System.out.println("执行完毕");
executorService.shutdown();
}
}
| true
|
572e0aa3f5a5b4ceb0083b507a5c56a9b1d532f2
|
Java
|
zhouxinghang/codestudy
|
/src/leetcode/array/_56_MergeIntervals.java
|
UTF-8
| 1,985
| 4
| 4
|
[] |
no_license
|
package leetcode.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* @author zhouxinghang
* @date 2019-08-26
* 合并区间
* 给出一个区间的集合,请合并所有重叠的区间。
* Input: [[1,3],[2,6],[8,10],[15,18]]
* Output: [[1,6],[8,10],[15,18]]
* Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
*/
public class _56_MergeIntervals {
/**
* 先排序,然后一个个判断
* 时间复杂度:一个sort + 线性扫描 O(nlogn)
* 空间复杂度:O(1) (or O(n)O(n))。如果我们可以原地排序 intervals ,就不需要额外的存储空间;否则,我们就需要一个线性大小的空间去存储 intervals 的备份,来完成排序过程
*
* Runtime: 41 ms, faster than 7.75% of Java online submissions for Merge Intervals.
* Memory Usage: 45.5 MB, less than 23.19% of Java online submissions for Merge Intervals.
* @param intervals
* @return
*/
public int[][] merge(int[][] intervals) {
List<int[]> res = new ArrayList<>();
if (intervals.length == 0 || intervals == null) {
return res.toArray(new int[0][]);
}
Arrays.sort(intervals, Comparator.comparingInt(left -> left[0]));
int left = intervals[0][0];
int right = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
if (right >= intervals[i][0]) {
right = Math.max(right, intervals[i][1]);
} else {
res.add(new int[]{left, right});
left = intervals[i][0];
right = intervals[i][1];
}
}
res.add(new int[]{left, right});
return res.toArray(new int[0][]);
}
public static void main(String[] args) {
int[][] intervals = new int[][]{new int[]{8,10}, new int[]{1,3}};
new _56_MergeIntervals().merge(intervals);
}
}
| true
|
e26f88d1f000b38b557b31064da81e9a16be474a
|
Java
|
gesellix/dotplot
|
/org.dotplot.plugin/src/org/dotplot/core/plugins/PluginException.java
|
UTF-8
| 857
| 2.09375
| 2
|
[] |
no_license
|
/**
*
*/
package org.dotplot.core.plugins;
import org.dotplot.core.services.ServiceException;
/**
* @author Christian Gerhardt <case42@gmx.net>
*
*/
public class PluginException extends ServiceException {
/**
* UID for serialisation.
*/
private static final long serialVersionUID = -112476321729843371L;
/**
* Creates a new <code>PluginException</code>.
*/
public PluginException() {
super();
}
/**
* Creates a new <code>PluginException</code>.
*
* @param arg0
*/
public PluginException(String arg0) {
super(arg0);
}
/**
* Creates a new <code>PluginException</code>.
*
* @param arg0
* @param arg1
*/
public PluginException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
/**
* Creates a new <code>PluginException</code>.
*
* @param arg0
*/
public PluginException(Throwable arg0) {
super(arg0);
}
}
| true
|
69ac3c20257da01b454b61cd50035d55bc5b3735
|
Java
|
liukaixiong/cat-demo
|
/src/main/java/com/elab/cat/catdemo/aop/CatAnnotation.java
|
UTF-8
| 262
| 1.890625
| 2
|
[] |
no_license
|
package com.elab.cat.catdemo.aop;
import java.lang.annotation.*;
/**
* @author Liukx
* @create 2018-02-07 13:51
* @email liukx@elab-plus.com
**/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CatAnnotation {
String value();
}
| true
|
e67b555730ac30724e26eca836cc9b700979ba31
|
Java
|
YaYeKlinch/springProject
|
/src/main/java/com/examle/springProject/exceptions/TypeCardException.java
|
UTF-8
| 598
| 2.5
| 2
|
[] |
no_license
|
package com.examle.springProject.exceptions;
public class TypeCardException extends RuntimeException {
public TypeCardException() {
}
public TypeCardException(String message) {
super(message);
}
public TypeCardException(String message, Throwable cause) {
super(message, cause);
}
public TypeCardException(Throwable cause) {
super(cause);
}
public TypeCardException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true
|
ea6841b130f2b77411572a9c94f0a9703a86c78a
|
Java
|
erokhinav/software-design
|
/search-aggregator/src/main/java/com/erokhinav/actors/ChildActor.java
|
UTF-8
| 1,149
| 2.609375
| 3
|
[] |
no_license
|
package com.erokhinav.actors;
import java.util.Map;
import akka.actor.AbstractActor;
import com.erokhinav.search.SearchClient;
import com.erokhinav.search.SearchEngineResult;
import com.google.gson.Gson;
public class ChildActor extends AbstractActor {
private final Map<String, Long> sleepDuration = Map.of(
"Google", 500L,
"Yandex", 600L,
"Bing", 700L);
SearchClient client;
ChildActor(SearchClient client) {
super();
this.client = client;
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(String.class, this::getSearchResult).build();
}
private void getSearchResult(String query) {
String resultJson = client.makeSearchRequest(query);
Gson g = new Gson();
SearchEngineResult engineResult = g.fromJson(resultJson, SearchEngineResult.class);
try {
Thread.sleep(sleepDuration.get(engineResult.getEngineName()));
getSender().tell(engineResult, getSender());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true
|
d260fddfed78f8fdfd2d8cda958a6b5a17568fff
|
Java
|
peterfazekas/nezoter-nsjg
|
/src/hu/auditorium/App.java
|
UTF-8
| 1,247
| 2.75
| 3
|
[] |
no_license
|
package hu.auditorium;
import java.util.Scanner;
import hu.auditorium.controller.Auditorium;
import hu.auditorium.domain.service.Console;
import hu.auditorium.domain.service.DataReader;
import hu.auditorium.domain.service.DataWriter;
public class App {
private final Auditorium auditorium;
private final Console console;
private final DataWriter writer;
public App() {
console = new Console(new Scanner(System.in));
DataReader data = new DataReader();
auditorium = new Auditorium(data.getData("foglaltsag.txt", "kategoria.txt"));
writer = new DataWriter("szabad.txt");
}
public static void main(String[] args) {
new App().run();
}
private void run() {
System.out.println("2. feladat:");
int row = console.readInt("- adja meg a sor számát: ");
int column = console.readInt("- adja meg a szék számát: ");
System.out.println(auditorium.getSeatStaus(row, column));
System.out.println("3. feladat: " + auditorium.getSoldSeatRange());
System.out.println("4. feladat: " + auditorium.getMostPopularCategory());
System.out.println("5. feladat: " + auditorium.getCurrentIncome());
System.out.println("6. feladat: " + auditorium.getUniqueSeatCount());
writer.printAll(auditorium.getAuditoriumState());
}
}
| true
|
3dc3526238ebc31a2f26e95fcbf1e359cbdfdef8
|
Java
|
kohei-okazaki/nok
|
/nok-app/src/test/java/jp/co/nok/tool/gen/BaseGenerator.java
|
UTF-8
| 4,981
| 2.578125
| 3
|
[] |
no_license
|
package jp.co.nok.tool.gen;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Stream;
import jp.co.nok.common.io.property.reader.PropertyReader;
import jp.co.nok.common.log.Logger;
import jp.co.nok.common.log.LoggerFactory;
import jp.co.nok.common.type.BaseEnum;
import jp.co.nok.common.util.FileUtil.FileSeparator;
import jp.co.nok.tool.excel.Excel;
import jp.co.nok.tool.excel.ExcelReader;
import jp.co.nok.tool.util.ToolUtil;
/**
* 自動生成基底クラス<br>
* 自動生成ツールを作成する場合、本クラスを継承し{@linkplain #generateImpl()}に実際の自動生成処理を記述する
*
* @version 1.0.0
*/
public abstract class BaseGenerator {
/** LOG */
protected final Logger LOG = LoggerFactory.getLogger(this.getClass());
/** 自動生成ツール設定ファイル情報 */
protected ToolProperty prop;
/** 自動生成ツールのExcel情報 */
protected Excel excel;
/**
* 自動生成を行う
*
* @throws Exception
* 自動生成処理に失敗した場合
*/
final void generate() throws Exception {
LOG.debug("自動生成開始");
try {
// 自動生成ツール設定ファイルを取得
this.prop = readProp();
// Excelファイルを取得
this.excel = new ExcelReader().read(prop);
// 自動生成個別処理
List<GenerateFile> genFileList = generateImpl();
// 自動生成ファイルを作成
ToolUtil.createGenFileList(genFileList);
} finally {
LOG.debug("自動生成終了");
}
}
/**
* 個別自動生成処理を行う<br>
* 本クラスを継承して実処理を実装すること
*
* @return 自動生成ファイルリスト
* @throws Exception
* 自動生成個別処理が失敗した場合
*/
abstract List<GenerateFile> generateImpl() throws Exception;
/**
* 設定ファイルを読込を行う
*
* @return 設定ファイル
* @throws URISyntaxException
* パスの指定が不正な場合
*/
private ToolProperty readProp() throws URISyntaxException {
Path path = Paths.get(this.getClass().getClassLoader().getResource("").toURI());
String binDir = path.getParent().toString();
// 設定ファイルを取得
StringJoiner sj = new StringJoiner(FileSeparator.SYSTEM.getValue());
sj.add(binDir);
sj.add("test");
sj.add("tool.properties");
ToolProperty prop = new PropertyReader().read(sj.toString(), ToolProperty.class);
Stream.of(prop.getTargetTables().split(",")).forEach(e -> prop.addTargetTable(e));
return prop;
}
/**
* 自動生成区分の列挙
*
* @version 1.0.0
*/
public static enum GenerateType implements BaseEnum {
/** Entity作成 */
ENTITY("ENTITY", "nok-app\\src\\main\\java\\jp\\co\\nok\\db\\entity",
EntityGenerator.class),
/** DAO作成 */
DAO("DAO", "nok-app\\src\\main\\java\\jp\\co\\nok\\db\\dao",
DaoGenerator.class),
/** DDL作成 */
DDL("DDL", "nok-docs\\02_design\\90_db\\01_ddl", CreateTableGenerator.class),
/** DROP作成 */
DROP("DROP", "nok-docs\\02_design\\90_db\\02_drop", DropSqlGenerator.class),
/** テーブル定義作成 */
TABLE_DEFINE("TABLE_DEFINE", "nok-docs\\02_design\\90_db\\99_others",
TableDefineGenerator.class);
/** 値 */
private String value;
/** 出力先パス */
private String path;
/** 自動生成クラス型 */
private Class<? extends BaseGenerator> genClass;
/**
* コンストラクタ
*
* @param value
* 値
* @param path
* 出力先パス
* @param genClass
* 自動生成クラス型
*/
private GenerateType(String value, String path,
Class<? extends BaseGenerator> genClass) {
this.value = value;
this.path = path;
this.genClass = genClass;
}
@Override
public String getValue() {
return this.value;
}
public String getPath() {
return this.path;
}
public Class<? extends BaseGenerator> getGenClass() {
return this.genClass;
}
public static GenerateType of(String value) {
return BaseEnum.of(GenerateType.class, value);
}
}
}
| true
|
a9f9d0b4d6b81fc3e5d54a25b9d2ae232ece5d7d
|
Java
|
zyk492322922/framework
|
/framework-api/src/main/java/com/zyk/api/controller/demo/DemoController.java
|
UTF-8
| 1,315
| 1.804688
| 2
|
[] |
no_license
|
/*
* @Copyright: 2005-2018 www.hyjf.com. All rights reserved.
*/
package com.zyk.api.controller.demo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zyk.api.common.response.R;
import com.zyk.api.service.entity.SysDept;
import com.zyk.api.common.response.R;
import com.zyk.api.service.entity.SysDept;
import com.zyk.api.service.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author zhangqingqing
* @version DemoController, v0.1 2019/11/27 9:52
*/
@Slf4j
@RestController
@Api(value = "接口示例",tags = "接口示例")
@RequestMapping("/demo")
public class DemoController {
@Autowired
ISysDeptService iSysDeptService;
@ApiOperation(value = "分页查询")
@GetMapping("/pageSearch")
public R<List<SysDept>> pageSearch(){
IPage<SysDept> result = iSysDeptService.pageSearch(2,3);
return R.data(result.getRecords());
}
}
| true
|
3b631925ad719be1260c43ccc212f716c2949771
|
Java
|
juanmanuelromeraferrio/start-android
|
/server/src/main/resources/source/package/java/infrastructure/StartAndroidDatabase.java
|
UTF-8
| 1,111
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package #PACKAGE_NAME#.infrastructure;
import android.content.Context;
import android.content.SharedPreferences;
import #PACKAGE_NAME#.StartAndroidApplication;
import com.google.gson.Gson;
/**
* Created by Juan Manuel Romera on 18/5/2016.
*/
public class StartAndroidDatabase implements Database {
private static final String DB = "DB";
@Override
public <T extends Object> void save(String key, Object value) {
SharedPreferences sharedPref = StartAndroidApplication.getContext().getSharedPreferences(DB, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = sharedPref.edit();
Gson gson = new Gson();
String json = gson.toJson(value);
prefsEditor.putString(key, json);
prefsEditor.commit();
}
@Override
public <T extends Object> T get(String key, Class<T> classValue) {
SharedPreferences sharedPref = StartAndroidApplication.getContext().getSharedPreferences(DB, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPref.getString(key, "");
return gson.fromJson(json, classValue);
}
}
| true
|
47ec947a77faa473531401b44fddd5bf437a8a92
|
Java
|
saramb/routeIt
|
/app/src/main/java/com/it/mahaalrasheed/route/from.java
|
UTF-8
| 7,748
| 1.890625
| 2
|
[] |
no_license
|
package com.it.mahaalrasheed.route;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import java.util.ArrayList;
import java.util.List;
import io.realm.Realm;
public class from extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks {
Realm relam;
List<FavoriteClass> item;
ListView lv;
int id;
String[] array;
ArrayAdapter addapter;
////////////////////// search ////////////////////
private static final int GOOGLE_API_CLIENT_ID = 0;
private AutoCompleteTextView mAutocompleteTextView;
private GoogleApiClient mGoogleApiClient;
private PlaceArrayAdapter mPlaceArrayAdapter;
public static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(24.329542, 46.380488),new LatLng(25.159071, 47.239394));
////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.activity_from);
lv = (ListView)findViewById(R.id.listView2);
update();
//////---search-----////
mGoogleApiClient = new GoogleApiClient.Builder(from.this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this)
.build();
mAutocompleteTextView = (AutoCompleteTextView) findViewById(R.id
.autoCompleteTextView);
mAutocompleteTextView.setThreshold(1);
mAutocompleteTextView.setOnItemClickListener(mAutocompleteClickListener);
mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,
BOUNDS_MOUNTAIN_VIEW, null);
mAutocompleteTextView.setAdapter(mPlaceArrayAdapter);
if(!mAutocompleteTextView.hasFocus()){
Drawable image = getResources().getDrawable(R.mipmap.ic_launcher);
image.setBounds(12, 0, 80, 68);
mAutocompleteTextView.setCompoundDrawables(image, null, null, null);
// mAutocompleteTextView.setCompoundDrawablesWithIntrinsicBounds( R.mipmap.searchicon2, 0, 0, 0);
mAutocompleteTextView.setHint(" Search");
}
mAutocompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
Drawable image = getResources().getDrawable(R.mipmap.ic_launcher);
image.setBounds(12, 0, 80, 68);
mAutocompleteTextView.setCompoundDrawables(image, null, null, null);
// mAutocompleteTextView.setCompoundDrawablesWithIntrinsicBounds( R.mipmap.searchicon2, 0, 0, 0);
mAutocompleteTextView.setHint(" Search");
} else {
//Assign your image again to the view, otherwise it will always be gone even if the text is 0 again.
mAutocompleteTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
mAutocompleteTextView.setHint(" ");
}
}
});
}
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i("s", "Selected: " + item.description);
Log.i("s", "Fetching details for ID: " + item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess())
return;
else {
// Selecting the first object buffer.
final Place place = places.get(0);
Intent n = new Intent(from.this, map.class);
n.putExtra("page","from".toString());
n.putExtra("name", place.getName().toString());
n.putExtra("lat", place.getLatLng().latitude );
n.putExtra("lng", place.getLatLng().longitude);
startActivity(n);
finish();}
}
};
public void update(){
relam = Realm.getInstance(getApplicationContext());
item = relam.allObjects(FavoriteClass.class);
array = new String[item.size()];
for (int i = 0; i < item.size(); i++) {
array[i] = item.get(i).getName();}
addapter = new ArrayAdapter(from.this, android.R.layout.simple_list_item_1,array);
lv.setAdapter(addapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent n = new Intent(from.this, map.class);
FavoriteClass F = relam.allObjects(FavoriteClass.class).get(position);
n.putExtra("page","from");
n.putExtra("name",F.getName().toString());
n.putExtra("lat", F.getLat());
n.putExtra("lng", F.getLng());
startActivity(n);
finish();
}
});
}
@Override
public void onConnected(Bundle bundle) {
mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,
"Google Places API connection failed with error code:" +
connectionResult.getErrorCode(),
Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionSuspended(int i) {
mPlaceArrayAdapter.setGoogleApiClient(null);
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.from_back, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId()== R.id.back){
finish();
}
return true;
}
}
| true
|
a1b62ad1fd7e69cb1ee25c462c6decaece3389bb
|
Java
|
yesamer/drools
|
/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/constraints/LambdaFieldReader.java
|
UTF-8
| 1,716
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2020. Red Hat, Inc. and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.modelcompiler.constraints;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.drools.base.base.CoreComponentsBuilder;
import org.drools.model.functions.Function1;
import org.drools.util.ClassUtils;
import static org.drools.base.util.Drools.hasMvel;
public class LambdaFieldReader implements Function1 {
private final Method accessor;
private final String field;
public LambdaFieldReader( Class<?> clazz, String field ) {
this.accessor = ClassUtils.getAccessor( clazz, field );
this.field = field;
}
@Override
public Object apply( Object o ) {
try {
if (accessor != null) {
return accessor.invoke( o );
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException( e );
}
if (!hasMvel()) {
throw new RuntimeException("Complex timestamp expressions can be used only with drools-mvel on classpath");
}
return CoreComponentsBuilder.get().getMVELExecutor().eval( field, o );
}
}
| true
|
27b60ca837377b37a8fdc91a16dd3649294ebf9e
|
Java
|
tobinatore/MC_RobeK_App
|
/app/src/main/java/com/noethlich/tobias/mcrobektrainingsplaner/WahlFragment.java
|
UTF-8
| 1,336
| 1.914063
| 2
|
[] |
no_license
|
package com.noethlich.tobias.mcrobektrainingsplaner;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Tobias on 05.08.2016.
*/
public class WahlFragment extends Fragment {
GridView gridView;
Context context;
ArrayList<Boolean> activatedButtons;
ButtonCheck bc = new ButtonCheck();
public WahlFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_wahl, container, false);
gridView = (GridView) v.findViewById(R.id.gridView1);
gridView.setAdapter(new GridAdapter(context));
return v;
}
}
| true
|
432ab1240559f1af9248d7653d9769a58c036e70
|
Java
|
xrealm/tiktok-src
|
/sources/com/p280ss/android/ugc/aweme/profile/p1487ui/BindAccountView.java
|
UTF-8
| 7,808
| 1.609375
| 2
|
[] |
no_license
|
package com.p280ss.android.ugc.aweme.profile.p1487ui;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.support.p029v7.app.AlertDialog.C1081a;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bytedance.ies.ugc.appcontext.C6399b;
import com.p280ss.android.ugc.aweme.profile.model.User;
import com.p280ss.android.ugc.aweme.profile.service.C36065a;
import com.p280ss.android.ugc.aweme.shortvideo.util.C41540at;
import com.p280ss.android.ugc.aweme.utils.C42951au;
import com.p280ss.android.ugc.aweme.views.AutoRTLImageView;
import com.zhiliaoapp.musically.df_live_zego_link.R;
import java.util.ArrayList;
/* renamed from: com.ss.android.ugc.aweme.profile.ui.BindAccountView */
public class BindAccountView extends LinearLayout {
/* renamed from: a */
protected Context f94542a;
/* renamed from: b */
protected LinearLayout f94543b;
/* renamed from: c */
protected TextView f94544c;
/* renamed from: d */
protected AutoRTLImageView f94545d;
/* renamed from: e */
protected AutoRTLImageView f94546e;
/* renamed from: f */
protected AutoRTLImageView f94547f;
/* renamed from: g */
protected C36132a f94548g;
/* renamed from: h */
private ArrayList<Integer> f94549h;
/* renamed from: i */
private boolean f94550i;
/* renamed from: com.ss.android.ugc.aweme.profile.ui.BindAccountView$a */
public interface C36132a {
/* renamed from: a */
void mo91966a();
/* renamed from: a */
void mo91967a(int i);
}
public void setEventListener(C36132a aVar) {
this.f94548g = aVar;
}
public void setIsMyProfile(boolean z) {
this.f94550i = z;
}
public BindAccountView(Context context) {
this(context, null);
}
/* renamed from: a */
private String m116528a(int i) {
switch (i) {
case 1:
return this.f94542a.getString(R.string.buc);
case 2:
return this.f94542a.getString(R.string.ftd);
case 3:
return this.f94542a.getString(R.string.fh4);
default:
return "";
}
}
/* access modifiers changed from: protected */
/* renamed from: a */
public void mo91959a(Context context) {
this.f94542a = context;
View inflate = LayoutInflater.from(context).inflate(R.layout.b2l, this, true);
this.f94543b = (LinearLayout) inflate.findViewById(R.id.bke);
this.f94544c = (TextView) inflate.findViewById(R.id.ckr);
this.f94545d = (AutoRTLImageView) inflate.findViewById(R.id.axl);
this.f94546e = (AutoRTLImageView) inflate.findViewById(R.id.axt);
this.f94547f = (AutoRTLImageView) inflate.findViewById(R.id.axx);
this.f94543b.setOnTouchListener(new C36566p(this));
}
/* renamed from: b */
private void m116530b(User user) {
int size = this.f94549h.size();
if (size == 1) {
int intValue = ((Integer) this.f94549h.get(0)).intValue();
m116529a(user, intValue);
if (this.f94548g != null) {
this.f94548g.mo91967a(intValue);
}
} else if (size > 1 && this.f94542a != null && user != null) {
C1081a aVar = new C1081a(this.f94542a);
ArrayList arrayList = new ArrayList();
ArrayList arrayList2 = new ArrayList();
if (!TextUtils.isEmpty(user.getInsId())) {
arrayList.add(Integer.valueOf(1));
arrayList2.add(this.f94542a.getString(R.string.buc));
}
if (!TextUtils.isEmpty(user.getYoutubeChannelId())) {
arrayList.add(Integer.valueOf(2));
arrayList2.add(this.f94542a.getString(R.string.ftd));
}
if (!C6399b.m19946v() && !TextUtils.isEmpty(user.getTwitterId())) {
arrayList.add(Integer.valueOf(3));
arrayList2.add(this.f94542a.getString(R.string.fh4));
}
aVar.mo4236a((CharSequence[]) arrayList2.toArray(new String[0]), (OnClickListener) new C36568r(this, arrayList, user));
C42951au.m136342a(aVar.mo4242b());
}
}
/* renamed from: a */
public final void mo91960a(User user) {
if (this.f94542a != null) {
this.f94549h.clear();
if (!TextUtils.isEmpty(user.getInsId())) {
this.f94549h.add(Integer.valueOf(1));
setVisibility(0);
this.f94545d.setVisibility(0);
} else {
this.f94545d.setVisibility(8);
}
if (!TextUtils.isEmpty(user.getYoutubeChannelId())) {
this.f94549h.add(Integer.valueOf(2));
setVisibility(0);
this.f94546e.setVisibility(0);
} else {
this.f94546e.setVisibility(8);
}
if (TextUtils.isEmpty(user.getTwitterName()) || C6399b.m19946v()) {
this.f94547f.setVisibility(8);
} else {
this.f94549h.add(Integer.valueOf(3));
setVisibility(0);
this.f94547f.setVisibility(0);
}
if (this.f94549h.size() == 0) {
setVisibility(8);
return;
}
if (this.f94549h.size() == 1) {
String a = m116528a(((Integer) this.f94549h.get(0)).intValue());
TextView textView = this.f94544c;
if (TextUtils.isEmpty(a)) {
a = this.f94542a.getString(R.string.c_z);
}
textView.setText(a);
} else {
this.f94544c.setText(R.string.c_z);
}
setVisibility(0);
this.f94543b.setOnClickListener(new C36567q(this, user));
}
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public final /* synthetic */ void mo91961a(User user, View view) {
m116530b(user);
}
public BindAccountView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
/* renamed from: a */
private void m116529a(User user, int i) {
if (user != null && this.f94542a != null) {
C36065a.f94305a.mo91794a(this.f94542a, user, i);
}
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public final /* synthetic */ boolean mo91963a(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case 0:
C41540at.m132302a(this.f94543b, 1.0f, 0.5f, 150);
break;
case 1:
break;
}
C41540at.m132302a(this.f94543b, 0.5f, 1.0f, 150);
if (this.f94548g != null) {
this.f94548g.mo91966a();
}
return false;
}
public BindAccountView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.f94549h = new ArrayList<>();
mo91959a(context);
}
/* access modifiers changed from: 0000 */
/* renamed from: a */
public final /* synthetic */ void mo91962a(ArrayList arrayList, User user, DialogInterface dialogInterface, int i) {
if (i < arrayList.size()) {
int intValue = ((Integer) arrayList.get(i)).intValue();
m116529a(user, intValue);
if (this.f94548g != null) {
this.f94548g.mo91967a(intValue);
}
}
}
}
| true
|
fce1ae160286a536b8abc9472d527e6be21dde2b
|
Java
|
Arshad101/HotelBooking
|
/app/src/main/java/com/ans/hotel_booking/Admin_login.java
|
UTF-8
| 1,353
| 2.0625
| 2
|
[] |
no_license
|
package com.ans.hotel_booking;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Admin_login extends AppCompatActivity {
EditText Admnuser;
EditText Admnpass;
Button Admnlogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
Admnuser = (EditText)findViewById(R.id.AdmetName);
Admnpass= (EditText)findViewById(R.id.Admetpass);
Admnlogin= (Button) findViewById(R.id.Admbtnlogin);
Admnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validate(Admnuser.getText().toString(), Admnpass.getText().toString());
}
});
}
private void validate(String userName, String userPassword) {
if ((userName.equals("Admin")) && (userPassword.equals("1234"))) {
Intent intent = new Intent(Admin_login.this, logged_admin.class);
startActivity(intent);
} else
Toast.makeText(Admin_login.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
| true
|
e43352394fd23156b2f9565a94e8afa3e4b5c4be
|
Java
|
Massimo931/Java
|
/Progetti BlueJ/Grafici/grafico1/FunctionPanel.java
|
UTF-8
| 2,162
| 3.3125
| 3
|
[] |
no_license
|
import java.awt.*;
import javax.swing.*;
class FunctionPanel extends JPanel
{
int xMin=-9, xMax=5, yMin=-3, yMax=4;
int larghezza=800, altezza=600;
float fattoreScalaX, fattoreScalaY;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.white);
fattoreScalaX=larghezza/((float)xMax-xMin);
fattoreScalaY=altezza/((float)yMax-yMin);
//g.drawString("Grafico funzione (3x^2 - 2)/(2x^2 + 1) by Massimo Arnoni",60,40);
for(int x=0; x<800; x=x+20) {
g.setColor(Color.green);
g.drawLine(x, 0, x, 600);
}
for(int y=0; y<600; y=y+20) {
g.setColor(Color.green);
g.drawLine(0, y, 800, y);
}
g.setColor(Color.black);
g.drawRect(0,0,larghezza-1,altezza-1);
// assi cartesiani
g.setColor(Color.red);
g.drawLine(0, Math.round((-yMin) * fattoreScalaY), larghezza-1, Math.round((-yMin)*fattoreScalaY));
g.drawLine(Math.round((-xMin) * fattoreScalaX), 0, Math.round((-xMin)*fattoreScalaX), altezza - 1);
// estremi degli assi
g.drawString(""+xMin, 5, Math.round((-yMin)*fattoreScalaY) - 5);
g.drawString(""+xMax, larghezza + 5, Math.round((-yMin)*fattoreScalaY) - 5);
g.drawString(""+yMax, Math.round((-xMin) * fattoreScalaX) + 5, 15);
g.drawString(""+yMin, Math.round((-xMin) * fattoreScalaX) + 5,altezza - 5);
g.setColor(Color.blue);
setPixel(g,xMin,f(xMin));
for (int ix=1; ix<larghezza; ix++)
{
float x = xMin+((float)ix)/fattoreScalaX;
setPixel(g,x,f(x));
}
}
static float f(float x)
{
return (float)((3 * (x * x)) - 2)/((2 * (x * x)) + 1);
}
void setPixel(Graphics g, float x, float y)
{
if (x<xMin || x>xMax || y<yMin || y>yMax)
return;
int ix = Math.round((x-xMin)*fattoreScalaX);
int iy = altezza-Math.round((y-yMin)*fattoreScalaY);
g.drawLine(ix,iy,ix,iy);
}
}
| true
|
060f64ee50734a7f6f706a4ccec364257306d425
|
Java
|
jeremysamuel13/AuctionSystem
|
/src/Auction.java
|
UTF-8
| 6,043
| 3.15625
| 3
|
[] |
no_license
|
/*
* @author Jeremy Samuel
* E-mail: jeremy.samuel@stonybrook.edu
* Stony Brook ID: 113142817
* CSE 214
* Recitation Section 3
* Recitation TA: Dylan Andres
* HW #6
*/
import java.io.Serializable;
/**
* Auction class
* Holds all info of a specific auction
*/
public class Auction implements Serializable {
int timeRemaining;
double currentBid;
String auctionID;
String sellerName;
String buyerName;
String itemInfo;
//contains currentBid in a string format which is later turned into the
// dollar/cent format ($xx.xx)
String stringBid;
boolean open;
public Auction(){
}
/**
* Constructor with parameters
* @param timeRemaining
* The time remaining in the auction
* @param currentBid
* The current bid on the auction
* @param auctionID
* The id of the auction
* @param sellerName
* The seller of the auction
* @param buyerName
* The buyer/highest bidder of the auction
* @param itemInfo
* Info of the auction. Includes cpu, memory and hdd info.
*/
public Auction(int timeRemaining, double currentBid, String auctionID,
String sellerName, String buyerName, String itemInfo){
this.timeRemaining = timeRemaining;
this.currentBid = currentBid;
this.auctionID = auctionID;
this.sellerName = sellerName;
this.buyerName = buyerName;
this.itemInfo = itemInfo;
open = timeRemaining != 0;
//converts currentBid into stringBid which will be used for printing
if(currentBid > -1){
stringBid = Double.toString(currentBid);
if(stringBid.substring(stringBid.indexOf(".") + 1).length() != 2){
stringBid = stringBid + "0";
}
}
}
/**
* Gets the time remaining of the auction
* @return
* Returns the time remaining of the auction
*/
public int getTimeRemaining() {
return timeRemaining;
}
/**
* Gets the current bid of the auction
* @return
* Returns the current bid of the auction
*/
public double getCurrentBid() {
return currentBid;
}
/**
* Gets the id of the auction
* @return
* Returns the id of the auction
*/
public String getAuctionID() {
return auctionID;
}
/**
* Gets the seller name of the auction
* @return
* Returns the seller name of the auction
*/
public String getSellerName() {
return sellerName;
}
/**
* Gets the name of the buyer/highest bidder of auction
* @return
* Returns the buyer/highest bidder of auction
*/
public String getBuyerName() {
return buyerName;
}
/**
* Gets the info of the auction
* @return
* Returns the info of the auction
*/
public String getItemInfo() {
return itemInfo;
}
/**
* Gets the currentBid in a dollar/cent form
* @return
* Returns the currentBid in a dollar/cent form
*/
public String getStringBid() {
return stringBid;
}
/**
* Gets if the auction is open or not
* @return
* Returns true if auction is open, false if otherwise
*/
public boolean isOpen() {
return open;
}
/**
* Decrements the time of the current auction
* @param time
* The amount of time (in hours) that you want to pass
*/
public void decrementTimeRemaining(int time){
if(time > timeRemaining) {
timeRemaining = 0;
open = false;
}else
timeRemaining = timeRemaining - time;
}
/**
* Creates a new bid on the current auction and overwrites the previous
* bid if the new bid exceeds the previous bid
* @param bidderName
* The name of the bidder
* @param bidAmt
* The amount the bidder has bid on the auction
* @throws ClosedAuctionException
* Throws exception when auction is closed
*/
public void newBid(String bidderName, double bidAmt) throws
ClosedAuctionException, IllegalArgumentException{
if(open){
if(bidAmt > currentBid) {
currentBid = bidAmt;
buyerName = bidderName;
stringBid = Double.toString(currentBid);
if(stringBid.substring(stringBid.indexOf(".") + 1)
.length() != 2){
stringBid = stringBid + "0";
}
}else if(bidAmt < 0){
throw new IllegalArgumentException("Invalid bid: Bid amount " +
"has to be a positive value and greater than the " +
"current bid");
}else{
throw new IllegalArgumentException("Bid has to be higher than" +
" current bid");
}
}else{
throw new ClosedAuctionException("Auction is closed");
}
}
/**
* Converts auction into a readable string which is to be used in the
* printTable() method in the AuctionTable class
* @return
* Returns a String that contains the auction in a readable manner
*/
public String toString(){
//removes new lines that are caused by flawed formatting in xml (ex.
// o econgo1 in the yahoo auction data)
itemInfo = itemInfo.replace("\n", "");
sellerName = sellerName.replace("\n", "");
if(currentBid == -1 && buyerName == null){
return String.format("%12s%3s%11s%3s%-22s%4s%24s%3s%10s%3s%-100s",
auctionID, " | ", "", " | ", sellerName, " | ",
"", " | ", timeRemaining + " hours", " | ", itemInfo);
}else {
return String.format("%12s%4s%10s%3s%-22s%4s%24s%3s%10s%3s%-100s",
auctionID, " | $", stringBid, " | ", sellerName, " | ",
buyerName, " | ", timeRemaining + " hours", " | ",
itemInfo);
}
}
}
| true
|
fe58c51e5208236ec5719d6263fb0df4ce41d960
|
Java
|
C1507930/itcast0820Project
|
/src/com/ivo/service/IFollowUpRequisitionService.java
|
UTF-8
| 191
| 1.648438
| 2
|
[] |
no_license
|
package com.ivo.service;
import com.ivo.domain.FollowUpRequisition;
public interface IFollowUpRequisitionService {
void saveFollowUpRequisition(FollowUpRequisition followUpRequisition);
}
| true
|
8df29e737abb7e5f8083fe78d6bfb4560a052340
|
Java
|
SHDori/ComunityBoard
|
/src/main/java/Gachon/ComunityBoard/config/auth/SecurityConfig.java
|
UTF-8
| 3,234
| 1.984375
| 2
|
[] |
no_license
|
package Gachon.ComunityBoard.config.auth;
import Gachon.ComunityBoard.config.JwtAuthFilter;
import Gachon.ComunityBoard.domain.user.Role;
import Gachon.ComunityBoard.service.token.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomOAuth2UserService customOAuth2UserService;
private final OAuth2AuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler;
private final TokenService tokenService;
protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.httpBasic().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.cors().configurationSource(corsConfigurationSource())
//.headers().frameOptions().disable()
.and()
.authorizeRequests()
// .antMatchers("/**","/css/**","/js/**","/images/**","/api/board/search/**","/api/board/all","/api/loginedUser").permitAll()// 모두에게 허용
// .antMatchers("/api/**").hasRole(Role.USER.name()) // User권한가진사람한테만 허용
// .anyRequest().authenticated() //나머지페이지는 인증된 사람에게만 허용
//.antMatchers("/api/board/posts/**","/api/user/userInfo/**").authenticated()
.anyRequest().permitAll()
.and()
.logout()
.logoutSuccessUrl("/api/board")
.and()
.oauth2Login()
.defaultSuccessUrl("/api/board")
.successHandler(oAuth2AuthenticationSuccessHandler)
.userInfoEndpoint()
.userService(customOAuth2UserService);
http.addFilterBefore(new JwtAuthFilter(tokenService), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOriginPattern("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
| true
|
374dec06090052063643a7e4bfba2e36908b79d9
|
Java
|
WikiToLearn/WikiRating
|
/src/main/java/org/wikitolearn/wikirating/service/mediawiki/RevisionMediaWikiService.java
|
UTF-8
| 3,532
| 2.234375
| 2
|
[] |
no_license
|
package org.wikitolearn.wikirating.service.mediawiki;
import com.fasterxml.jackson.core.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.wikidata.wdtk.wikibaseapi.ApiConnection;
import org.wikitolearn.wikirating.exception.GetDiffPreviousRevisionExeception;
import org.wikitolearn.wikirating.model.graph.Revision;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* @author aletundo, valsdav
*
*/
@Service
public class RevisionMediaWikiService extends MediaWikiService<Revision>{
/**
* Get the revision
* @param apiUrl
* @return the revision with the diff information
* @throws GetDiffPreviousRevisionExeception
*/
public String getDiffPreviousRevision(String apiUrl, int oldRevId, int newRevId)
throws GetDiffPreviousRevisionExeception {
try {
Map<String, String> parameters = mediaWikiApiUtils.getDiffRevisionParams(oldRevId, newRevId);
ApiConnection connection = mediaWikiApiUtils.getApiConnection(apiUrl);
InputStream response = mediaWikiApiUtils.sendRequest(connection, "GET", parameters);
JSONObject responseJson = mediaWikiApiUtils.streamToJson(response);
String diffText = responseJson.getJSONObject("compare").getString("*");
return diffText;
} catch (JSONException e) {
LOG.error("An error occurred getting diff of previous revision of revision with id: {}. {}", newRevId,
e.getMessage());
throw new GetDiffPreviousRevisionExeception();
}
}
/**
* Get all the revisions for a specific page querying MediaWiki API
* @param apiUrl the MediaWiki API url
* @param pageId the id the page of which getting the revisions
* @return revisions a list that contains all the fetched revisions
*/
public List<Revision> getAllRevisionByPageId(String apiUrl, int pageId) {
Map<String, String> parameters = mediaWikiApiUtils.getRevisionParams(pageId);
ApiConnection connection = mediaWikiApiUtils.getApiConnection(apiUrl);
InputStream response;
boolean moreRevs = true;
JSONArray revsJson = new JSONArray();
List<JSONArray> toBeConcat = new ArrayList<>();
List<Revision> revs = new ArrayList<>();
try {
while(moreRevs){
response = mediaWikiApiUtils.sendRequest(connection, "GET", parameters);
JSONObject responseJson = mediaWikiApiUtils.streamToJson(response);
toBeConcat.add(responseJson.getJSONObject("query").getJSONObject("pages").
getJSONObject(parameters.get("pageids")).getJSONArray("revisions"));
if(responseJson.has("continue")){
String continueFrom = responseJson.getJSONObject("continue").getString("rvcontinue");
parameters.put("rvcontinue", continueFrom);
}else{
moreRevs = false;
revsJson = concatArrays(toBeConcat);
}
}
revs = mapper.readValue(revsJson.toString(), new TypeReference<List<Revision>>(){});
return revs;
} catch (JSONException e){
LOG.error("An error occurred while a JSONObject or JSONArray. {}", e.getMessage());
} catch(IOException e){
LOG.error("An error occurred while converting an InputStream to JSONObject. {}", e.getMessage());
}
return revs;
}
}
| true
|
7289e315baf86820aa5f80daef542df67753204f
|
Java
|
arghhjayy/Java-Stuff
|
/src/KadaneAlgo.java
|
UTF-8
| 649
| 3.65625
| 4
|
[] |
no_license
|
//Given an array containing both negative and positive integers.
//Find the contiguous sub-array with maximum sum.
public class KadaneAlgo {
//Algorithm:
//set running maximum = INFINITY, max ends here = 0
public static int findMaximumSum(int[] arr){
int running_maximum = arr[0];
int maximum = arr[0];
for(int i = 0; i < arr.length; i++){
running_maximum = Math.max(arr[i], running_maximum + arr[i]);
maximum = Math.max(running_maximum, maximum);
}
return maximum;
}
public static void main(String[] args) {
int[] arr = {1, -1, 2, -2, 3, 4, -6, -1, 1, 5, -2};
System.out.println(findMaximumSum(arr));
}
}
| true
|
1cc1cf21cfb90b04f95fcc5f9a290f8d6473d13d
|
Java
|
EssinZhang/JavaLearning
|
/jdk8Project/src/chapter1/default_keyboard/Animal.java
|
UTF-8
| 430
| 3.28125
| 3
|
[] |
no_license
|
package chapter1.default_keyboard;
/**
* description: Animal <br>
* date: 2020/9/16 16:10 <br>
*
* @author: ZhangYixin <br>
* version: 1.0 <br>
*/
public interface Animal {
void run();
void eat();
default void breath(){
System.out.println("呼吸氧气");
}
static void test(){
System.out.println("接口中写静态方法");
System.out.println("小狗静静站着");
}
}
| true
|
b0cece3bbe89c5b9d68b79bf1fe83c34d44ad49c
|
Java
|
Turtle54321/RecruitInform
|
/RecruitInform/src/main/java/com/recruit/controller/TeacherSide.java
|
UTF-8
| 6,631
| 2.109375
| 2
|
[] |
no_license
|
package com.recruit.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.mail.Message.RecipientType;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.recruit.pojo.M2sList;
import com.recruit.pojo.Message;
import com.recruit.pojo.Message2student;
import com.recruit.pojo.Student;
import com.recruit.pojo.Teacher;
import com.recruit.service.M2sService;
import com.recruit.service.MessageService;
import com.recruit.service.StudentService;
import com.recruit.service.TeacherService;
import com.recruit.util.MailUtil;
@Controller
@RequestMapping("/teacher")
public class TeacherSide {
@Resource
private TeacherService tDAO;
@Resource
private MessageService mDAO;
@Resource
private M2sService m2sDAO;
@Resource
private StudentService studentDAO;
@RequestMapping("/tlogin")
public String login(String teacherId, String password, HttpSession session, HttpServletRequest request,
Model model) {
Teacher teacher = tDAO.getTeacherById(Integer.parseInt(teacherId));
if (teacher == null) {
model.addAttribute("message", "无该用户!");
} else if (!password.equals(teacher.getPassword().trim())) {
model.addAttribute("message", "密码错误!");
} else if (password.equals(teacher.getPassword().trim())) {
session.setAttribute("teacherId", teacherId);
return "infolist.do";
} else {
model.addAttribute("message", "未知错误!");
}
return "redirect:/tlogin.jsp";
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/tlogin.jsp";
}
@RequestMapping("/infolist")
public String infolist(HttpServletRequest request, Model model) {
List<Message> mList = mDAO.selectAll();
model.addAttribute("messagelist", mList);
int count = 10;
if (request.getParameter("count") != null) {
System.out.println(request.getParameter("count") + "!!!");
// 确保count为进一的整十
count = (Integer.parseInt(request.getParameter("count").trim()) + 9) / 10 * 10;
String type = request.getParameter("type");
System.out.println(type);
System.out.println(("1".equals(type)));
if ("-1".equals(type))
count = count - 10;
if ("1".equals(type))
count = count + 10;
}
if (count >= mList.size()) {
count = mList.size();
model.addAttribute("full", -1);
}
System.out.println(count);
model.addAttribute("count", count);
return "infolist.jsp";
}
@RequestMapping("/infodetails")
public String infodetails(HttpServletRequest request, Model model) {
int messageId = Integer.parseInt(request.getParameter("messageId"));
Message message = mDAO.getMessageById(messageId);
List<Message2student> infoViewList = m2sDAO.getAllStudent(messageId);
model.addAttribute("message", message);
model.addAttribute("viewlist", infoViewList);
return "infodetails.jsp";
}
@RequestMapping("/infofeedback")
public String infofeedback(HttpServletRequest request, Model model) {
int messageId = Integer.parseInt(request.getParameter("messageId"));
Message message = mDAO.getMessageById(messageId);
List<Message2student> infoViewList = m2sDAO.getAllStudent(messageId);
model.addAttribute("message", message);
model.addAttribute("viewlist", infoViewList);
return "infofeedback.jsp";
}
@RequestMapping("/newInform")
public String newInform(Message message, M2sList infoViewList, HttpSession session,
HttpServletResponse response) {
System.out.println(message.getType());
//获取当前日期时间并加入到message中
Date date=new Date();
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
String curTime=format.format(date);
message.setReleaseTime(curTime);
//判断通知学生是否存在于student表中
// StudentDAO studentDAO = (StudentDAO) MyBeansFactory.getBeans("studentdao");
// for (Message2student view : infoViewList.getM2sList()) {
//
// Student student = studentDAO.getStudentById(view.getStudent_id());
// PrintWriter out;
// try {
// out = response.getWriter();
// if (student == null) {
// out.print("<script language='javascript'>alert('学号为" + view.getStudent_id()
// + "的同学不在数据库中');window.location='newInform.jsp';</script>");
// return null;
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// System.out.println("getWriter失败!");
// return "newInform.jsp";
// }
//
// }
int teacherId = Integer.parseInt(session.getAttribute("teacherId").toString());
message.setIssuer(teacherId);
mDAO.insertSelective(message);
int messageId = message.getMessageId();
System.out.println("teacherId:" + teacherId);
for (Message2student view : infoViewList.getInfoViewList()) {
view.setMessageId(messageId);
if(view.getMail() == ""){
Student student = studentDAO.getStudentById(view.getStudentId());
if(student != null)
view.setMail(student.getMail().trim());
}
try {
System.out.println(view.getMail().trim());
InternetAddress to = new InternetAddress(view.getMail().trim());
MimeMessage mail = new MailUtil().SendMail();
mail.setRecipient(RecipientType.TO, to);
// 设置主题
mail.setSubject(message.getType());
// 设置邮件内容
mail.setContent("请于" + message.getDeadline() + view.getNote() + "到" + message.getPlace(),
"text/html;charset=UTF-8");
Transport.send(mail);
System.out.println("发送邮件成功");
view.setIsSendMail(1);
// 发送邮件成功
} catch (Exception e) {
// TODO Auto-generated catch block
view.setIsSendMail(0); // 发送邮件失败
// e.printStackTrace();
System.out.println("发送邮件失败");
} finally {
// TODO: handle finally clause
System.out.println("!!!"+view.getStudentId());
m2sDAO.insertMessage2student(view);
System.out.println("插入成功");
}
}
return "infodetails.do?messageId=" + messageId;
}
}
| true
|
02ad57e5d997bfee63a1a0dac04325284f7bf2a0
|
Java
|
icudroid/mtzik-v2
|
/apps/webapps/artist-bo-webapp/src/main/java/fr/k2i/adbeback/webapp/bean/security/PermissionRightDto.java
|
UTF-8
| 364
| 1.703125
| 2
|
[] |
no_license
|
package fr.k2i.adbeback.webapp.bean.security;
import lombok.Data;
import lombok.experimental.Builder;
import java.io.Serializable;
import java.util.List;
/**
* User: dimitri
* Date: 13/01/15
* Time: 14:35
* Goal:
*/
@Data
@Builder
public class PermissionRightDto implements Serializable{
private String permission;
private List<RightDto> rights;
}
| true
|
6a21bc50083489a6cee345647ab19fc1c5ca1bac
|
Java
|
araideeja/rest-spring-boot-demo
|
/src/main/java/com/tbank/om/dwh/accountInquiry/AccountInquiryApplication.java
|
UTF-8
| 339
| 1.679688
| 2
|
[] |
no_license
|
package com.tbank.om.dwh.accountInquiry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccountInquiryApplication {
public static void main(String[] args) {
SpringApplication.run(AccountInquiryApplication.class, args);
}
}
| true
|
9444820ebb1eddd51c29c74b62992ac59c75fcd9
|
Java
|
moonlooker/myliabilities
|
/src/main/java/com/myliabilities/dao/AStartTableCheck.java
|
UTF-8
| 712
| 2.140625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.myliabilities.dao;
import com.myliabilities.dao.accountbook.CreateAccountbookTable;
import com.myliabilities.dao.accountt.CreateAccountTable;
import com.myliabilities.dao.liabilities.CreateLiabilitiesTable;
/**
* 应用启动,如果没有表就创建一个
* @author LL
* 2020年5月25日
*/
public class AStartTableCheck {
static {
CreateAccountTable cbt = new CreateAccountTable();
cbt.createAccountTable();
cbt.createAccountIndex();
CreateAccountbookTable cabt = new CreateAccountbookTable();
cabt.createAccountTable();
cabt.createAccountIndex();
CreateLiabilitiesTable clt = new CreateLiabilitiesTable();
clt.createLiabilitiesTable();
clt.createLiabilitiesIndex();
}
}
| true
|
b152ab5500789ba29d786cde205c37814f0f1f62
|
Java
|
janng0/Android-J0Loader
|
/src/androidTest/java/ru/jango/j0loader/test/LoadingAdapter2.java
|
UTF-8
| 1,185
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package ru.jango.j0loader.test;
import ru.jango.j0loader.LoadingAdapter;
import ru.jango.j0loader.Request;
import ru.jango.j0util.LogUtil;
public class LoadingAdapter2<T> extends LoadingAdapter<T> {
@Override
public void processStarted(Request request) {
LogUtil.d(LoadingAdapter.class, "loading started: " + request.getURI());
}
@Override
public void uploadingUpdateProgress(Request request, long uploadedBytes, long totalBytes) {
LogUtil.d(LoadingAdapter.class, "uploading progress: " + (uploadedBytes * 100 / totalBytes));
}
@Override
public void downloadingUpdateProgress(Request request, long loadedBytes, long totalBytes) {
LogUtil.d(LoadingAdapter.class, "loading progress: " + (loadedBytes * 100 / totalBytes));
}
@Override
public void processFinished(Request request, byte[] rawData, T data) {
LogUtil.d(LoadingAdapter.class, "loading finished: " + request.getURI());
}
@Override
public void processFailed(Request request, Exception e) {
LogUtil.d(LoadingAdapter.class, "loading failed: " + request.getURI());
LogUtil.d(LoadingAdapter.class, e.toString());
}
}
| true
|
c37546d3ccda357be15eebd7d1f8a89b49425a00
|
Java
|
kailIII/geotoolkit
|
/modules/processing/geotk-processing/src/main/java/org/geotoolkit/processing/coverage/merge/MergeDescriptor.java
|
UTF-8
| 5,444
| 1.625
| 2
|
[] |
no_license
|
/*
* Geotoolkit.org - An Open Source Java GIS Toolkit
* http://www.geotoolkit.org
*
* (C) 2013, Geomatys
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotoolkit.processing.coverage.merge;
import java.util.HashMap;
import java.util.Map;
import org.apache.sis.util.iso.ResourceInternationalString;
import org.apache.sis.util.iso.SimpleInternationalString;
import org.geotoolkit.parameter.DefaultParameterDescriptor;
import org.geotoolkit.parameter.DefaultParameterDescriptorGroup;
import org.geotoolkit.processing.AbstractProcessDescriptor;
import org.geotoolkit.process.Process;
import org.geotoolkit.process.ProcessDescriptor;
import org.geotoolkit.processing.coverage.CoverageProcessingRegistry;
import org.opengis.coverage.Coverage;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.IdentifiedObject;
/**
*
*
* @author Johann Sorel (Geomatys)
*/
public class MergeDescriptor extends AbstractProcessDescriptor {
public static final String NAME = "merge";
/**
* Mandatory - Coverages to merge
*/
public static final ParameterDescriptor<Coverage[]> IN_COVERAGES;
/**
* Mandatory - output coverage envelope
*/
public static final ParameterDescriptor<Envelope> IN_ENVELOPE;
/**
* Mandatory - output coverage resolution
*/
public static final ParameterDescriptor<Double> IN_RESOLUTION;
public static final ParameterDescriptorGroup INPUT_DESC;
/**
* Mandatory - Resulting coverage.
*/
public static final ParameterDescriptor<Coverage> OUT_COVERAGE;
public static final ParameterDescriptorGroup OUTPUT_DESC;
static {
Map<String, Object> propertiesInCov = new HashMap<String, Object>();
propertiesInCov.put(IdentifiedObject.NAME_KEY, "coverages");
propertiesInCov.put(IdentifiedObject.ALIAS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inCoverages"));
propertiesInCov.put(IdentifiedObject.REMARKS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inCoveragesDesc"));
IN_COVERAGES = new DefaultParameterDescriptor<Coverage[]>(propertiesInCov, Coverage[].class, null, null, null, null, null, true);
Map<String, Object> propertiesInEnv = new HashMap<String, Object>();
propertiesInEnv.put(IdentifiedObject.NAME_KEY, "envelope");
propertiesInEnv.put(IdentifiedObject.ALIAS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inEnvelope"));
propertiesInEnv.put(IdentifiedObject.REMARKS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inEnvelopeDesc"));
IN_ENVELOPE = new DefaultParameterDescriptor<Envelope>(propertiesInEnv, Envelope.class, null, null, null, null, null, true);
Map<String, Object> propertiesInResolution = new HashMap<String, Object>();
propertiesInResolution.put(IdentifiedObject.NAME_KEY, "resolution");
propertiesInResolution.put(IdentifiedObject.ALIAS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inResolution"));
propertiesInResolution.put(IdentifiedObject.REMARKS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.inResolutionDesc"));
IN_RESOLUTION = new DefaultParameterDescriptor<Double>(propertiesInResolution, Double.class, null, null, null, null, null, true);
INPUT_DESC = new DefaultParameterDescriptorGroup(NAME + "InputParameters", IN_COVERAGES, IN_ENVELOPE, IN_RESOLUTION);
Map<String, Object> propertiesOutCov = new HashMap<String, Object>();
propertiesOutCov.put(IdentifiedObject.NAME_KEY, "result");
propertiesOutCov.put(IdentifiedObject.ALIAS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.outCoverage"));
propertiesOutCov.put(IdentifiedObject.REMARKS_KEY, new ResourceInternationalString("org/geotoolkit/process/coverage/bundle", "merge.outCoverageDesc"));
OUT_COVERAGE = new DefaultParameterDescriptor<Coverage>(propertiesOutCov, Coverage.class, null, null, null, null, null, true);
OUTPUT_DESC = new DefaultParameterDescriptorGroup(NAME + "OutputParameters", OUT_COVERAGE);
}
public static final ProcessDescriptor INSTANCE = new MergeDescriptor();
private MergeDescriptor() {
super(NAME, CoverageProcessingRegistry.IDENTIFICATION,
new SimpleInternationalString("Merge multiple coverages."),
INPUT_DESC, OUTPUT_DESC);
}
@Override
public Process createProcess(ParameterValueGroup input) {
return new MergeProcess(input);
}
}
| true
|
65bae425f322a3d8cad52065dc84906124f2af86
|
Java
|
pramod6019/axelaauto
|
/src/axela/ws/cust/WS_Feature_List.java
|
UTF-8
| 2,775
| 1.9375
| 2
|
[] |
no_license
|
package axela.ws.cust;
//Divya
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.sql.rowset.CachedRowSet;
import org.codehaus.jettison.json.JSONObject;
import cloudify.connect.Connect;
import cloudify.connect.ConnectWS;
import com.google.gson.Gson;
public class WS_Feature_List extends ConnectWS {
public String StrSql = "";
public String SqlJoin = "";
public String CountSql = "";
public String StrSearch = "";
public String StrHTML = "";
public String pagecurrent = "";
public String user_id = "";
public String model_id = "";
public String comp_id = "0";
public int TotalRecords = 0;
Map<Integer, Object> sqlmap = new HashMap<Integer, Object>();
Gson gson = new Gson();
JSONObject obj = new JSONObject();
ArrayList<String> list = new ArrayList<String>();
Map<String, String> map = new HashMap<String, String>();
JSONObject output = new JSONObject();
ArrayList<String> list1 = new ArrayList<String>();
Map<String, String> map1 = new HashMap<String, String>();
Connect ct = new Connect();
public JSONObject featuredata(JSONObject input) throws Exception {
if (AppRun().equals("0")) {
SOPError("input ===== " + input);
}
if (!input.isNull("user_id")) {
user_id = CNumeric(PadQuotes((String) input.get("user_id")));
}
if (!input.isNull("comp_id")) {
comp_id = CNumeric(PadQuotes((String) input.get("comp_id")));
}
if (!input.isNull("model_id")) {
model_id = CNumeric(PadQuotes((String) input.get("model_id")));
}
if (!model_id.equals("0")) {
StrSql = "Select feature_id, feature_name, coalesce(group_concat(img_value),'') as 'images'"
+ " from " + compdb(comp_id) + "axela_app_model_feature"
+ " INNER JOIN " + compdb(comp_id) + "axela_inventory_item_model ON model_id = feature_model_id"
+ " LEFT JOIN " + compdb(comp_id) + "axela_app_model_feature_img ON img_feature_id = feature_id"
+ " where 1=1"
+ " and feature_active = '1'"
+ " and feature_model_id= " + model_id
+ " GROUP BY feature_id"
+ " ORDER BY feature_name";
SOPError("StrSql = " + StrSql);
CachedRowSet crs =processQuery(StrSql, 0);
String img[] = null;
if (crs.isBeforeFirst()) {
while (crs.next()) {
map.put("feature_id", crs.getString("feature_id"));
map.put("feature_name", crs.getString("feature_name"));
list.add(gson.toJson(map)); // Converting String to Json
}
map.clear();
output.put("listdata", list);
} else {
output.put("msg", "No Feature Found!");
}
crs.close();
} else {
output.put("msg", "Invalid Request!");
}
if (AppRun().equals("0")) {
SOPError("output = " + output);
}
return output;
}
}
| true
|
7450c0127e9023b5f1f8300464e02149a64b7b04
|
Java
|
Yugp72/DSA-Programs
|
/Stacks&Queues/Implemantion/MyLLStack.java
|
UTF-8
| 1,611
| 3.890625
| 4
|
[
"MIT"
] |
permissive
|
public class MyLLStack {
public static void main(String[] args) {
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
for (int i = 0; i < 4; ++i) {
if (!s.isEmpty()) {
System.out.println(s.peek());
}
System.out.println(s.pop());
}
}
static class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
static class Stack {
int size = 0;
ListNode head, tail;
public Stack() {
head = null;
tail = null;
}
public boolean push(int val) {
ListNode newNode = new ListNode(val);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = tail.next;
}
size++;
return true;
}
public boolean pop() {
if (isEmpty()) {
return false;
}
ListNode temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
tail = temp;
size--;
return true;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public int peek() {
return !isEmpty() ? tail.val : null;
}
}
}
| true
|
4d86040d3b94be0e116d56c379338fcf14f08887
|
Java
|
SkyC00P/study
|
/java/algorithm/src/done/RunningSum_of_1dArray.java
|
UTF-8
| 486
| 3.328125
| 3
|
[] |
no_license
|
package done;
public class RunningSum_of_1dArray {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Running Sum
* of 1d Array. Memory Usage: 40.4 MB, less than 30.44% of Java online
* submissions for Running Sum of 1d Array.
*/
public int[] runningSum(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum = nums[i] + sum;
nums[i] = sum;
}
return nums;
}
}
| true
|
3d707484804d59fe73b87027bce0b1277adf7ab9
|
Java
|
rootmelo92118/analysis
|
/sources/org/apache/http/p070b/C2586e.java
|
UTF-8
| 1,253
| 1.71875
| 2
|
[] |
no_license
|
package org.apache.http.p070b;
import java.io.Serializable;
import org.apache.http.C2598i;
import org.apache.http.C2600k;
import org.apache.http.p072d.C2591a;
import org.apache.http.p072d.C2593c;
/* renamed from: org.apache.http.b.e */
/* compiled from: BasicStatusLine */
public class C2586e implements Serializable, Cloneable, C2600k {
private static final long serialVersionUID = -2443303766890459269L;
/* renamed from: a */
private final C2598i f9135a;
/* renamed from: b */
private final int f9136b;
/* renamed from: c */
private final String f9137c;
public C2586e(C2598i iVar, int i, String str) {
this.f9135a = (C2598i) C2591a.m12012a(iVar, "Version");
this.f9136b = C2591a.m12011a(i, "Status code");
this.f9137c = str;
}
/* renamed from: b */
public int mo15822b() {
return this.f9136b;
}
/* renamed from: a */
public C2598i mo15821a() {
return this.f9135a;
}
/* renamed from: c */
public String mo15823c() {
return this.f9137c;
}
public String toString() {
return C2585d.f9134b.mo15818a((C2593c) null, (C2600k) this).toString();
}
public Object clone() {
return super.clone();
}
}
| true
|
0809ec93f51c834350e78458d883010b44ca800c
|
Java
|
morientes26/vittap
|
/src/main/java/com/vitta_pilates/core/studioadmin/mvvm/ClassTemplateViewModel.java
|
UTF-8
| 4,113
| 1.90625
| 2
|
[] |
no_license
|
package com.vitta_pilates.core.studioadmin.mvvm;
import com.vitta_pilates.core.shared.mvvm.BaseViewModel;
import com.vitta_pilates.core.studioadmin.service.ClassCategoryService;
import com.vitta_pilates.core.studioadmin.service.ClassTemplateService;
import com.vitta_pilates.model.dao.ClassCategory;
import com.vitta_pilates.model.dao.ClassTemplate;
import com.vitta_pilates.model.dao.Level;
import com.vitta_pilates.model.repository.LevelRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import java.util.List;
@VariableResolver(DelegatingVariableResolver.class)
public class ClassTemplateViewModel {
private final Logger log = LoggerFactory.getLogger(ClassTemplateViewModel.class);
private String keyword;
private List<ClassTemplate> classTemplateList;
private ClassTemplate selectedClassTemplate;
private List<ClassCategory> listClassCategory;
private ClassCategory selectedClassCategory;
private List<Level> listLevel;
private Level selectedLevel;
@WireVariable("classTemplateService")
private ClassTemplateService service;
@WireVariable("classCategoryService")
private ClassCategoryService serviceCategory;
@WireVariable("levelRepository")
private LevelRepository levelRepository;
@Command
@NotifyChange("classTemplateList")
public void search(){
classTemplateList = service.findByNameOrDescription(keyword);
}
@Command
@NotifyChange({"classTemplateList", "selectedClassTemplate"})
public void submit(){
new BaseViewModel<ClassTemplate>(service, selectedClassTemplate).submit();
}
@Command
@NotifyChange(".")
public void delete(){
new BaseViewModel<ClassTemplate>(service, selectedClassTemplate).delete();
}
@Command
@NotifyChange({"classTemplateList", "selectedClassTemplate"})
public void clear(){
init();
}
@Init
public void init(){
keyword = "";
classTemplateList = service.getAll();
listClassCategory = serviceCategory.getAll();
selectedClassTemplate = new ClassTemplate();
selectedClassCategory = new ClassCategory();
listLevel = levelRepository.findAll();
}
// public ClassTemplateViewModel(EntityService<ClassTemplate> service, Entity selectedClassTemplate){
// super(service, selectedClassTemplate);
// }
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public List<ClassTemplate> getClassTemplateList() {
return classTemplateList;
}
public void setClassTemplateList(List<ClassTemplate> classTemplateList) {
this.classTemplateList = classTemplateList;
}
public ClassTemplate getSelectedClassTemplate() {
return selectedClassTemplate;
}
public void setSelectedClassTemplate(ClassTemplate selectedClassTemplate) {
this.selectedClassTemplate = selectedClassTemplate;
}
public ClassTemplateService getService() {
return service;
}
public void setService(ClassTemplateService service) {
this.service = service;
}
public List<ClassCategory> getListClassCategory() {
return listClassCategory;
}
public void setListClassCategory(List<ClassCategory> listClassCategory) {
this.listClassCategory = listClassCategory;
}
public ClassCategory getSelectedClassCategory() {
return selectedClassCategory;
}
public void setSelectedClassCategory(ClassCategory selectedClassCategory) {
this.selectedClassCategory = selectedClassCategory;
}
public List<Level> getListLevel() {
return listLevel;
}
public void setListLevel(List<Level> listLevel) {
this.listLevel = listLevel;
}
public Level getSelectedLevel() {
return selectedLevel;
}
public void setSelectedLevel(Level selectedLevel) {
this.selectedLevel = selectedLevel;
}
}
| true
|
5a9fbb19185ae5fc6de3c089ab44c9248b4c4665
|
Java
|
andifalk/agile-testing
|
/amazon-shipping-calculator/src/main/java/info/novatec/amazon/shipping/calculator/entity/Address.java
|
UTF-8
| 964
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package info.novatec.amazon.shipping.calculator.entity;
public class Address {
private String street;
private String postofficebox;
private String zipCode;
private String city;
private Country county;
public Address() {
super();
}
public Address(String street, String postofficebox, String zipCode,
String city, Country county) {
super();
this.street = street;
this.postofficebox = postofficebox;
this.zipCode = zipCode;
this.city = city;
this.county = county;
}
/**
* @return the street
*/
public final String getStreet() {
return street;
}
/**
* @return the postofficebox
*/
public final String getPostofficebox() {
return postofficebox;
}
/**
* @return the zipCode
*/
public final String getZipCode() {
return zipCode;
}
/**
* @return the city
*/
public final String getCity() {
return city;
}
/**
* @return the county
*/
public final Country getCounty() {
return county;
}
}
| true
|
856bf69dcae96f2c20ca7929eb51e258133169a7
|
Java
|
Ellipse6814/NewPowerUp
|
/src/org/usfirst/frc/team6814/robot/Constants.java
|
UTF-8
| 2,938
| 2.140625
| 2
|
[] |
no_license
|
package org.usfirst.frc.team6814.robot;
import edu.wpi.first.wpilibj.CounterBase.EncodingType;
public class Constants {
// This is a class for global static constants for the robot.
// Elevator
public static final int kElevatorMotorPort = 4; // PWM
public static final double kElevatorKp = 0;
public static final double kElevatorKi = 0;
public static final double kElevatorKd = 0;
public static final double kElevatorMaxHeightByPID = 2.44;// meters
public static final double kElevatorPIDTolerance = 0.01;// meters
public static final int kElevatorEncoderReduceNoiseAverageSampleNum = 5;
public static final int kElevatorEncoderChannelA = 2;
public static final int kElevatorEncoderChannelB = 3;
public static final boolean kElevatorEncoderReversed = false;
public static final EncodingType kElevatorEncoderEncodingType = EncodingType.k4X;
public static final double kElevatorEncoderRegardStop = 0.2; // seconds
public static final double kElevatorGearboxRatio = 1 / 49; // output rotations with one motor rotation
public static final double kElevatorShaftDiameter = 0.02; // meters
public static final double kElevatorPulse2Distance = (kElevatorGearboxRatio) * (Math.PI * kElevatorShaftDiameter);
//
// Intake
public static final int kIntakeLeftMotorPort = 5;
public static final int kIntakeRightMotorPort = 6;
public static final double kIntakeLeftSpeed = 1;
public static final double kIntakeRightSpeed = 1;
//
// Drive
public static final int kDriveLeftFrontMotorPort = 0;
public static final int kDriveLeftBackMotorPort = 1;
public static final int kDriveRightFrontMotorPort = 2;
public static final int kDriveRightBackMotorPort = 3;
public static final int kDriveEncoderChannelA = 0;
public static final int kDriveEncoderChannelB = 1;
public static final int kDriveEncoderReduceNoiseAverageSampleNum = 5;
public static final boolean kDriveEncoderReversed = true;
public static final EncodingType kDriveEncoderEncodingType = EncodingType.k4X;
public static final double kDriveEncoderRegardStop = 1; // seconds
public static final double kDriveGearboxRatio = 1 / 1; // output rotations with one motor rotation
public static final double kDriveWheelDiameter = 0.15; // meters
public static final double kDriveRotation2Distance = (kDriveGearboxRatio) * (Math.PI * kDriveWheelDiameter);
public static final double kDrivePulse2Distance = kDriveRotation2Distance / 128;
public static final double kDriveStraightPIDkP = 1;
public static final double kDriveStraightPIDkI = 0;
public static final double kDriveStraightPIDkD = 0;
public static final double kDriveStraightTurnPIDkP = 0.12; //on cement
public static final double kDriveTurnPIDkP = 0.1;
public static final double kDriveTurnPIDkI = 0;
public static final double kDriveTurnPIDkD = 0.05;
// static PID constants:
// static acceleration, current limits
// static motor, sensor ports:
// static field parameters:
}
| true
|
210edb3a912b33f40fe89b5c5b4ee40653ceba33
|
Java
|
528854302/renren-generator
|
/provider/src/main/java/com/a528854302/gmall/provider/dao/WareSkuDao.java
|
UTF-8
| 914
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.a528854302.gmall.provider.dao;
import com.a528854302.gmall.provider.entity.WareSkuEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
* 商品库存
*
* @author 528854302
* @email 528854302@qq.com
* @date 2020-07-18 19:55:07
*/
@Mapper
public interface WareSkuDao extends BaseMapper<WareSkuEntity> {
@Update("UPDATE `wms_ware_sku` SET stock_locked=stock_locked+#{num} \n" +
"WHERE sku_id=#{skuId} AND stock>=stock_locked+#{num}")
Integer stockLock(@Param("skuId") Long skuId,@Param("num") Integer num);
@Update("UPDATE `wms_ware_sku` SET stock_locked=stock_locked-#{num} WHERE sku_id=#{skuId}")
Integer releaseStockLock(@Param("skuId") Long skuId,@Param("num") Integer num);
}
| true
|
153990c8f0b9d550a2de6e7e89002464b7ba0d7a
|
Java
|
EnochUlquiorra/HisSystemBaseOnSSH
|
/finalSSH2/src/hzcc/domain/Project.java
|
UTF-8
| 1,511
| 2.5
| 2
|
[] |
no_license
|
package hzcc.domain;
import java.io.Serializable;
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
private String projID;
private String projName;
private String depID;
private String unit;
private float price;
private String notes;
public String getProjID() {
return projID;
}
public void setProjID(String projID) {
this.projID = projID;
}
public String getProjName() {
return projName;
}
public void setProjName(String projName) {
this.projName = projName;
}
public String getDepID() {
return depID;
}
public void setDepID(String depID) {
this.depID = depID;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public String toString() {
return "Project{" +
"projID='" + projID + '\'' +
", projName='" + projName + '\'' +
", depID='" + depID + '\'' +
", unit='" + unit + '\'' +
", price=" + price +
", notes='" + notes + '\'' +
'}';
}
}
| true
|
6d49b2b3713a192ee8a69f1626a979dbc96c3a04
|
Java
|
HaoDrang/DataCrawler
|
/WordsComber/src/com/youdao/dic/comber/WordComberCreator.java
|
UTF-8
| 911
| 2.703125
| 3
|
[] |
no_license
|
package com.youdao.dic.comber;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class WordComberCreator {
public static IWordComber create(String dir) {
File wordFile = GetFileData(dir);
Document doc = ParseData(wordFile);
return new YouDaoWordComber_v6_3(doc);
}
private static Document ParseData(File wordFile) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(wordFile);
return doc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static File GetFileData(String dir) {
File f = new File(dir);
if(f.exists())
{
return f;
}
System.out.println("File Read Failed...\n DIR: " + dir);
return null;
}
}
| true
|
a513c98c143fd8341dde8419cf7c59c61457456a
|
Java
|
benjaminSe1/hearthStone
|
/src/hero/factory/MageFactory.java
|
UTF-8
| 304
| 2.6875
| 3
|
[] |
no_license
|
package hero.factory;
import hero.Hero;
import hero.Mage;
public class MageFactory implements HeroFactory {
/**
* Méthode permettant de créer un Hero mage
* @return - le nouveau Hero Mage
*/
@Override
public Hero createHero() {
return new Mage(30, 0, 0);
}
}
| true
|
e4a8515199d1d93e3fe8c3b7a22c7cca9c172457
|
Java
|
applewjg/cpp
|
/array/maxSubArray.java
|
UTF-8
| 526
| 3
| 3
|
[] |
no_license
|
public class maxSubArray {
public static int getMax(int[] a) {
int max, max_including_current;
max = max_including_current = Integer.MIN_VALUE;
for (int i=0; i<a.length; i++) {
max_including_current = (max_including_current>0)? max_including_current + a[i] : a[i];
max = Math.max(max, max_including_current);
}
return max;
}
public static void main(String[] args) {
int a[] = {2,-6,7,-3,9,4};
System.out.println(getMax(a));
}
}
| true
|
80e5c54119d651f377a235240c4e8b3367eb3183
|
Java
|
iotum/cordova-plugin-cookie-manager
|
/src/android/CookieManagementPlugin.java
|
UTF-8
| 1,505
| 2.40625
| 2
|
[
"MIT"
] |
permissive
|
package plugin.cookiemanagement;
import android.os.Build.VERSION;
import android.webkit.CookieManager;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
/**
* This class makes sure cookies are moved to persistent memory.
*/
public class CookieManagementPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("flush".equals(action)) {
this.flush(callbackContext);
return true;
} else if ("remove".equals(action)) {
/**
* args[]
* args[0] - domain
* args[1] - cookieName
*/
this.remove(args.getString(0), args.getString(1), callbackContext);
return true;
}
return false;
}
private void flush(CallbackContext callbackContext) {
if (VERSION.SDK_INT >= 21) {
CookieManager.getInstance().flush();
}
callbackContext.success();
}
private void remove(String domain, String cookieName, CallbackContext callbackContext) {
if (domain == null || cookieName == null) {
callbackContext.error("domain or cookie name is missing");
return;
}
CookieManager.getInstance().setCookie(domain, String.format("%s=''", cookieName));
callbackContext.success();
}
}
| true
|
ea44babd29fee3f572d58599e50c4a833e192290
|
Java
|
S62Groep4/RegistratieSysteem
|
/src/main/java/rest/StolenVehicleResource.java
|
UTF-8
| 676
| 2.359375
| 2
|
[] |
no_license
|
package rest;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import service.VehicleService;
@Stateless
@Path("/stolen")
@Consumes(MediaType.APPLICATION_JSON)
public class StolenVehicleResource {
@Inject
VehicleService vehicleService;
@Path("/{carTrackerSerial}")
public Response markAsMonitored(@PathParam("carTrackerSerial") String carTrackerSerial){
vehicleService.markVehicleMonitored(carTrackerSerial);
return Response.ok().build();
}
}
| true
|
3b8141cc73dbd417abbb9319f698d4d5140e78ec
|
Java
|
junzkn/GTD-APP
|
/app/src/main/java/com/jun/gtd/net/Net.java
|
UTF-8
| 4,895
| 2.109375
| 2
|
[] |
no_license
|
package com.jun.gtd.net;
import android.text.TextUtils;
import com.jun.gtd.bean.ResponseDataBean;
import com.jun.gtd.bean.TodoBean;
import com.jun.gtd.bean.UserBean;
import com.jun.gtd.utils.PreUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Net {
public static final String BASE_URL = "http://jun:8080" ;
public static final int TIME_OUT_CONNECT = 200 ;
public static final int TIME_OUT_READ = 200 ;
public static final String COOKIE_NAME = "Cookie";
public static final String SAVE_USER_LOGIN_KEY = "user/login";
public static final String SET_COOKIE_KEY = "set-cookie";
public static final int NO_LOGIN = -1001;
private static Net mInstance;
private API api;
final Interceptor requestInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
String cookie = PreUtils.getString(Net.SAVE_USER_LOGIN_KEY);
if (!TextUtils.isEmpty(cookie)) {
builder.addHeader(Net.COOKIE_NAME, cookie);
}
return chain.proceed(builder.build());
}
};
final Interceptor responseInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
final String requestUrl = request.url().toString();
if(requestUrl.contains("user")){
PreUtils.set(Net.SAVE_USER_LOGIN_KEY, encodeCookie(response.headers(Net.SET_COOKIE_KEY)));
}
return response;
}
};
private Net() {
final OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY))
.addInterceptor(requestInterceptor)
.addInterceptor(responseInterceptor)
.connectTimeout(Net.TIME_OUT_CONNECT, TimeUnit.SECONDS)
.readTimeout(Net.TIME_OUT_READ, TimeUnit.SECONDS)
.build();
api = new Retrofit.Builder()
.baseUrl(Net.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build()
.create(API.class);
}
public static Net getInstance() {
if (mInstance == null) {
synchronized (Net.class) {
mInstance = new Net();
}
}
return mInstance;
}
public void postLogin(String username, String password, Callback<ResponseDataBean<UserBean>> callback) {
api.postLogin(username, password).enqueue(callback);
}
public void postLogout(Callback<ResponseDataBean> callback){
api.postLogout().enqueue(callback);
}
public void postRegister(String username, String password,String repassword,
Callback<ResponseDataBean<UserBean>> callback) {
api.postRegister(username, password,repassword).enqueue(callback);
}
public void postAddTodo ( TodoBean todo ,Callback<ResponseDataBean<TodoBean>> callback){
api.postAddTodo(todo).enqueue(callback);
}
public void getGetTodo (int symbol , int flag , Callback<ResponseDataBean<List<TodoBean>>> callback){
api.getGetTodo(symbol,flag).enqueue(callback);
}
public void postDeleteTodo(int id,Callback<ResponseDataBean> callback){
api.postDeleteTodo(id).enqueue(callback);
}
public void postUpdateTodo(TodoBean todo , Callback<ResponseDataBean<TodoBean>> callback){
api.postUpdateTodo(todo).enqueue(callback);
}
public void postUpdateTodoStatus(int id , int status,Callback<ResponseDataBean<TodoBean>> callback){
api.postUpdateTodoStatus(id,status).enqueue(callback);
}
public static String encodeCookie(List<String> cookies) {
final StringBuilder sb = new StringBuilder();
final Set<String> set = new HashSet<>();
for (String cookie : cookies) {
set.addAll(Arrays.asList(cookie.split(";")));
}
for (String s : set) {
sb.append(s).append(";");
}
if (sb.length() > 0)
sb.delete(sb.length() - 1, sb.length());
return sb.toString().trim();
}
}
| true
|
7624c01ef275845517694d46f194f0794e775612
|
Java
|
aliyun/aliyun-openapi-java-sdk
|
/aliyun-java-sdk-couponnew/src/main/java/com/aliyuncs/couponnew/model/v20190401/GetHasCouponUidListRequest.java
|
UTF-8
| 1,775
| 1.734375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.aliyuncs.couponnew.model.v20190401;
import com.aliyuncs.RpcAcsRequest;
/**
* @author auto create
* @version
*/
public class GetHasCouponUidListRequest extends RpcAcsRequest<GetHasCouponUidListResponse> {
public GetHasCouponUidListRequest() {
super("CouponNew", "2019-04-01", "GetHasCouponUidList");
}
private String fromApp;
private String param;
private String idempotentToken;
public String getFromApp() {
return this.fromApp;
}
public void setFromApp(String fromApp) {
this.fromApp = fromApp;
if(fromApp != null){
putQueryParameter("FromApp", fromApp);
}
}
public String getParam() {
return this.param;
}
public void setParam(String param) {
this.param = param;
if(param != null){
putQueryParameter("Param", param);
}
}
public String getIdempotentToken() {
return this.idempotentToken;
}
public void setIdempotentToken(String idempotentToken) {
this.idempotentToken = idempotentToken;
if(idempotentToken != null){
putQueryParameter("IdempotentToken", idempotentToken);
}
}
@Override
public Class<GetHasCouponUidListResponse> getResponseClass() {
return GetHasCouponUidListResponse.class;
}
}
| true
|
b108e356839e42bca5792ca86908d293b8283938
|
Java
|
huangchunyan1/web1
|
/src/com/tairun/bean/Order.java
|
UTF-8
| 1,122
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tairun.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="o_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int o_id;
@OneToOne
@JoinColumn(name="product_id")
private Product product;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
private Date o_createTime;
public int getO_id() {
return o_id;
}
public void setO_id(int o_id) {
this.o_id = o_id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getO_createTime() {
return o_createTime;
}
public void setO_createTime(Date o_createTime) {
this.o_createTime = o_createTime;
}
}
| true
|
9d932e0160c04f7faa431c54b09203c853ed3399
|
Java
|
mmedbenmansour/tnb
|
/src/bean/TauxTaxe.java
|
UTF-8
| 2,972
| 2.15625
| 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 bean;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
/**
*
* @author simob
*/
@Entity
public class TauxTaxe implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateApplication;
private double tauxTaxe;
@OneToOne
private CategorieTerrain categorieTerrain;
@OneToMany(mappedBy = "tauxTaxe")
private List<TaxeAnnuelle> taxeAnnuelles;
public TauxTaxe() {
}
public TauxTaxe(Long id) {
this.id = id;
}
public TauxTaxe(double tauxTaxe, int categorieHabitation) {
this.tauxTaxe = tauxTaxe;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public double getTauxTaxe() {
return tauxTaxe;
}
public void setTauxTaxe(double tauxTaxe) {
//if(tauxTaxe>0 && tauxTaxe<1)
this.tauxTaxe = tauxTaxe;
}
public CategorieTerrain getCategorieTerrain() {
if(categorieTerrain==null){
CategorieTerrain categorieTerrain=new CategorieTerrain();
}
return categorieTerrain;
}
public void setCategorieTerrain(CategorieTerrain categorieTerrain) {
this.categorieTerrain = categorieTerrain;
}
public Date getDateApplication() {
return dateApplication;
}
public void setDateApplication(Date dateApplication) {
this.dateApplication = dateApplication;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TauxTaxe other = (TauxTaxe) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return "TauxTaxe{" + "id=" + id + ", tauxTaxe=" + tauxTaxe + '}';
}
}
| true
|
4b0024ebe994d37f7c61627f2bd5bcd3ebd388ee
|
Java
|
JakubNajman/ParkManager
|
/src/main/java/bdbt_park_rozrywki/Data.java
|
UTF-8
| 2,414
| 1.953125
| 2
|
[] |
no_license
|
package bdbt_park_rozrywki;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.LogFactory;
import org.hibernate.mapping.Collection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import oracle.jdbc.logging.annotations.Log;
@Configuration
@EnableWebSecurity
public class Data extends WebSecurityConfigurerAdapter{
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("user")
.password("user")
.roles("USER")
.and()
.withUser("admin")
.password("admin")
.roles("ADMIN");
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new MySimpleUrlAuthenticationSuccessHandler();
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests()
.antMatchers("/user").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/").permitAll()
.and().formLogin()
.loginPage("/login").permitAll()
.successHandler(myAuthenticationSuccessHandler())
.and()
.logout().permitAll();;
}
}
| true
|
d19c326b78c25e0dc989e531f88dff04ac3058e5
|
Java
|
bellmit/lol-java
|
/src/main/java/wsg/lol/common/base/AppException.java
|
UTF-8
| 1,556
| 2.703125
| 3
|
[] |
no_license
|
package wsg.lol.common.base;
import org.slf4j.Logger;
/**
* Specified {@link RuntimeException} for the application.
*
* @author Kingen
*/
public class AppException extends RuntimeException {
/**
* @see wsg.lol.common.constant.ErrorCodeConst
*/
private String errorCode;
/**
* Arguments for the error message.
*/
private String[] args;
public AppException(String errorCode) {
super(errorCode);
this.errorCode = errorCode;
}
public AppException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public AppException(String errorCode, String message, String[] args) {
super(message);
this.errorCode = errorCode;
this.args = args;
}
public AppException(String errorCode, String[] args) {
this.errorCode = errorCode;
this.args = args;
}
public AppException(String errorCode, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
}
public AppException(String errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
public String[] getArgs() {
return args;
}
/**
* {@inheritDoc}
*/
public Throwable fillInStackTrace() {
return this;
}
public AppException error(Logger logger) {
logger.error(this.getMessage());
return this;
}
}
| true
|
a5c757688a3a894a3dbb5f7bfeb85b44cc10b7fe
|
Java
|
srishti77/Learn
|
/src/DS/MatrixSpiral.java
|
UTF-8
| 2,135
| 3.78125
| 4
|
[] |
no_license
|
package DS;
public class MatrixSpiral {
public static void main(String[] args) {
int matrix[][] = { { 1 }};
//MatrixSpiral spiral = new MatrixSpiral();
int[] array = spiralCopy(matrix);
}
public static int[] spiralCopy(int[][] inputMatrix) {
// your code goes here
int row = inputMatrix.length, col = inputMatrix[0].length, k = 0, index = 0;
int array[];
if (row == 0) {
return new int[1];// 0
}
if (row == 1) {
array = new int[col];
for (int i = 0; i < col; i++) {
array[index] = inputMatrix[0][i];
System.out.print(inputMatrix[k][i]+" ");
index++;
}
return array;
}
if (col == 1) {
array = new int[row];
for (int i = 0; i < row; i++) {
array[index] = inputMatrix[i][0];
System.out.print(inputMatrix[k][i]+" ");
index++;
}
return array;
}
array = new int[row * col];
for (k = 0; k < row / 2; k++) {
/*
* // K =0 : 1, 2, 3 ,4 5 1... n-1// k = 1 : 7, 8,9.. 2... n-2
*/
for (int i = k; i < col - k; i++) {
System.out.print(inputMatrix[k][i]+" ");
array[index] = inputMatrix[k][i];
index++;
}
/*
* // k=0: matrix[j][m-k] .. 10,15,20 //2 .. 4-1.. 3 // k = 1; matrix[2][2] ..
* 14 top-bot (row) = m
*
*/
for (int j = k + 1; j < row - k; j++) {
System.out.print(inputMatrix[j][col - k - 1]+" ");
array[index] = inputMatrix[j][col - k - 1]; // 1,
index++;
}
/*
* bot right- left // n= col(5) m = 4 //k =0; matrix[m-1-k][p] =
*/
for (int p = col - k - 2; p >= k; p--) {
System.out.print(inputMatrix[row - k - 1][p]+" ");
/*[1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]
1 2 3 4 5 10 15 20 19 18 17 16 116 7 8 9 14 13 12*/
array[index] = inputMatrix[row - k - 1][p]; // 19, 18--..
index++;
}
/*
* bot to top
*
* // k = 0; matrix[q][k] //k = 1; matrix[2][1] = 12
*/
for (int q = row - k - 2; q > k; q--) {
System.out.print(inputMatrix[q][k]);
array[index] = inputMatrix[q][k]; // 16., 11, 6
index++;
}
System.out.println();
}
return array;
}
}
| true
|
9eea099967f89ea1fc5523b24537aa313cbde51e
|
Java
|
sravani2044/playforgood
|
/src/com/playforgood/ui/NewAppsFragment.java
|
UTF-8
| 2,892
| 2.03125
| 2
|
[] |
no_license
|
package com.playforgood.ui;
import java.util.ArrayList;
import java.util.List;
import com.example.good2play.R;
import com.playforgood.db.AppStatsDataSource;
import com.playforgood.stats.AppStats;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
public class NewAppsFragment extends Fragment {
GridView gridView;
ArrayList<Item> gridArray = new ArrayList<Item>();
CustomGridViewAdapter customGridAdapter;
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_monitored_apps, container, false);
//set grid view item
int flags = PackageManager.GET_META_DATA |
PackageManager.GET_SHARED_LIBRARY_FILES |
PackageManager.GET_UNINSTALLED_PACKAGES;
PackageManager pm = getActivity().getPackageManager();
AppStatsDataSource datasource = ((AppStatsApp)getActivity().getApplication()).getDataSource();
ArrayList<String> existingApps = new ArrayList<String>();
if (datasource != null) {
List<AppStats> stats = datasource.getAllAppStatss();
for (AppStats a : stats) {
existingApps.add(a.getappName());
}
}
List<ApplicationInfo> applications = pm.getInstalledApplications(flags);
for (ApplicationInfo appInfo : applications) {
if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
// System application
}
else if (!existingApps.contains(appInfo.packageName)) {
// Installed by user
Drawable icon = pm.getApplicationIcon(appInfo);
Bitmap hcon = ((BitmapDrawable)icon).getBitmap();
gridArray.add(new Item(hcon, pm.getApplicationLabel(appInfo).toString(), appInfo.packageName));
}
}
gridView = (GridView) view.findViewById(R.id.gridView1);
customGridAdapter = new CustomGridViewAdapter(inflater.getContext(), R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Item item = gridArray.get(position);
Fragment df = new DefaultSettingsFragment(item);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.container, df).commit();
}
});
return view;
}
}
| true
|
6dce402996e0c9d9470cbcfe203ba0cf91a921c8
|
Java
|
kidd808/smART
|
/app/src/main/java/micc/beaconav/indoorEngine/databaseLite/BuildingSqliteHelper.java
|
UTF-8
| 2,704
| 2.328125
| 2
|
[] |
no_license
|
package micc.beaconav.indoorEngine.databaseLite;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by nagash on 15/03/15.
*/
public class BuildingSqliteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
//private static String DB_NAME = "building";
private String DIR_PATH = ""; // = "/data/data/{package_name}/databases/";
private static String FILE_NAME = "dblite.db";
// private static String TEMP_DIR_PATH = Environment.getExternalStorageDirectory().getPath() + "/beaconav/";
private SQLiteDatabase mDataBase;
private final Context mContext;
public BuildingSqliteHelper(Context context)
{
super(context, FILE_NAME, null, DATABASE_VERSION);
this.mContext = context;
if(android.os.Build.VERSION.SDK_INT >= 17)
DIR_PATH = mContext.getApplicationInfo().dataDir + "/databases/";
else
DIR_PATH = "/data/data/" + mContext.getPackageName() + "/databases";
}
/**
* Copies the database file at the specified location over the current
* internal application database.
* */
public boolean importDatabase(String dbPath) throws IOException {
// Close the SQLiteOpenHelper so it will commit the created empty
close();
File directory = new File(DIR_PATH);
directory.mkdirs();
File newDb = new File(DIR_PATH + FILE_NAME);
File importDb = new File(dbPath);
if (importDb.exists()) {
FileUtils.copyFile(new FileInputStream(importDb), new FileOutputStream(newDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
getWritableDatabase().close();
return true;
}
return false;
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DIR_PATH + FILE_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
@Override
public void onCreate(SQLiteDatabase db) {
return; // questo software fa da client non scrive niente sul db dell'edificio
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
return; // questo software fa da client non scrive niente sul db dell'edificio
}
}
| true
|
5f19833b3d008024147e2800679ca53fe10ad58e
|
Java
|
ravis-git/sat-corelationid-experiment
|
/predix-aggregate-service/src/main/java/com/example/predixaggregateservice/service/TerminalAggregateService.java
|
UTF-8
| 249
| 1.796875
| 2
|
[] |
no_license
|
package com.example.predixaggregateservice.service;
import com.example.predixaggregateservice.model.Terminal;
/**
* Created by ravipalakodeti on 7/31/17.
*/
public interface TerminalAggregateService {
public Terminal getTerminalDetails();
}
| true
|
d1a5f9106f63aef9b17c436cd26299b92d788e99
|
Java
|
tuananh0333/Device-Management
|
/src/main/java/letuananh/device_management/model/Model.java
|
UTF-8
| 296
| 1.921875
| 2
|
[] |
no_license
|
package letuananh.device_management.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Model {
private String modelId;
private String modelName;
private String categoryId;
}
| true
|
58fe964461cb993fa8db9bc3318110560e0b9db5
|
Java
|
bracksnow/My-study
|
/자바 자료구조(백준)/select_sort.java
|
UTF-8
| 910
| 3.5625
| 4
|
[] |
no_license
|
package DataStructure;
import java.util.Scanner;
public class select_sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
int[] number = new int[count];
for(int i = 0;i<count;i++){
number[i] = sc.nextInt();
}
select(number);
for(int SortedNumber:number){
System.out.println(SortedNumber);
}
}
public static void select(int number[]) {
int indexMin, temp;
for (int i = 0; i < number.length - 1; i++) {
indexMin = i;
for (int j = i + 1; j < number.length; j++) {
if (number[j] < number[indexMin]) {
indexMin = j;
}
}
temp = number[indexMin];
number[indexMin] = number[i];
number[i] = temp;
}
}
}
| true
|
11608f2a2bb3e5348337c17d41be5872d9dca677
|
Java
|
elysium986/GitPet
|
/src/main/java/model/Operator.java
|
UTF-8
| 3,183
| 2.453125
| 2
|
[] |
no_license
|
package model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.*;
/**
* Created by Alexander Khodakovskyi on 21/07/14.
*/
@Entity
@Table(name = "OPERATOR")
@SequenceGenerator(name = "SEQ_OPERATOR", sequenceName = "SEQ_OPERATOR")
public class Operator implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_OPERATOR")
private Long id;
@Column(name = "OPERATOR_NAME", unique = true, nullable = false)
private String operatorName;
@Column(name = "OPERATOR_CODE", unique = true, nullable = false)
private String operatorCode;
@ManyToOne
@JoinColumn(name = "FK_COUNTRY")
private Country country;
@Column(name = "START_DATE")
private Date startDate;
@Column(name = "END_DATE")
private Date endDate;
@Column(name = "UPDATED")
private Date updated;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "OPERATOR_PRODUCT",
joinColumns = @JoinColumn(name = "FK_OPERATOR"),
inverseJoinColumns = @JoinColumn(name = "FK_PRODUCT"))
private Set<Product> products = new HashSet<Product>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
public String getOperatorCode() {
return operatorCode;
}
public void setOperatorCode(String operatorCode) {
this.operatorCode = operatorCode;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Operator other = (Operator) obj;
return !(operatorName == null ? other.getOperatorName() != null : !operatorName.equals(other.operatorName));
}
}
| true
|
591bdd267ee7bc872422edf7d0738cc439c28d60
|
Java
|
Harshal-Git/Sort
|
/src/main/java/com/countInversionsInArray/EfficientApproach.java
|
UTF-8
| 3,882
| 3.703125
| 4
|
[] |
no_license
|
/**
*
*/
package com.countInversionsInArray;
import java.util.Arrays;
/**
* @author Harshal-Git
*
* -> Count number of inversions in a given array. Inversion is considered if a pair from given array, (a[i], a[j]) is formed such
* that i < j AND a[i] > a[j].
*
* -> efficient approach : merge sort based algo to count inversions
*
* -> ex:
* i/p: {2, 4, 1, 3, 5} => o/p: 3 [(4, 1), (4, 3), (2, 1)]
*
* i/p: {10, 20, 30, 40} => o/p: 0 [no such inversion pairs can be made with an ascending sorted array]
*
* i/p: {40, 30, 20, 10} => o/p: 6 [(40, 30), (40, 20), (40, 10), (30, 20), (30, 10), (20, 10)]
*
* -> Time complexity: O(n * log n)
* -> Space complexity: O(n)
* -> Auxiliary space: O(n)
*/
public class EfficientApproach {
/**
* @param args
*/
public static void main(String[] args) {
int [] data1 = {2, 4, 1, 3, 5};
System.out.println("Array: "+Arrays.toString(data1)+": inversions => "+getInversions(data1));
int [] data2 = {10, 20, 30, 40};
System.out.println("\nArray: "+Arrays.toString(data2)+": inversions => "+getInversions(data2));
int [] data3 = {40, 30, 20, 10};
System.out.println("\nArray: "+Arrays.toString(data3)+": inversions => "+getInversions(data3));
int [] data4 = {2, 5, 8, 11, 3, 6, 9, 13};
System.out.println("\nArray: "+Arrays.toString(data4)+": inversions => "+getInversions(data4));
}
/**
* @param data
* @return
*/
private static int getInversions(int[] data) {
return countInversions(data, 0, (data.length-1));
}
/**
* @param data
* @param start
* @param end
* @return
*/
private static int countInversions(int[] data, int start, int end) {
int inversionCount = 0;
if(start < end) {
int mid = (start+((end-start)/2));
inversionCount+= countInversions(data, start, mid);
inversionCount+= countInversions(data, (mid+1), end);
inversionCount+= countInversionsAndMerge(data, start, mid, end);
}
return inversionCount;
}
/**
* @param data
* @param start
* @param mid
* @param end
* @return
*/
private static int countInversionsAndMerge(int[] data, int start, int mid, int end) {
// sub arrays initializations
int leftSize = ((mid-start)+1);
int rightSize = (end-mid);
int indexArr = 0;
// prepare left array
int [] leftArr = new int[leftSize];
for(int index = start; index <= mid; index++) {
leftArr[indexArr] = data[index];
indexArr++;
}
// prepare right array
int [] rightArr = new int[rightSize];
indexArr = 0;
for(int index = (mid+1); index <= end; index++) {
rightArr[indexArr] = data[index];
indexArr++;
}
// merge both arrays in sorted manner and count inversions
int inversionCount = 0;
int leftIndex = 0, rightIndex = 0;
indexArr = start;
while(indexArr <= end) {
// if arrays stays within the limit : compare & insert into the main array
if((leftIndex < leftSize) && (rightIndex < rightSize)) {
if(leftArr[leftIndex] <= rightArr[rightIndex]) {
// if left array element is smaller
data[indexArr] = leftArr[leftIndex];
leftIndex++;
} else {
// if right array element is smaller
data[indexArr] = rightArr[rightIndex];
rightIndex++;
/*
* Inversion calculation
* if any element we find in left array is greater than right array;
* that means the element & all further elements in the left array
* are higher and will form inversion pairs with the same right array.
* Hence we can directly calculate multiple inversion pairs with this formula.
*/
inversionCount+= (leftSize-leftIndex);
}
} else if(leftIndex < leftSize){
// if right array is exhausted
data[indexArr] = leftArr[leftIndex];
leftIndex++;
} else {
// if left array is exhausted
data[indexArr] = rightArr[rightIndex];
rightIndex++;
}
indexArr++;
}
return inversionCount;
}
}
| true
|
96e21c5938fee9ac005fbb4d812a801a5ec8ff39
|
Java
|
Abdullahr29/arservertestpro
|
/src/main/java/Patient.java
|
UTF-8
| 422
| 3.0625
| 3
|
[] |
no_license
|
import java.io.Serializable;
public class Patient implements Serializable {
String name;
int id;
String phoneNumber;
public Patient(String name,int id, String phone){
this.name = name;
this.id = id;
phoneNumber = phone;
}
public String toPrint(){
String output = "Patient " + name + ", id: " + id + ", phone number: " + phoneNumber;
return output;
}
}
| true
|
25bc6fff12e2c5d48b9dea9c7fd84bc83f2b8f86
|
Java
|
HazelChen/treasuryArbitrage-service
|
/src/com/bwq/treasuryArbitrage/modelsCalculation/SimpleArbitrage.java
|
UTF-8
| 478
| 2.84375
| 3
|
[] |
no_license
|
package com.bwq.treasuryArbitrage.modelsCalculation;
import java.util.Date;
public class SimpleArbitrage {
private double price;
private Date date;
public SimpleArbitrage(double price, Date date) {
this.price = price;
this.date = date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public double getPrice() {
return price;
}
public double setPrice(double price) {
return this.price = price;
}
}
| true
|
8464bafa89c31bd5946e995af1414c3876fa0a8f
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/25/25_378227eb6a9ab727cba607ef03ea184f43135075/MoneyController/25_378227eb6a9ab727cba607ef03ea184f43135075_MoneyController_s.java
|
UTF-8
| 6,044
| 1.960938
| 2
|
[] |
no_license
|
package com.gemantic.killer.controller;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gemantic.common.util.MyListUtil;
import com.gemantic.common.util.http.cookie.CookieUtil;
import com.gemantic.killer.model.User;
import com.gemantic.labs.killer.model.MoneyFlow;
import com.gemantic.labs.killer.service.MoneyFlowService;
import com.gemantic.labs.killer.service.UsersService;
/**
* 提供游戏房间的创建,删除,玩家列表等功能
*
* @author xdyl
*
*/
@Controller
public class MoneyController {
private static final Log log = LogFactory.getLog(MoneyController.class);
@Autowired
private UsersService userSevice;
@Autowired
private MoneyFlowService moneyFlowService;
@Autowired
private CookieUtil cookieUtil;
/**
* 游戏准备
*
* @param request
* @param response
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/money/flow")
public String list(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer page, Integer size, Long uid, String type) throws Exception {
if (uid == null) {
uid = cookieUtil.getID(request, response);
if(uid==null){
return "redirect/";
}
}
if ("out".equals(type)) {
} else {
type = "in";
}
log.info(uid + " start get money list " + type);
if (page == null) {
page = 1;
}
if (page < 1) {
page = 1;
}
if (size == null) {
size = 21;
}
Integer start = (page - 1) * size;
List<Long> userIDS = new ArrayList();
List<User> users = new ArrayList();
List<Long> ids = new ArrayList();
if ("in".equals(type)) {
ids = this.moneyFlowService.getMoneyFlowIdsByUid(uid, start, size);
} else {
ids = this.moneyFlowService.getMoneyFlowIdsByFid(uid, start, size);
}
List<MoneyFlow> mfs = this.moneyFlowService.getObjectsByIds(ids);
Set<Long> uids = new HashSet();
uids.add(uid);
for (MoneyFlow mf : mfs) {
uids.add(mf.getFid());
uids.add(mf.getUid());
}
users = this.userSevice.getObjectsByIds(new ArrayList(uids));
Map<Long, User> ids_user = MyListUtil.convert2Map(User.class.getDeclaredField("id"), users);
//log.info("money all " + ids_user);
users = this.userSevice.getObjectsByIds(userIDS);
model.addAttribute("uid", uid);
model.addAttribute("current", ids_user.get(uid));
model.addAttribute("mfs", mfs);
model.addAttribute("id_users", ids_user);
model.addAttribute("type", type);
model.addAttribute("page", page);
model.addAttribute("size", size);
return "/room/financial/moneyFlow";
}
/**
* 游戏准备
*
* @param request
* @param response
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/money/trade", method = RequestMethod.POST)
public String trade(HttpServletRequest request, HttpServletResponse response, ModelMap model, MoneyFlow mf) throws Exception {
log.info("start trade "+mf);
Long currentID = cookieUtil.getID(request, response);
if (mf==null||currentID == null||mf.getUid()==null) {
log.warn(mf+" not exist or not login ");
model.addAttribute("code", -9001);
return "/message/accept/show";
}
mf.setFid(currentID);
User fuser=this.userSevice.getObjectById(currentID);
if(fuser==null){
log.warn(currentID+"not exist ");
model.addAttribute("code", -9001);
return "/room/person/trade";
}
if(mf.getMoney()<=0){
log.warn(mf+" incorrect money ");
model.addAttribute("code", -9004);
return "/room/person/trade";
}
if(fuser.getMoney()<mf.getMoney()){
log.warn(fuser+" no money "+mf);
model.addAttribute("code", -9002);
return "/room/person/trade";
}
User tuser=this.userSevice.getObjectById(mf.getUid());
if(tuser==null){
log.warn(mf.getId()+" to use not exist ");
model.addAttribute("code", -9003);
return "/room/person/trade";
}
mf.setHappenAt(System.currentTimeMillis());
//s@163.com sogou@163.com qq
if(currentID.equals(284L)||currentID.equals(256L)||currentID.equals(245L)){
log.info("admin give money ~ "+mf);
}else{
fuser.setMoney(fuser.getMoney()-mf.getMoney());
}
Integer tax=mf.getMoney()/20;
log.info("tax is "+tax);
tuser.setMoney(tuser.getMoney()+mf.getMoney()-tax);
List<User> users=new ArrayList();
users.add(fuser);
users.add(tuser);
this.userSevice.updateList(users);
this.moneyFlowService.insert(mf);
model.addAttribute("code", 0);
model.addAttribute("money", fuser.getMoney());
return "/room/person/trade";
}
@RequestMapping(value = "/money/trade")
public String getTrade(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
Long uid = cookieUtil.getID(request, response);
if(uid==null){
return "redirect:/";
}
User user=this.userSevice.getObjectById(uid);
model.addAttribute("current", user);
return "/room/financial/trade";
}
}
| true
|
c49eadcd1ff63733d32fbbc980e3c82aea804c0d
|
Java
|
bronto/bronto-api-java-sdk
|
/client/src/main/java/com/bronto/api/model/DeliveryGroupFilter.java
|
UTF-8
| 6,784
| 1.96875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.bronto.api.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for deliveryGroupFilter complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="deliveryGroupFilter">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="deliveryGroupId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="listByType" type="{http://api.bronto.com/v4}memberType" minOccurs="0"/>
* <element name="automatorId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="messageGroupId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="deliveryId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="name" type="{http://api.bronto.com/v4}stringValue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "deliveryGroupFilter", propOrder = {
"deliveryGroupId",
"listByType",
"automatorId",
"messageGroupId",
"deliveryId",
"name"
})
public class DeliveryGroupFilter {
@XmlElement(nillable = true)
protected List<String> deliveryGroupId;
@XmlSchemaType(name = "string")
protected MemberType listByType;
@XmlElement(nillable = true)
protected List<String> automatorId;
@XmlElement(nillable = true)
protected List<String> messageGroupId;
@XmlElement(nillable = true)
protected List<String> deliveryId;
@XmlElement(nillable = true)
protected List<StringValue> name;
/**
* Gets the value of the deliveryGroupId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the deliveryGroupId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeliveryGroupId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDeliveryGroupId() {
if (deliveryGroupId == null) {
deliveryGroupId = new ArrayList<String>();
}
return this.deliveryGroupId;
}
/**
* Gets the value of the listByType property.
*
* @return
* possible object is
* {@link MemberType }
*
*/
public MemberType getListByType() {
return listByType;
}
/**
* Sets the value of the listByType property.
*
* @param value
* allowed object is
* {@link MemberType }
*
*/
public void setListByType(MemberType value) {
this.listByType = value;
}
/**
* Gets the value of the automatorId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the automatorId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAutomatorId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAutomatorId() {
if (automatorId == null) {
automatorId = new ArrayList<String>();
}
return this.automatorId;
}
/**
* Gets the value of the messageGroupId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageGroupId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageGroupId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getMessageGroupId() {
if (messageGroupId == null) {
messageGroupId = new ArrayList<String>();
}
return this.messageGroupId;
}
/**
* Gets the value of the deliveryId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the deliveryId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeliveryId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getDeliveryId() {
if (deliveryId == null) {
deliveryId = new ArrayList<String>();
}
return this.deliveryId;
}
/**
* Gets the value of the name property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the name property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getName().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StringValue }
*
*
*/
public List<StringValue> getName() {
if (name == null) {
name = new ArrayList<StringValue>();
}
return this.name;
}
}
| true
|
d693e144dd9f0a01935319d8a71c5f889cc8a7f0
|
Java
|
mmemon21/FitnessApp
|
/app/src/main/java/com/example/fitnessproject3fall/ViewProfileActivity.java
|
UTF-8
| 8,103
| 1.890625
| 2
|
[] |
no_license
|
package com.example.fitnessproject3fall;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.fitnessproject3fall.model.Coach;
import com.example.fitnessproject3fall.model.FitnessDAO;
import com.example.fitnessproject3fall.model.FitnessDB;
import com.example.fitnessproject3fall.model.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ViewProfileActivity extends AppCompatActivity {
private ImageView profilePic;
public Uri imageUri;
private FirebaseStorage storage;
private StorageReference storageReference;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference databaseReference = firebaseDatabase.getReference();
private DatabaseReference first = databaseReference.child("raul");
private boolean status;
FitnessDAO dao = FitnessDB.getFitnessDB(this).dao();
User user = dao.searchUser(LoginActivity.USER_ID);
Coach coach = dao.searchCoach(LoginActivity.GROUP_ID);
List<Coach> list_coach = dao.getAllCoach();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
ArrayList<Integer> list_id = new ArrayList<>();
for(int i =0; i < list_coach.size(); i++){
list_id.add(list_coach.get(i).getUser_id());
}
status = false;
for(int j =0; j < list_id.size(); j++){
if(user.getUser_id() == list_id.get(j)){
status = true;
}
}
TextView status_text = findViewById(R.id.memberstatus);
if(status){
status_text.setText("Coach");
}else{
status_text.setText("Group Member");
}
TextView full_name = findViewById(R.id.fullName);
full_name.setText(user.getFirst_name() + " " + user.getLast_name());
TextView age = findViewById(R.id.ageTextView);
age.setText(""+user.getAge());
TextView coach_name = findViewById(R.id.coachTextView);
coach_name.setText(coach.getFirst_name() + " " + coach.getLast_name());
TextView user_name = findViewById(R.id.usernameTextView);
user_name.setText(user.getUsername());
TextView bio = findViewById(R.id.viewBio);
bio.setText(user.getBio());
profilePic = findViewById(R.id.profilePicture);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
profilePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
choosePicture();
}
});
Button menuButton = findViewById(R.id.menuButton);
menuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(status){
Intent intent = new Intent(ViewProfileActivity.this, AdminActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(ViewProfileActivity.this, MainActivity.class);
startActivity(intent);
}
}
});
Button edit_profile = findViewById(R.id.editProfileButton);
edit_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ViewProfileActivity.this, EditProfileActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
first.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String link = dataSnapshot.getValue(String.class);
Picasso.get().load(link).into(profilePic);
}
@Override
public void onCancelled(DatabaseError databaseError) {
try {
if(!user.getProfile_url().isEmpty()) {
Picasso.get().load(user.getProfile_url()).into(profilePic);
}else{
Snackbar.make(findViewById(android.R.id.content),"Image empty.\nEdit profile and to add a url.", Snackbar.LENGTH_LONG).show();
}
}catch (Exception e){
Snackbar.make(findViewById(android.R.id.content),"Image URL Error.", Snackbar.LENGTH_LONG).show();
}
}
});
}
private void choosePicture(){
Intent intent = new Intent();
intent.setType("images/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode ==1 && resultCode ==RESULT_OK && data!= null && data.getData()!=null){
imageUri = data.getData();
profilePic.setImageURI(imageUri);
uploadPicture();
}
}
private void uploadPicture() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading Image...");
pd.show();
final String randomKey = UUID.randomUUID().toString();
StorageReference riversRef = storageReference.child("image" + randomKey);
riversRef.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Snackbar.make(findViewById(android.R.id.content),"Image Uploaded.", Snackbar.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Failed to Upload", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progressPercent = (100 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
pd.setMessage("Percentage: " + (int)progressPercent + "%");
}
});
}
}
| true
|
55cc32293009889f1fa2f5e8f59f90e3033f7231
|
Java
|
AmosWang0626/im
|
/src/main/java/com/amos/im/core/handler/ImHandler.java
|
UTF-8
| 1,560
| 2.25
| 2
|
[] |
no_license
|
package com.amos.im.core.handler;
import com.amos.im.common.BasePacket;
import com.amos.im.core.command.Command;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.HashMap;
import java.util.Map;
/**
* PROJECT: im
* DESCRIPTION: 简化同级Handler >>>>> ch.pipeline().addLast()
*
* @author amos
* @date 2019/4/4
*/
@ChannelHandler.Sharable
public class ImHandler extends SimpleChannelInboundHandler<BasePacket> {
public static final ImHandler INSTANCE = new ImHandler();
private final Map<Byte, SimpleChannelInboundHandler<? extends BasePacket>> handlerMap;
private ImHandler() {
handlerMap = new HashMap<>();
handlerMap.put(Command.MESSAGE_REQUEST, MessageRequestHandler.INSTANCE);
handlerMap.put(Command.GROUP_CREATE_REQUEST, GroupCreateRequestHandler.INSTANCE);
handlerMap.put(Command.GROUP_JOIN_REQUEST, GroupJoinRequestHandler.INSTANCE);
handlerMap.put(Command.GROUP_LIST_REQUEST, GroupMemberListRequestHandler.INSTANCE);
handlerMap.put(Command.GROUP_QUIT_REQUEST, GroupQuitRequestHandler.INSTANCE);
handlerMap.put(Command.GROUP_MESSAGE_REQUEST, GroupMessageRequestHandler.INSTANCE);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, BasePacket basePacket) throws Exception {
if (handlerMap.get(basePacket.getCommand()) != null) {
handlerMap.get(basePacket.getCommand()).channelRead(ctx, basePacket);
}
}
}
| true
|
9e915c3adb50071cc4f5e359ab0d7ca9c2129011
|
Java
|
Bruno599/OOS
|
/Praktikum_1/src/aufgabe1/Main.java
|
UTF-8
| 192
| 1.820313
| 2
|
[] |
no_license
|
package aufgabe1;
public class Main {
public static void main(String[] args) {
Pascdreieck dreieck = new Pascdreieck();
dreieck.print_pascdreieck();
}
}
| true
|