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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cefd0dbb96f1d6614fe0802a213a5c05d4204aa9
|
Java
|
dgerasimenko/RestService
|
/src/main/java/com/restservice/service/BaseService.java
|
UTF-8
| 584
| 2.203125
| 2
|
[] |
no_license
|
package com.restservice.service;
import com.restservice.dto.IBaseDto;
import com.restservice.exception.ServiceException;
import java.util.List;
public abstract class BaseService<E, T extends IBaseDto> implements IBaseService<E, T> {
public List<T> getAll() throws ServiceException {
List<T> result;
try {
List<E> dbResult = getDao().findAll();
result = getDtoConverter().convertToDto(dbResult);
} catch (Exception ex) {
throw new ServiceException("Failed to findAll.", ex);
}
return result;
}
}
| true
|
25b4ac301e183cd690485d65b864b38082c190d4
|
Java
|
moutainhigh/meidianyishop
|
/meidianyi-common/src/main/java/com/meidianyi/shop/service/pojo/saas/shop/ShopMpListVo.java
|
UTF-8
| 797
| 1.523438
| 2
|
[] |
no_license
|
package com.meidianyi.shop.service.pojo.saas.shop;
import java.math.BigDecimal;
import java.sql.Timestamp;
import lombok.Data;
/**
* 店铺发布列表返回值
* @author zhaojianqiang
*
* 2019年11月22日 上午11:30:59
*/
@Data
public class ShopMpListVo {
private String appId;
private Integer shopId;
private Timestamp createTime;
private String nickName;
private Timestamp publishTime;
private Timestamp lastUploadTime;
private Integer bindTemplateId;
private Byte openPay;
private String principalName;
private String shopType;
private Byte isEnabled;
private BigDecimal renewMoney;
private Timestamp expireTime;
private Integer templateId;
private String userVersion;
private String bindUserVersion;
private String shopExpireStatus;
private Timestamp startTime;
}
| true
|
9a5fe51ba4088fa9adf13bdf3e840ff552b5147a
|
Java
|
nassimbg/Problems
|
/src/test/java/MinimumSizeSubarraySumTest.java
|
UTF-8
| 276
| 2.1875
| 2
|
[] |
no_license
|
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MinimumSizeSubarraySumTest {
@Test
public void minSubArrayLen() throws Exception {
assertEquals(2, MinimumSizeSubarraySum.minSubArrayLen(7, new int[] { 2, 3, 1, 2, 4, 3 }));
}
}
| true
|
8df7f240d79531f043c50ad29de6793b3c90c439
|
Java
|
Dmitrij-berg/HomeWork3
|
/Chislo.java
|
WINDOWS-1251
| 1,464
| 3.75
| 4
|
[] |
no_license
|
package HomeWork3;
import java.util.Scanner;
/**
* " ": [1, 100]. .
* , , .
* , .
*/
public class Chislo {
Scanner h = new Scanner(System.in);
int f = 0, nn = 0, n = 0;
public int vvod(){
System.out.println(" ");
return h.nextInt();
}
public int ugad(int nn){
f = vvod();
while (true) {
if (f == nn) {
System.out.println(", !");
break;
} else {
if (nn > f) {
System.out.println(" ");
f = vvod();
} else {
System.out.println(" ");
f = vvod();
}
}
}
return f;
}
public void pers(){
n = (int) (Math.random()*100)+1;
ugad(n);
}
public static void main(String[] args) {
Chislo ggg = new Chislo();
ggg.pers();
}
}
| true
|
69a6b363f7fe752986617b20982b76ab10f9045a
|
Java
|
nxchodev/PhonexEffects
|
/src/me/nacho/effects/commands/SpeedCommand.java
|
UTF-8
| 1,405
| 2.671875
| 3
|
[] |
no_license
|
package me.nacho.effects.commands;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import me.nacho.effects.colors.Colors;
public class SpeedCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender instanceof Player)) {
Bukkit.getConsoleSender().sendMessage(Colors.translate("&4No pelotudo"));
return true;
}
Player player = (Player) sender;
if(!player.hasPermission("phonexeffects.speed") || !player.isOp()) {
sender.sendMessage(Colors.translate("&cNo Permission."));
return true;
}
if(!player.hasPotionEffect(PotionEffectType.SPEED)) {
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,Integer.MAX_VALUE, 1));
sender.sendMessage(Colors.translate("&aGiven you &b&lSpeed Effect"));
player.playSound(player.getLocation(), Sound.DRINK, 10, 1);
} else {
player.removePotionEffect(PotionEffectType.SPEED);
sender.sendMessage(Colors.translate("&cRemoved from you &b&lSpeed Effect"));
player.playSound(player.getLocation(), Sound.ANVIL_BREAK, 10, 1);
}
return true;
}
}
| true
|
0cfeb2c6f0d53f31853371e767b498daf7d70759
|
Java
|
MagdalenaR/ZaawansowanaJava
|
/src/main/java/ZZPJ/Project/Model/MovieWithRating.java
|
UTF-8
| 1,254
| 2.9375
| 3
|
[] |
no_license
|
package ZZPJ.Project.Model;
import ZZPJ.Project.Crawler;
import org.jsoup.nodes.Document;
public class MovieWithRating extends MovieDecorator {
protected double rate;
protected int ratingCount;
public MovieWithRating(Movie movie) {
super(movie);
}
public boolean downloadMovieInfo(Crawler crawler, String urlForMovie) {
Document document = crawler.downloadDocument(urlForMovie);
if (document == null || document.equals("")) {
return false;
} else {
movie.downloadMovieInfo(crawler, urlForMovie);
this.rate = crawler.getMovieRate(document);
this.ratingCount = crawler.getMovieRatingCount(document);
return true;
}
}
public void showMovieInformatation() {
movie.showMovieInformatation();
System.out.println("Rating value: " + this.rate);
System.out.println("Rating count: " + this.ratingCount);
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public int getRatingCount() {
return ratingCount;
}
public void setRatingCount(int ratingCount) {
this.ratingCount = ratingCount;
}
}
| true
|
eafa4a60b1589a88a8d8b8abbd31d345119ee6e5
|
Java
|
Mathias279/Dames
|
/jeuDeDamesVanBorm/src/dames/vueC/Map.java
|
UTF-8
| 2,142
| 3.0625
| 3
|
[] |
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 dames.vueC;
/**
*
* @author Lenovo
*/
public class Map {
private final int taille;
private Case[][] tableauCases;
public Map(int taille) {
this.taille = taille;
this.tableauCases = new Case[taille][taille];
int i,j;
boolean blanc=true;
//Case tempCase = new Case(1,1);
for(i=0;i<this.taille;i++){
for(j=0;j<this.taille;j++){
this.tableauCases[i][j] = new Case();
if(blanc){
this.tableauCases[i][j].setApparence('O');
}
else {
this.tableauCases[i][j].setApparence('X');
}
blanc=!blanc;
}
}
}
public Case[][] getTableauCases() {
return tableauCases;
}
public Case getTableauCases(int x, int y) {
return tableauCases[x][y];
}
public void setTableauCases(Case[][] tableauCases) {
this.tableauCases = tableauCases;
}
public void mapConsole(){
int i,j;
for(i = 0;i<2*(this.taille)+3;i++){
System.out.print("#");
}
System.out.println();
for(i=0;i<this.taille;i++){
System.out.print("# ");
for(j=0;j<this.taille;j++){
//System.out.print("i:"+i+" j="+j);
System.out.print(this.getTableauCases(i,j).getApparence());
//System.out.print(dieze+" ");
System.out.print(" ");//dieze);
}
System.out.print('#');
System.out.println();
}
for(i = 0;i<(2*this.taille)+3;i++){
System.out.print('#');
}
System.out.println();
}
}
| true
|
38727d317820389d3aee47946cc99dba54472817
|
Java
|
moutainhigh/amez-springcloud
|
/common/common-invoke-amez/src/main/java/com/union/aimei/remote/model/UpdateLoginPasswordVo.java
|
UTF-8
| 717
| 1.882813
| 2
|
[] |
no_license
|
package com.union.aimei.remote.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author GaoWei
* @describe 修改登录密码vo
* @time 2018/4/12,17:06
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "修改登录密码VO")
public class UpdateLoginPasswordVo {
@ApiModelProperty(value = "用户UUID")
private String uuid;
@ApiModelProperty(value = "旧密码")
private String oldLoginPassword;
@ApiModelProperty(value = "新密码")
private String newLoginPassword;
@ApiModelProperty(value = "IP")
private String ip;
}
| true
|
f50ccd28d2737cf39c934da34b13dc963b8b2f2a
|
Java
|
EmalinaBidari/CS136L
|
/Attack.java
|
UTF-8
| 166
| 3.09375
| 3
|
[] |
no_license
|
public class Attack{
private int amount;
public Attack(int amount){
this.amount = amount;
}
public int getDamage(){
return amount;
}
}
| true
|
e0d8490419c74e43fbab50b182e44fab18afa143
|
Java
|
newrelic/newrelic-java-agent
|
/instrumentation/websphere-liberty-profile-environment-8.5.5.5/src/main/java/com/ibm/ws/tcpchannel/internal/TCPChannelFactory.java
|
UTF-8
| 1,875
| 1.921875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.ibm.ws.tcpchannel.internal;
import com.ibm.websphere.channelfw.ChannelData;
import com.ibm.wsspi.channelfw.Channel;
import com.ibm.wsspi.channelfw.exception.ChannelException;
import com.newrelic.agent.bridge.AgentBridge;
import com.newrelic.api.agent.weaver.NewField;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import java.util.Map;
import java.util.logging.Level;
@Weave
public class TCPChannelFactory {
@NewField
private static final String DEFAULT_HTTP_ENDPOINT = "defaultHttpEndpoint";
protected Channel createChannel(final ChannelData channelData) throws ChannelException {
if (channelData.isInbound() && DEFAULT_HTTP_ENDPOINT.equals(channelData.getExternalName())) {
Map<Object, Object> propertyBag = channelData.getPropertyBag();
if (propertyBag.containsKey("port")) {
try {
int port = Integer.valueOf((String) propertyBag.get("port"));
AgentBridge.publicApi.setAppServerPort(port);
} catch (NumberFormatException e) {
AgentBridge.getAgent().getLogger().log(Level.SEVERE,
"could not find server port for WebSphere Liberty Profile. Found {0}",
propertyBag.get("port"));
}
} else {
AgentBridge.getAgent().getLogger().log(Level.FINE,
"could not find server port for WebSphere Liberty Profile.");
}
} else {
AgentBridge.getAgent().getLogger().log(Level.FINE,
"could not find server port for WebSphere Liberty Profile.");
}
return Weaver.callOriginal();
}
}
| true
|
ba8105b5f90dbb6bc46a5b5af292f1053b414644
|
Java
|
2381447237/gongsiCode
|
/放开穿(可以运行)/Shopping/src/com/example/secondlevelactivity/BaozuActivity.java
|
UTF-8
| 3,471
| 2.0625
| 2
|
[] |
no_license
|
package com.example.secondlevelactivity;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import okhttp3.Call;
import com.example.adapters.BaozuAdapter;
import com.example.infoclass.BaozuContent;
import com.example.shopping.R;
import com.example.thirdlevelactivity.AboutUsActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class BaozuActivity extends Activity implements OnClickListener{
private ImageView iv_back;
private TextView tv_baozu;
private GridView gv;
private List<BaozuContent> data=new ArrayList<BaozuContent>();
private BaozuAdapter bAdapter;
private String urlStr="http://web.youli.pw:85/Json/Get_Packages_Dict.aspx";
private String userID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_baozu);
Intent intent=getIntent();
userID=intent.getStringExtra("userID");
iv_back=(ImageView) findViewById(R.id.img_back_baozu);
iv_back.setOnClickListener(this);
tv_baozu=(TextView) findViewById(R.id.tv_baozu);
tv_baozu.setOnClickListener(this);
gv=(GridView) findViewById(R.id.gv_baozu);
gv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for(BaozuContent c:data){
c.setSelect(false);
}
data.get(position).setSelect(true);
bAdapter.notifyDataSetChanged();
}
});
getData();
}
private void getData(){
OkHttpUtils.post().url(urlStr).addParams("AcctID",userID).build().execute(new StringCallback() {
@Override
public void onResponse(final String str) {
runOnUiThread(new Runnable() {
public void run() {
Gson gson=new Gson();
Type listType=new TypeToken<LinkedList<BaozuContent>>(){}.getType();
LinkedList<BaozuContent> llc=gson.fromJson(str,listType);
BaozuContent c=null;
for(int i=0;i<llc.size();i++){
if(i==0){
c=new BaozuContent(llc.get(i).PackageName,llc.get(i).Description,true);
}else{
c=new BaozuContent(llc.get(i).PackageName,llc.get(i).Description,false);
}
data.add(c);
}
bAdapter=new BaozuAdapter(data, BaozuActivity.this);
gv.setAdapter(bAdapter);
}
});
}
@Override
public void onError(Call arg0, Exception arg1) {
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img_back_baozu:
finish();
break;
case R.id.tv_baozu:
Intent auIntent=new Intent(BaozuActivity.this,AboutUsActivity.class);
auIntent.putExtra("type","baozu");
startActivity(auIntent);
break;
default:
break;
}
}
}
| true
|
112b9ea54b649407ee1001c5d13e66f914e64e1f
|
Java
|
google/j2cl-protobuf
|
/javatests/com/google/protobuf/contrib/j2cl/integration/BooleanFieldsTest.java
|
UTF-8
| 7,367
| 2.078125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.protobuf.contrib.j2cl.integration;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.protobuf.contrib.j2cl.protos.Accessor.TestProto;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BooleanFieldsTest {
@Test
public void testOptionalFieldNoDefault_defaultInstance() {
assertThat(TestProto.getDefaultInstance().hasOptionalBool()).isFalse();
assertThat(TestProto.getDefaultInstance().getOptionalBool()).isFalse();
}
@Test
public void testOptionalFieldNoDefault_setTrue() {
TestProto.Builder builder = TestProto.newBuilder().setOptionalBool(true);
assertThat(builder.hasOptionalBool()).isTrue();
assertThat(builder.getOptionalBool()).isTrue();
TestProto proto = builder.build();
assertThat(proto.hasOptionalBool()).isTrue();
assertThat(proto.getOptionalBool()).isTrue();
}
@Test
public void testOptionalFieldNoDefault_setFalse() {
TestProto.Builder builder = TestProto.newBuilder().setOptionalBool(false);
assertThat(builder.hasOptionalBool()).isTrue();
assertThat(builder.getOptionalBool()).isFalse();
TestProto proto = builder.build();
assertThat(proto.hasOptionalBool()).isTrue();
assertThat(proto.getOptionalBool()).isFalse();
}
@Test
public void testOptionalFieldNoDefault_clear() {
TestProto.Builder builder = TestProto.newBuilder().setOptionalBool(true);
builder.clearOptionalBool();
assertThat(builder.hasOptionalBool()).isFalse();
TestProto proto = builder.build();
assertThat(proto.hasOptionalBool()).isFalse();
}
@Test
public void testOptionalFieldWithDefault_setTrue() {
assertThat(TestProto.getDefaultInstance().getOptionalBoolWithDefault()).isTrue();
TestProto.Builder builder = TestProto.newBuilder().setOptionalBoolWithDefault(true);
assertThat(builder.getOptionalBoolWithDefault()).isTrue();
assertThat(builder.hasOptionalBoolWithDefault()).isTrue();
TestProto proto = builder.build();
assertThat(proto.hasOptionalBoolWithDefault()).isTrue();
assertThat(proto.getOptionalBoolWithDefault()).isTrue();
}
@Test
public void testOptionalFieldWithDefault_setFalse() {
TestProto.Builder builder = TestProto.newBuilder().setOptionalBoolWithDefault(false);
assertThat(builder.hasOptionalBoolWithDefault()).isTrue();
assertThat(builder.getOptionalBoolWithDefault()).isFalse();
TestProto proto = builder.build();
assertThat(proto.hasOptionalBoolWithDefault()).isTrue();
assertThat(proto.getOptionalBoolWithDefault()).isFalse();
}
@Test
public void testRepeatedField_defaultInstance() {
assertThat(TestProto.getDefaultInstance().getRepeatedBoolCount()).isEqualTo(0);
assertThat(TestProto.newBuilder().build().getRepeatedBoolCount()).isEqualTo(0);
if (InternalChecks.isCheckIndex()) {
assertThrows(Exception.class, () -> TestProto.newBuilder().build().getRepeatedBool(3));
} else {
assertThat(TestProto.newBuilder().build().getRepeatedBool(3)).isNull();
}
}
@Test
public void testRepeatedField_add() {
TestProto.Builder builder = TestProto.newBuilder().addRepeatedBool(true).addRepeatedBool(false);
assertThat(Arrays.asList(true, false))
.containsExactlyElementsIn(builder.getRepeatedBoolList())
.inOrder();
TestProto proto = builder.build();
assertThat(Arrays.asList(true, false))
.containsExactlyElementsIn(proto.getRepeatedBoolList())
.inOrder();
}
@Test
public void testRepeatedField_addAll() {
TestProto proto = TestProto.newBuilder().addRepeatedBool(true).addRepeatedBool(false).build();
TestProto.Builder builder =
proto.toBuilder().addAllRepeatedBool(Arrays.asList(false, true, true));
assertThat(Arrays.asList(true, false, false, true, true))
.containsExactlyElementsIn(builder.getRepeatedBoolList())
.inOrder();
TestProto proto2 = builder.build();
assertThat(Arrays.asList(true, false, false, true, true))
.containsExactlyElementsIn(proto2.getRepeatedBoolList())
.inOrder();
}
@Test
public void testRepeatedField_set() {
TestProto proto =
TestProto.newBuilder()
.addRepeatedBool(true)
.addRepeatedBool(false)
.addRepeatedBool(false)
.build();
TestProto.Builder builder = proto.toBuilder().setRepeatedBool(2, true);
assertThat(Arrays.asList(true, false, true))
.containsExactlyElementsIn(builder.getRepeatedBoolList())
.inOrder();
TestProto proto2 = builder.build();
assertThat(Arrays.asList(true, false, true))
.containsExactlyElementsIn(proto2.getRepeatedBoolList().toArray())
.inOrder();
}
@Test
public void testRepeatedField_getAndCount() {
TestProto.Builder builder =
TestProto.newBuilder().addRepeatedBool(true).addRepeatedBool(false).addRepeatedBool(false);
assertThat(builder.getRepeatedBoolCount()).isEqualTo(3);
assertThat(builder.getRepeatedBool(0)).isTrue();
assertThat(builder.getRepeatedBool(1)).isFalse();
assertThat(builder.getRepeatedBool(2)).isFalse();
if (InternalChecks.isCheckIndex()) {
assertThrows(Exception.class, () -> builder.getRepeatedBool(3));
} else {
assertThat(builder.getRepeatedBool(3)).isNull();
}
TestProto proto = builder.build();
assertThat(proto.getRepeatedBoolCount()).isEqualTo(3);
assertThat(proto.getRepeatedBool(0)).isTrue();
assertThat(proto.getRepeatedBool(1)).isFalse();
assertThat(proto.getRepeatedBool(2)).isFalse();
if (InternalChecks.isCheckIndex()) {
assertThrows(Exception.class, () -> proto.getRepeatedBool(3));
} else {
assertThat(proto.getRepeatedBool(3)).isNull();
}
}
@Test
public void testRepeatedField_clear() {
TestProto proto = TestProto.newBuilder().addRepeatedBool(true).addRepeatedBool(false).build();
TestProto.Builder builder = proto.toBuilder().clearRepeatedBool();
assertThat(builder.getRepeatedBoolCount()).isEqualTo(0);
assertThat(builder.getRepeatedBoolList()).isEmpty();
TestProto proto2 = builder.build();
assertThat(proto2.getRepeatedBoolCount()).isEqualTo(0);
assertThat(proto2.getRepeatedBoolCount()).isEqualTo(0);
}
@Test
public void testRepeatedField_getReturnsImmutableList() {
TestProto.Builder builder = TestProto.newBuilder().addRepeatedBool(true);
List<Boolean> repeatedFieldList = builder.getRepeatedBoolList();
assertThrows(Exception.class, () -> repeatedFieldList.add(false));
assertThrows(Exception.class, () -> repeatedFieldList.remove(0));
}
}
| true
|
b7e02d73e5398e72d0e0f6d5bd3a8a2cf08f1690
|
Java
|
NiteshSK/programmingInterview
|
/src/main/java/com/practice/codingInterviewBook/insertIntervals.java
|
UTF-8
| 1,797
| 3.703125
| 4
|
[] |
no_license
|
package com.practice.codingInterviewBook;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*
* this class can be used to insert a particular interval in between an Array of intervals
* */
public class insertIntervals {
public static void main(String[] args) {
ArrayList<Interval> arrayList = new ArrayList<Interval>();
arrayList.add(new Interval(2,4));
arrayList.add(new Interval(3,6));
arrayList.add(new Interval(11,14));
arrayList.add(new Interval(5,8));
arrayList.add(new Interval(7,9));
insertInterval(arrayList,new Interval(0,1));
}
static ArrayList<Interval> insertInterval(ArrayList<Interval> intervals, Interval intervalToInsert){
ArrayList<Interval> result = new ArrayList<Interval>();
for(Interval interval:intervals){
if(interval.end<intervalToInsert.start){
result.add(interval);
}
else if(interval.start>intervalToInsert.end){
result.add(intervalToInsert);
intervalToInsert=interval;
}
else if(interval.start<intervalToInsert.end || interval.end>intervalToInsert.start){
intervalToInsert = new Interval(Math.min(interval.start,intervalToInsert.start),Math.max(interval.end,intervalToInsert.end));
}
}
result.add(intervalToInsert);
for (int i =0;i<result.size();i++){
System.out.println(result.get(i).start+","+result.get(i).end);
}
return result;
}
}
class Interval{
int start;
int end;
Interval(){
start=0;
end=0;
}
Interval(int start,int end){
this.start = start;
this.end = end;
}
}
| true
|
2928a6e315bb3625cd5360e638f0c90dbcc605a0
|
Java
|
han1396735592/fast-code
|
/fast-code-core/src/main/java/cn/qqhxj/fastcode/core/vo/TableConfig.java
|
UTF-8
| 913
| 1.929688
| 2
|
[] |
no_license
|
package cn.qqhxj.fastcode.core.vo;
import lombok.Data;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Data
public class TableConfig {
private ProjectConfig projectConfig;
private List<String> templateList;
private List<TemplateConfig> templateConfigList;
private Map<String, Object> metaData;
private String table;
private boolean save;
private String savePath;
public List<TemplateConfig> getTemplateConfigList() {
return templateList.stream().map(item -> {
TemplateConfig config = new TemplateConfig();
config.setTable(table);
config.setTemplate(item);
config.setSave(save);
config.setSavePath(savePath);
config.setMetaData(metaData);
config.setTableConfig(this);
return config;
}).collect(Collectors.toList());
}
}
| true
|
bb5c8f43f3870052a83e9d984495126d333a8909
|
Java
|
Mrsulin/base
|
/src/club/sulin/collection/Person.java
|
UTF-8
| 1,666
| 3.296875
| 3
|
[] |
no_license
|
package club.sulin.collection;
import java.io.Serializable;
/**
* Title: Person
* desc 实现compareble接口,是为了重写compareTo方法,让TreeMap和TreeSet在排序的时候有排序规则
*
* @author sulin
* @date 2019-07-12
*/
public final class Person implements Comparable<Person>, Serializable {
private String name;
private Integer id;
public Person(String name, Integer id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return id != null ? id.equals(person.id) : person.id == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Person o) {
if (this.id > o.id) {
return 1;
} else if (this.id < o.id) {
return -1;
} else {
return 0;
}
}
}
| true
|
d68742e8263d019d9e87233500dc1c3500c31b7a
|
Java
|
casanovapick/ReadSecret
|
/app/src/main/java/ais/co/th/readsecret/MainActivity.java
|
UTF-8
| 2,446
| 2.234375
| 2
|
[] |
no_license
|
package ais.co.th.readsecret;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button btnGET;
TextView txtSecret;
Button btnOut;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
btnGET = (Button) findViewById(R.id.btn_get);
btnOut = (Button) findViewById(R.id.btn_logout);
txtSecret = (TextView) findViewById(R.id.txt_secret);
btnGET.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("ais.co.th.writesecret", "ais.co.th.writesecret.ConfirmActivity"));
startActivityForResult(intent,200);
}
});
btnOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs.edit().putString("Secret","").apply();
finish();
}
});
if(prefs.getString("Secret","").matches("")){
btnOut.setVisibility(View.GONE);
btnGET.setVisibility(View.VISIBLE);
}else{
txtSecret.setText("Login with "+prefs.getString("Secret",""));
btnGET.setVisibility(View.GONE);
btnOut.setVisibility(View.VISIBLE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (200 == requestCode) {
if (resultCode == RESULT_OK) {
txtSecret.setText("Login with "+data.getStringExtra("Secret"));
prefs.edit().putString("Secret", data.getStringExtra("Secret")).apply();
btnGET.setVisibility(View.GONE);
btnOut.setVisibility(View.VISIBLE);
}
}
}
}
| true
|
ab0fdb610d83ab4f28ae6b6b3cb7d94e44c6ce89
|
Java
|
robinlabs/RobinClient
|
/app/src/main/java/com/magnifis/parking/pref/IntListPreference.java
|
UTF-8
| 1,954
| 2.28125
| 2
|
[] |
no_license
|
package com.magnifis.parking.pref;
import java.lang.reflect.Field;
import com.magnifis.parking.utils.Utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.TypedArray;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
public class IntListPreference extends ListPreference {
private static String TAG=IntListPreference.class.getSimpleName();
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
if (a.hasValue(index)) {
return Integer.toString(a.getInt(index,-1));
}
return null;
}
@Override
protected String getPersistedString(String defaultReturnValue) {
int d=Utils.isEmpty(defaultReturnValue)?-1:Integer.parseInt(defaultReturnValue);
return Integer.toString( getPersistedInt(d) );
}
@Override
protected boolean persistString(String value) {
return super.persistInt(Integer.parseInt(value));
}
@Override
public void setEntryValues(int entryValuesResId) {
Context ctx=getContext();
int ia[]=ctx.getResources().getIntArray(entryValuesResId);
if (ia==null) super.setEntryValues(null); else {
String sa[]=new String[ia.length];
for (int i=0;i<ia.length;i++) sa[i]=Integer.toString(ia[i]);
super.setEntryValues(sa);
}
}
public IntListPreference(Context context) {
this(context, null);
}
public IntListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
int idsListPreference[]=Utils.getInternalAndroidResIds("styleable","ListPreference");
int idListPreference_entryValues=Utils.getInternalAndroidResId("styleable", "ListPreference_entryValues");
TypedArray a = context.obtainStyledAttributes(attrs, idsListPreference, 0, 0);
int rId=a.getResourceId(idListPreference_entryValues, 0);
setEntryValues(rId);
a.recycle();
}
}
| true
|
58fc4d54218a47826557c499a615f32c1f8ccaae
|
Java
|
mt40/Problem-Solving
|
/archive/unsorted/2016.01/2016.01.26 - unsorted/SPOJ_MSE06H.java
|
UTF-8
| 1,847
| 3.140625
| 3
|
[] |
no_license
|
package workspace;
import helperClasses.InputReader;
import java.io.PrintWriter;
import java.util.Arrays;
import helperClasses.FastScanner;
import helperClasses.Util;
public class SPOJ_MSE06H {
int inf = Integer.MAX_VALUE;
public void solve(int testNumber, InputReader input, PrintWriter out) {
FastScanner in = new FastScanner(input);
int n = in.i(), m = in.i(), k = in.i();
BIT tree = new BIT(m);
Edge []a = new Edge[k];
for(int i = 0; i < k; ++i) {
a[i] = new Edge(in.i(), in.i());
tree.add(a[i].des);
}
Arrays.sort(a);
long ans = 0;
for(Edge e : a) {
ans += tree.sum(e.des - 1);
tree.remove(e.des);
}
out.printf("Test case %d: ", testNumber);
out.println(Long.toUnsignedString(ans)); // for safety :)
}
class BIT {
int []arr;
int n;
public BIT(int n) {
this.n = n;
arr = new int[n + 1];
}
void add(int i) {
while(i <= n) {
arr[i]++;
i += i & (-i);
}
}
void remove(int i) {
while(i <= n) {
arr[i]--;
i += i & (-i);
}
}
long sum(int i) {
long rs = 0;
while(i > 0) {
rs += arr[i];
i -= i & (-i);
}
return rs;
}
}
class Edge implements Comparable<Edge> {
int src, des;
public Edge(int src, int des) {
this.src = src;
this.des = des;
}
@Override
public int compareTo(Edge o) {
int t = Integer.compare(src, o.src);
return (t == 0) ? Integer.compare(des, o.des) : t;
}
}
}
| true
|
f211b648869da275fd95baa7c58b0dd0099da6bc
|
Java
|
lechP/challenger
|
/src/main/java/codility/training/lesson08/MinPerimeterRectangle.java
|
UTF-8
| 392
| 2.890625
| 3
|
[] |
no_license
|
package codility.training.lesson08;
/**
* Created by LPI on 06.11.2015
*/
public class MinPerimeterRectangle {
int solution(int N){
int i=1;
int sideA = 1;
int sideB = N;
while(i*i<=N){
if(N%i==0){
sideA = i;
sideB = N/i;
}
i++;
}
return 2*(sideA + sideB);
}
}
| true
|
c29727a8c09c862d0221aa048273f31346052f98
|
Java
|
luca-98/cma-server-springboot
|
/src/main/java/com/github/cmateam/cmaserver/repository/InvoiceDetailedRepository.java
|
UTF-8
| 7,146
| 1.945313
| 2
|
[
"MIT"
] |
permissive
|
package com.github.cmateam.cmaserver.repository;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import com.github.cmateam.cmaserver.entity.InvoiceDetailedEntity;
import com.github.cmateam.cmaserver.entity.PatientEntity;
public interface InvoiceDetailedRepository extends JpaRepository<InvoiceDetailedEntity, UUID> {
@Query("select id from InvoiceDetailedEntity id join id.invoiceByInvoiceId i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and id.status = 2 and id.amount > id.amountPaid and p.id = ?1 order by id.createdAt DESC")
List<InvoiceDetailedEntity> getListInvoiceDetialDebtByPatientId(UUID patientId, Pageable pageable);
@Query("select count(id.id) from InvoiceDetailedEntity id join id.invoiceByInvoiceId i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and id.status = 2 and id.amount > id.amountPaid and p.id = ?1")
Integer countAllListInvoiceDetialDebtByPatientId(UUID patientId);
@Query("select id from InvoiceDetailedEntity id join id.invoiceByInvoiceId i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and id.status = 2 and id.amount > id.amountPaid and p.id = ?1 and date_trunc('day', i.createdAt) between ?2 and ?3 order by id.createdAt DESC")
List<InvoiceDetailedEntity> getListInvoiceDetialDebtByPatientIdAndDate(UUID patientId, Date startDate, Date endDate,
Pageable pageable);
@Query("select count(id.id) from InvoiceDetailedEntity id join id.invoiceByInvoiceId i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and id.status = 2 and id.amount > id.amountPaid and p.id = ?1 and date_trunc('day', i.createdAt) between ?2 and ?3")
Integer countAllListInvoiceDetialDebtByPatientIdAndDate(UUID patientId, Date startDate, Date endDate);
@Query("select distinct p from InvoiceEntity i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and p.patientNameSearch like ?1")
List<PatientEntity> autoSerachByName(String patientNameSearch, Pageable pageable);
@Query("select distinct p from InvoiceEntity i join i.patientByPatientId p where i.totalAmount > i.amountPaid and i.status = 2 and lower(p.patientCode) like ?1")
List<PatientEntity> autoSerachByPatientCode(String patientCode, Pageable pageable);
@Query("SELECT SUM(s.price) FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and date_trunc('day', ide.createdAt) between ?1 and ?2 group by date_trunc('day', ide.createdAt)")
Long sumAmoutOfServiceWithDate(Date startDate, Date endDate);
@Query("SELECT SUM(ms.totalAmout) FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and date_trunc('day', ide.createdAt) between ?1 and ?2 group by date_trunc('day', ide.createdAt)")
Long sumAmoutOfMedicineSaleWithDate(Date startDate, Date endDate);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and date_trunc('day', ide.createdAt) between ?1 and ?2")
List<InvoiceDetailedEntity> getInvoiceDetailedMedicineSaleWithDate(Date startDate, Date endDate);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE date_trunc('day', ide.createdAt) between ?1 and ?2 and ide.status = 2")
List<InvoiceDetailedEntity> getInvoiceDetailedServiceWithDate(Date startDate, Date endDate);
// month
@Query("SELECT SUM(ms.totalAmout) FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(month from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
Long sumAmoutOfMedicineSaleWithMonth(Integer month, Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(month from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
List<InvoiceDetailedEntity> getInvoiceDetailedMedicineSaleWithMonth(Integer month, Integer year);
@Query("SELECT SUM(s.price) FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(month from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
Long sumAmoutOfServiceWithMonth(Integer month, Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(month from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
List<InvoiceDetailedEntity> getInvoiceDetailedServiceWithMonth(Integer month, Integer year);
// quarter
@Query("SELECT SUM(ms.totalAmout) FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(quarter from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
Long sumAmoutOfMedicineSaleWithQuater(Integer quarter, Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(quarter from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
List<InvoiceDetailedEntity> getInvoiceDetailedMedicineSaleWithQuater(Integer quarter, Integer year);
@Query("SELECT SUM(s.price) FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(quarter from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
Long sumAmoutOfServiceWithQuater(Integer quarter, Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(quarter from ide.createdAt) = ?1 and extract(year from ide.createdAt) = ?2")
List<InvoiceDetailedEntity> getInvoiceDetailedServiceWithQuater(Integer quarter, Integer year);
// year
@Query("SELECT SUM(s.price) FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(year from ide.createdAt) = ?1")
Long sumAmoutOfServiceWithYear(Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s WHERE ide.status = 2 and extract(year from ide.createdAt) = ?1")
List<InvoiceDetailedEntity> getInvoiceDetailedServiceWithYear(Integer year);
@Query("SELECT ide FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(year from ide.createdAt) = ?1")
List<InvoiceDetailedEntity> getInvoiceDetailedMedicineSaleWithYear(Integer year);
@Query("SELECT SUM(ms.totalAmout) FROM InvoiceDetailedEntity ide join ide.medicineSaleByMedicineSaleId ms WHERE ide.status = 2 and extract(year from ide.createdAt) = ?1")
Long sumAmoutOfMedicineSaleWithYear(Integer year);
// get list year
@Query("SELECT distinct extract(year from ide.createdAt) FROM InvoiceDetailedEntity ide join ide.serviceByServiceId s")
List<Integer> getListYear();
@Query("select ide from InvoiceDetailedEntity ide join ide.invoiceByInvoiceId i where ide.status <> 0")
List<InvoiceDetailedEntity> getListInvoiceDetialDebtByInvoiceId(UUID invoiceId);
}
| true
|
246912aad0c498e043251ca93c5e12e17ebca641
|
Java
|
nm86nm/Java
|
/SpringJDBC/src/com/a/springjdbc/dao/PersonDAOImpl.java
|
UTF-8
| 809
| 2.390625
| 2
|
[] |
no_license
|
package com.a.springjdbc.dao;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.a.springjdbc.PersonMapper;
import com.a.springjdbc.model.Person;
public class PersonDAOImpl implements PersonDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public List<Person> listPerson() {
String sql = "SELECT * FROM person ORDER BY id ASC";
List<Person> listPerson = jdbcTemplate
.query(sql, new PersonMapper());
return listPerson;
}
/*public void setDataSource(String dataSource) {
this.dataSource = dataSource;
jdbcTemplate = new JdbcTemplate(dataSource);
}*/
}
| true
|
d52d7fa012caae4139aae64ab6f70f6d96201166
|
Java
|
CaptainMaximo/smtp-client
|
/src/main/java/com/github/captainmaximo/smtpclient/SmtpClientException.java
|
UTF-8
| 697
| 2.359375
| 2
|
[] |
no_license
|
package com.github.captainmaximo.smtpclient;
/**
*
* SmtpClientException
*
* @author CaptainMaximo
*
*/
public class SmtpClientException extends RuntimeException {
public SmtpClientException() {
super();
}
public SmtpClientException(String message) {
super(message);
}
public SmtpClientException(String message, Throwable cause) {
super(message, cause);
}
public SmtpClientException(Throwable cause) {
super(cause);
}
protected SmtpClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true
|
bd9ce7ce81b5be1c24c8e399c747275179329222
|
Java
|
ZalmanKelber/Java-Coursework-2
|
/ObjectOrientedCaesarCipher/TestCaesarCipherTwo.java
|
UTF-8
| 1,334
| 2.90625
| 3
|
[] |
no_license
|
/**
* Write a description of TestCaesarCipherTwo here.
*
* @author (your name)
* @version (a version number or a date)
*/
import edu.duke.*;
public class TestCaesarCipherTwo {
public String CaesarCipherTwoBreaker(String s) {
CaesarCipherTwo cct = new CaesarCipherTwo(0,0);
String s1 = cct.halfOfString(s, 0);
String s2 = cct.halfOfString(s, 1);
TestCaesarCipher tcct = new TestCaesarCipher();
int key1 = (tcct.maxIndex(tcct.countLetters(s1)) + 22) % 26;
int key2 = (tcct.maxIndex(tcct.countLetters(s2)) + 22) % 26;
System.out.println(key1);
System.out.println(key2);
cct = new CaesarCipherTwo(key1, key2);
return cct.decrypt(s);
}
public void simpleTests() {
FileResource fr = new FileResource();
String input = fr.asString();
//String input = "Aal uttx hm aal Qtct Fhljha pl Wbdl. Pvxvxlx!";
//CaesarCipherTwo cct = new CaesarCipherTwo(14, 24);
System.out.println("original: ");
System.out.println(input);
input = CaesarCipherTwoBreaker(input);
System.out.println("after decryption: ");
System.out.println(input);
//input = CaesarCipherTwoBreaker(input);
//System.out.println("after decryption: ");
//System.out.println(input);
}
}
| true
|
7089eff5f839d21c0744d1147cf9494f0654c1e1
|
Java
|
Savvynandha/Absolute-Java-5th-Edition-Solutions
|
/Chapter10/PP4/FileNumbers.java
|
UTF-8
| 2,828
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
package tomas.ochoa;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
/**
* Created by Tom's Desktop on 4/7/2016.
*/
public class FileNumbers
{
// Instance Variables
private String fileName;
// Constructors
// Default
public FileNumbers()
{
fileName = "";
}
// With file name
public FileNumbers(String name)
{
fileName = name;
}
// Accessors
// Method to open and calc average of file
public double getAvg()
{
// variables
double total = 0.0;
double avg = 0.0;
int count = 0;
Scanner fileInput = null;
//open file
try
{
fileInput = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error. File not found.");
}
catch(IOException e)
{
System.out.println("Fatal error");
System.exit(0);
}
// while there are double numbers
while(fileInput.hasNextDouble())
{
double next = fileInput.nextDouble();
total+=next;
count++;
}
// calculate average
avg = total/count;
NumberFormat formatter = new DecimalFormat("#.00");
System.out.println(String.format("Average of numbers of type double in file: " + formatter.format(avg)));
// close file
fileInput.close();
// return average
return avg;
}
// Method to open and calc standard deviation
public double getStdDev()
{
// variables
double avg = 0.0;
double stdDev = 0.0;
double total = 0.0;
double a = getAvg();
int count = 0;
Scanner fileInput = null;
//open file
try
{
fileInput = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error: File not found.");
}
catch(IOException e)
{
System.out.println("Fatal Error.");
System.exit(0);
}
// while there are sill double numbers
while(fileInput.hasNextDouble())
{
double next = fileInput.nextDouble();
total += (next - a) * (next - a);
count ++;
}
// Calculate Std Dev
avg = total/count;
stdDev = Math.sqrt(avg);
//close file
fileInput.close();
// return value
return stdDev;
}
}
| true
|
b6a3177c0707ebeca53383c9cb5c09dba5891d80
|
Java
|
TheSagab/Foundation-of-Programming-2
|
/Tutorial1/PROJECT_ECLIPSE/PROJECT_ECLIPSE/SoalTutorial1/src/soal/tutorial/satu/model/mapper/UserMapper.java
|
UTF-8
| 304
| 2.015625
| 2
|
[] |
no_license
|
package soal.tutorial.satu.model.mapper;
import soal.tutorial.satu.model.User;
/**
* Created by agungwb on 11/02/2017.
*/
public interface UserMapper {
public User getUserByUsername(String username);
public User getUserByUsernameAndHashedPassword(String username, String hashedPassword);
}
| true
|
740c3a3cc63faff46748209aeb66a70910b7f9c8
|
Java
|
shbondada/Samples
|
/WMIPrototype/src/main/java/com/example/wmi/print/service/PrinterDetailsResponse.java
|
UTF-8
| 523
| 1.648438
| 2
|
[] |
no_license
|
package com.example.wmi.print.service;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PrinterDetailsResponse {
private List<String> name;
private String computerName;
private String type;
private List<String> driverName;
private List<String> portName;
private boolean shared;
private boolean published;
private String deviceType;
}
| true
|
5cab1ed6a6ccbdabadbbf6dd08710f6025c3a3bb
|
Java
|
superdemon520/xzl
|
/doctor-api-service/src/main/java/cn/xinzhili/api/doctor/bean/BasicTreatmentApiInfo.java
|
UTF-8
| 607
| 2.046875
| 2
|
[] |
no_license
|
package cn.xinzhili.api.doctor.bean;
import java.util.List;
public class BasicTreatmentApiInfo {
private String id;
private String name;
private List<AttachedApiInfo> attachedInfos;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<AttachedApiInfo> getAttachedInfos() {
return attachedInfos;
}
public void setAttachedInfos(List<AttachedApiInfo> attachedInfos) {
this.attachedInfos = attachedInfos;
}
}
| true
|
3f4bedf90325d684daadbfb5c709be2af930b4cd
|
Java
|
weicm/test
|
/model/src/main/java/cn/julong/model/factory/simple/Factory.java
|
UTF-8
| 366
| 2.703125
| 3
|
[] |
no_license
|
package cn.julong.model.factory.simple;
/**
* Created by Think on 2016/7/26.
*/
public class Factory {
public MeizuPhone produce(String name) throws Exception {
if("PRO5".equals(name)) {
return new PRO5();
}else if("PRO6".equals(name)) {
return new PRO6();
}else {
throw new Exception("There is not this kind of phone!");
}
}
}
| true
|
86b8e42ef2a5637a14cbc08c493755e38f784f99
|
Java
|
cs13b1043/SWE-Project
|
/JFLAP 8.0/src/file/xml/formaldef/lsystem/AxiomTransducer.java
|
UTF-8
| 1,139
| 2.390625
| 2
|
[] |
no_license
|
package file.xml.formaldef.lsystem;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import view.lsystem.helperclasses.Axiom;
import debug.JFLAPDebug;
import file.xml.XMLHelper;
import file.xml.XMLTransducer;
/**
* Transducer specific to the axiom of an LSystem.
*
* @author Ian McMahon
*
*/
public class AxiomTransducer implements XMLTransducer<Axiom> {
private static final String AXIOM_TAG = "axiom";
@Override
public Axiom fromStructureRoot(Element root) {
List<Element> children = XMLHelper.getChildrenWithTag(root, getTag());
String axiom = "";
if (children != null) {
Element axiomNode = children.get(0);
if (axiomNode != null) {
axiom = axiomNode.getTextContent();
}
}
return new Axiom(axiom);
}
@Override
public String getTag() {
return AXIOM_TAG;
}
@Override
public boolean matchesTag(String tag) {
return AXIOM_TAG.equals(tag);
}
@Override
public Element toXMLTree(Document doc, Axiom structure) {
Element e = XMLHelper.createElement(doc, getTag(), structure, null);
return e;
}
}
| true
|
f4eeb4329d1005b3f859791e0f8e6612fd3c3502
|
Java
|
sanogotech/myerp09
|
/myerp-model/src/test/java/com/dummy/myerp/model/bean/comptabilite/JournalComptableTest.java
|
UTF-8
| 1,623
| 2.375
| 2
|
[] |
no_license
|
package com.dummy.myerp.model.bean.comptabilite;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class JournalComptableTest {
@Test
public void test_getByCode_toString_WhenJournalComptableExist() {
// Arrange
List<JournalComptable> listJournalComptable = new ArrayList<>();
JournalComptable journalComptable = new JournalComptable();
journalComptable.setCode("AA");
journalComptable.setLibelle("Alpha");
listJournalComptable.add(journalComptable);
listJournalComptable.add(new JournalComptable("BB","Beta"));
listJournalComptable.add(new JournalComptable("CC","Gama"));
// Act
JournalComptable rJournalComptable = JournalComptable.getByCode(listJournalComptable,"CC");
// Assert
Assert.assertEquals("Gama", rJournalComptable.getLibelle());
Assert.assertEquals("JournalComptable{code='CC', libelle='Gama'}", rJournalComptable.toString());
}
@Test
public void test_getByCode_toString_WhenJournalComptableNotExist() {
// Arrange
List<JournalComptable> listJournalComptable = new ArrayList<>();
listJournalComptable.add(new JournalComptable("AA","Alpha"));
listJournalComptable.add(new JournalComptable("BB","Beta"));
listJournalComptable.add(new JournalComptable("CC","Gama"));
// Act
JournalComptable rJournalComptable = JournalComptable.getByCode(listJournalComptable,"DD");
// Assert
Assert.assertEquals(null, rJournalComptable);
}
}
| true
|
7c3db30fa6e43f6a275520aeb8245bdcd9151c83
|
Java
|
NghiemHieu7295/NetbeanProjects
|
/Java2_Lab7/src/java2_lab7/TestEvents.java
|
UTF-8
| 985
| 3.171875
| 3
|
[] |
no_license
|
package java2_lab7;
import java.applet.Applet;
import java.awt.Button;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestEvents extends Applet implements ActionListener{
private int count = 0;
TextField text;
Button btnInc, btnDec;
@Override
public void init(){
text = new TextField("" + count);
btnInc = new Button("Increment");
btnDec = new Button("Decrement");
add(text);
add(btnInc);
add(btnDec);
btnInc.addActionListener(this);
btnDec.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
text.setText("" + --count);
}
});
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == btnInc){
text.setText("" + ++count);
}
}
}
| true
|
e877e00d3b8540d41cf4079401e99c49897f7bb3
|
Java
|
cinema-bizzarre/geek-spring-start
|
/src/main/ProductShop/ProductController.java
|
UTF-8
| 558
| 2.15625
| 2
|
[] |
no_license
|
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
public class ProductController {
private ProductService productService;
@Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}
@GetMapping("/all")
public String showAllProducts(Model model) {
model.addAttribute("products", productService.getAllProducts());
return "product-list";
}
}
| true
|
e12096eb90d411d97e2191e980bd35a624986b76
|
Java
|
chenghaochen1993/thread-core
|
/src/com/thread/lesson4/c_4_1/c_4_1_13_2/MyService.java
|
UTF-8
| 479
| 2.796875
| 3
|
[] |
no_license
|
package com.thread.lesson4.c_4_1.c_4_1_13_2;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by cch
* 2018-04-19 14:05.
*/
public class MyService {
public ReentrantLock lock = new ReentrantLock();
public void waitMethod(){
if(lock.tryLock()){
System.out.println(Thread.currentThread().getName()+"获得了锁");
}else {
System.out.println(Thread.currentThread().getName()+"没有获得锁");
}
}
}
| true
|
7ec8ffdf1e6122cf0e4ec43a0baf886f2fefee01
|
Java
|
00090216/IPAdressInfo
|
/app/src/main/java/com/example/charl/ipadressinfo/MainActivity.java
|
UTF-8
| 5,677
| 2.34375
| 2
|
[] |
no_license
|
package com.example.charl.ipadressinfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button Calc;
private TextView A;
private TextView B;
private TextView C;
private TextView D;
private TextView Mask;
private TextView ID;
private TextView BC;
private int Num1;
private int Num2;
private int Num3;
private int Num4;
private int NumM;
private int X1;
private int X2;
private int X3;
private int X4;
private String Comp1;
private String Comp2;
private String Comp3;
private String Comp4;
private String Comp5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calc = findViewById(R.id.Calc);
Calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Mask = findViewById(R.id.Mask);
Comp1 = Mask.getText().toString();
A = findViewById(R.id.One);
Comp2 = A.getText().toString();
B = findViewById(R.id.Two);
Comp3 = B.getText().toString();
C = findViewById(R.id.Three);
Comp4 = C.getText().toString();
D = findViewById(R.id.Four);
Comp5 = D.getText().toString();
if (!Comp1.isEmpty() & !Comp2.isEmpty() & !Comp3.isEmpty() & !Comp4.isEmpty() & !Comp5.isEmpty()) {
if (isNumeric(A,B,C,D,Mask) ) {
NumM = Integer.parseInt(Mask.getText().toString());
Num1 = Integer.parseInt(A.getText().toString());
Num2 = Integer.parseInt(B.getText().toString());
Num3 = Integer.parseInt(C.getText().toString());
Num4 = Integer.parseInt(D.getText().toString());
if (Num1 <= 255 & Num2 <= 255 & Num3 <= 255 & Num4 <= 255) {
if (Num1 >= 0 & Num2 >= 0 & Num3 >= 0 & Num4 >= 0) {
if (NumM == 24) {
X1 = Num1 & 255;
X2 = Num2 & 255;
X3 = Num3 & 255;
X4 = Num4 & 0;
ID = findViewById(R.id.Clase);
ID.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
X1 = Num1 | 0;
X2 = Num2 | 0;
X3 = Num3 | 0;
X4 = Num4 | 255;
BC = findViewById(R.id.Broadcast);
BC.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
}
if (NumM == 16) {
X1 = Num1 & 255;
X2 = Num2 & 255;
X3 = Num3 & 0;
X4 = Num4 & 0;
ID = findViewById(R.id.Clase);
ID.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
X1 = Num1 | 0;
X2 = Num2 | 0;
X3 = Num3 | 255;
X4 = Num4 | 255;
BC = findViewById(R.id.Broadcast);
BC.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
}
if (NumM == 8) {
X1 = Num1 & 255;
X2 = Num2 & 0;
X3 = Num3 & 0;
X4 = Num4 & 0;
ID = findViewById(R.id.Clase);
ID.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
X1 = Num1 | 0;
X2 = Num2 | 255;
X3 = Num3 | 255;
X4 = Num4 | 255;
BC = findViewById(R.id.Broadcast);
BC.setText(X1 + "" + "." + X2 + "" + "." + X3 + "" + "." + X4 + "");
}
}
}
}
}
}
});
}
private static boolean isNumeric(TextView A, TextView B, TextView C, TextView D, TextView Mask){
try {
String One = A.getText().toString();
String Two = B.getText().toString();
String Three= C.getText().toString();
String Four = D.getText().toString();
String Masked = Mask.getText().toString();
Integer.parseInt(One);
Integer.parseInt(Two);
Integer.parseInt(Three);
Integer.parseInt(Four);
Integer.parseInt(Masked);
return true;
} catch (NumberFormatException nfe){
return false;
}
}
}
| true
|
035ca4f63286251245cfe2124b3efc159cb0a8e2
|
Java
|
AshishkrMishra/HttpServerTool
|
/src/com/akm/myserver/httpserver/SimpleHttpServer.java
|
UTF-8
| 1,336
| 2.765625
| 3
|
[] |
no_license
|
package com.akm.myserver.httpserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.akm.myserver.handler.Handlers;
import com.akm.myserver.server.Main;
import com.sun.net.httpserver.HttpServer;
public class SimpleHttpServer {
private int port=5555;
private HttpServer server;
public void Start(int port) {
try {
this.port = port;
server = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("server started at " + port);
server.createContext("/", new Handlers.RootHandler());
server.createContext("/echoHeader", new Handlers.EchoHeaderHandler());
server.createContext("/echoGet", new Handlers.EchoGetHandler());
server.createContext("/echoPost", new Handlers.EchoPostHandler());
server.setExecutor(null);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("URL That Can be Accessible Are:=\n")
.append("/\n")
.append("/echoHeader\n")
.append("/echoGet\n")
.append("/echoPost\n");
server.start();
stringBuilder.append("Server Started");
Main.writeLog(stringBuilder.toString());
} catch (IOException e) {
//e.printStackTrace();
Main.getLogArea().setText(e.getMessage());
}
}
public void Stop() {
server.stop(0);
//System.out.println("server stopped");
Main.writeLog("server stopped");
}
}
| true
|
08432c6fb4570ed24435ca782144a5a1484bb46f
|
Java
|
BartlomiejJakubczak/Thesis
|
/app/src/main/java/com/example/bartomiejjakubczak/thesis/fragments/ManageFlatFragment.java
|
UTF-8
| 13,132
| 1.9375
| 2
|
[] |
no_license
|
package com.example.bartomiejjakubczak.thesis.fragments;
import android.app.Fragment;
import android.content.Context;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bartomiejjakubczak.thesis.R;
import com.example.bartomiejjakubczak.thesis.adapters.ManageFlatFragmentAdapter;
import com.example.bartomiejjakubczak.thesis.interfaces.FirebaseConnection;
import com.example.bartomiejjakubczak.thesis.interfaces.SharedPrefs;
import com.example.bartomiejjakubczak.thesis.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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 java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ManageFlatFragment extends Fragment implements FirebaseConnection, SharedPrefs {
private final static String TAG = "ManageFlatFragment";
private final String userDotlessEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail().replaceAll("[\\s.]", "");
private String oldName;
private String oldAddress;
private Boolean isOldName = true;
private Boolean isOldAddress = true;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mSearchedFlatDatabaseReference;
private DatabaseReference mFlatUsersDatabaseReference;
private DatabaseReference mUsersDatabaseReference;
private RecyclerView recyclerView;
private ManageFlatFragmentAdapter manageFlatFragmentAdapter;
private EditText flatName;
private ImageButton editFlatNameButton;
private EditText flatAddress;
private TextView flatCode;
private ImageButton editFlatAddressButton;
private Button saveChangesButton;
private void setButtons() {
if (loadStringFromSharedPrefs(getActivity(), "shared_prefs_is_owner").equals("yes")) {
editFlatNameButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flatName.isEnabled()) {
flatName.setEnabled(false);
} else {
flatName.setEnabled(true);
}
}
});
editFlatAddressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flatAddress.isEnabled()) {
flatAddress.setEnabled(false);
} else {
flatAddress.setEnabled(true);
}
}
});
saveChangesButton.setEnabled(false);
saveChangesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveChangesButton.setEnabled(false);
final String newName = flatName.getText().toString();
final String newAddress = flatAddress.getText().toString();
if (checkIfEmpty(newName)) {
flatName.setError("This field cannot be blank");
} else if (checkIfSpecialCharacter(newName)) {
flatName.setError("This field cannot contain special characters");
} else if (!newName.equals(oldName)){
mSearchedFlatDatabaseReference.child("name").setValue(newName).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getActivity(), "Changes saved", Toast.LENGTH_SHORT).show();
oldName = newName;
}
});
}
if (checkIfEmpty(newAddress)) {
flatAddress.setError("This field cannot be blank");
} else if (checkIfSpecialCharacter(newAddress)) {
flatAddress.setError("This field cannot contain special characters");
} else if(!newAddress.equals(oldAddress)){
mSearchedFlatDatabaseReference.child("address").setValue(newAddress).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getActivity(), "Changes saved", Toast.LENGTH_SHORT).show();
oldAddress = newAddress;
}
});
}
}
});
} else {
editFlatNameButton.setVisibility(View.GONE);
editFlatAddressButton.setVisibility(View.GONE);
saveChangesButton.setVisibility(View.GONE);
}
}
private boolean checkIfSpecialCharacter(String string) {
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(string);
return m.find();
}
private boolean checkIfEmpty(String string) {
String testString = string.trim();
return "".equals(testString);
}
private void setEditTexts() {
mSearchedFlatDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
oldName = dataSnapshot.child("name").getValue().toString();
flatName.setText(oldName);
flatName.setEnabled(false);
oldAddress = dataSnapshot.child("address").getValue().toString();
flatAddress.setText(oldAddress);
flatAddress.setEnabled(false);
flatCode.setText("Search code: " + dataSnapshot.child("searchCode").getValue().toString());
flatName.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) {
}
@Override
public void afterTextChanged(Editable s) {
if (oldName.equals(s.toString())) {
Log.d(TAG, isOldName.toString());
Log.d(TAG, isOldAddress.toString());
isOldName = true;
if (isOldAddress) {
saveChangesButton.setEnabled(false);
}
} else {
isOldName = false;
saveChangesButton.setEnabled(true);
}
}
});
flatAddress.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) {
}
@Override
public void afterTextChanged(Editable s) {
if (oldAddress.equals(s.toString())) {
Log.d(TAG, isOldName.toString());
Log.d(TAG, isOldAddress.toString());
isOldAddress = true;
if (isOldName) {
saveChangesButton.setEnabled(false);
}
} else {
isOldAddress = false;
saveChangesButton.setEnabled(true);
}
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void setRecyclerView() {
final ArrayList<User> users = new ArrayList<>();
final ArrayList<String> usersInFlatKeys = new ArrayList<>();
mFlatUsersDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
usersInFlatKeys.add(ds.getKey());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mUsersDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
if (usersInFlatKeys.contains(ds.getKey())) {
users.add(new User(
ds.child("name").getValue().toString(),
ds.child("surname").getValue().toString(),
ds.child("email").getValue().toString(),
ds.child("tag").getValue().toString()
));
}
}
manageFlatFragmentAdapter = new ManageFlatFragmentAdapter(getActivity(), users);
recyclerView.setAdapter(manageFlatFragmentAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_manage_flat, container, false);
recyclerView = view.findViewById(R.id.users_recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
flatName = view.findViewById(R.id.flat_name_fragment);
flatAddress = view.findViewById(R.id.flat_address_fragment);
flatCode = view.findViewById(R.id.flatCode_textView);
editFlatNameButton = view.findViewById(R.id.edit_flat_name_button);
editFlatAddressButton = view.findViewById(R.id.edit_flat_address_button);
saveChangesButton = view.findViewById(R.id.save_changes_button);
setButtons();
setEditTexts();
setRecyclerView();
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeFirebaseComponents();
initializeFirebaseDatabaseReferences(userDotlessEmail);
}
@Override
public void initializeFirebaseComponents() {
mFirebaseDatabase = FirebaseDatabase.getInstance();
}
@Override
public void initializeFirebaseDatabaseReferences(String dotlessEmail) {
mSearchedFlatDatabaseReference = mFirebaseDatabase.getReference().child(getString(R.string.firebase_references_flats))
.child(loadStringFromSharedPrefs(getActivity(), getString(R.string.shared_prefs_flat_key)));
mFlatUsersDatabaseReference = mFirebaseDatabase.getReference().child("flatUsers")
.child(loadStringFromSharedPrefs(getActivity(), getString(R.string.shared_prefs_flat_key)));
mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
}
@Override
public void putStringToSharedPrefs(Context context, String label, String string) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(label, string).apply();
}
@Override
public String loadStringFromSharedPrefs(Context context, String label) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(label, getString(R.string.shared_prefs_default));
}
}
| true
|
930d8d5aa0065b2b4aaf5d662d1f9085d8154333
|
Java
|
Game-Plan/OHServicesz
|
/app/src/main/java/com/ohservices/ohservices/ServiceProvider.java
|
UTF-8
| 333
| 2.46875
| 2
|
[] |
no_license
|
package com.ohservices.ohservices;
public class ServiceProvider {
String name;
String rent;
public ServiceProvider(String name, String rent) {
this.name = name;
this.rent = rent;
}
public String getName() {
return name;
}
public String getRent() {
return rent;
}
}
| true
|
4cd81b040b63ee32e409b1b4ffcec86f78178e33
|
Java
|
JorisDDaems/blogapplication
|
/src/main/java/be/intecbrussel/blogapplication/web_security_config/CreatePostDto.java
|
UTF-8
| 561
| 2.0625
| 2
|
[] |
no_license
|
package be.intecbrussel.blogapplication.web_security_config;
import lombok.Data;
import javax.validation.constraints.Size;
import java.util.List;
@Data
public class CreatePostDto {
@Size(max = 70, min = 1, message = "Title : 70 max characters")
private String postTitle;
@Size(max = 2000, min = 1, message = "Post : 1000 max characters")
private String postText;
@Size(max = 1000, message = "Post : 1000 max characters")
private String embedURL;
@Size(max = 10, message = "Tag: 10 max tags")
private List<String> tags;
}
| true
|
b8c5905d631dda5f32e2ba712a34926e228e52ce
|
Java
|
Daniyar111/TextAdventure
|
/app/src/main/java/com/text_adventure/daniyar/textadventure/ui/main/books/MainPresenter.java
|
UTF-8
| 1,826
| 2.46875
| 2
|
[] |
no_license
|
package com.text_adventure.daniyar.textadventure.ui.main.books;
import android.os.Bundle;
import android.widget.AdapterView;
import com.text_adventure.daniyar.textadventure.R;
import com.text_adventure.daniyar.textadventure.data.entity.BookModel;
import com.text_adventure.daniyar.textadventure.data.manager.ResourceManager;
import java.util.ArrayList;
public class MainPresenter implements MainContract.Presenter {
private MainContract.View mView;
private ArrayList<BookModel> mBookModels;
private ResourceManager mResourceManager;
public MainPresenter(ResourceManager resourceManager){
mResourceManager = resourceManager;
mBookModels = new ArrayList<>();
}
@Override
public ArrayList<BookModel> getBooks() {
for (int i = 0; i < imagesArray().length; i++) {
BookModel bookModel = new BookModel();
bookModel.setImageId(imagesArray()[i]);
bookModel.setName(mResourceManager.getResources().getStringArray(R.array.array_books)[i]);
mBookModels.add(bookModel);
}
return mBookModels;
}
@Override
public void onListViewItemClicked(AdapterView<?> adapterView, int i) {
BookModel bookModel = (BookModel) adapterView.getItemAtPosition(i);
Bundle bundle = new Bundle();
bundle.putString("book", bookModel.getName());
if(isViewAttached()){
mView.showDetails(bundle);
}
}
private int[] imagesArray(){
return new int[]{R.drawable.museum, R.drawable.heart_of_ice, R.drawable.psychotest};
}
@Override
public void bind(MainContract.View view) {
mView = view;
}
@Override
public void unbind() {
mView = null;
}
private boolean isViewAttached(){
return mView != null;
}
}
| true
|
3afa3dcb64105ffcf09809943dd5525dc042b2d0
|
Java
|
todinhvin/shoes-shop
|
/spring-boot/src/main/java/com/laptrinhweb/shoesshop/api/OrderController.java
|
UTF-8
| 2,270
| 2.109375
| 2
|
[] |
no_license
|
package com.laptrinhweb.shoesshop.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.laptrinhweb.shoesshop.dto.OrderDTO;
import com.laptrinhweb.shoesshop.dto.ProductDTO;
import com.laptrinhweb.shoesshop.dto.ProductPage;
import com.laptrinhweb.shoesshop.services.impl.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "api/orders")
@CrossOrigin(origins = "*", maxAge = 3600)
public class OrderController {
private OrderService orderService;
@Autowired
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping
@PreAuthorize("hasRole('ADMIN')")
public List<OrderDTO> getListOrder (@RequestParam(name = "pagination") String orderPage) {
orderPage = "{"+orderPage+"}";
ObjectMapper mapper = new ObjectMapper();
ProductPage orderPage1 = null;
try {
orderPage1 = mapper.readValue( orderPage, ProductPage.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return orderService.getOrderList(orderPage1);
}
@GetMapping(path = "/countItems")
@PreAuthorize("hasRole('ADMIN')")
public Long getCountList() {
return orderService.getCountItems();
}
@GetMapping(path = "/my-order")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public List<OrderDTO> getListOrderOfUser(Long userId) {
return orderService.getOrderListOfUser(userId);
}
@PostMapping
@PreAuthorize("hasRole('USER')")
public OrderDTO saveOrder(@RequestBody OrderDTO order ) {
return orderService.saveOrder(order);
}
@GetMapping(path = "/search")
public List<OrderDTO> getProductsSearched(@RequestParam(value = "search") String searchValue) {
return orderService.getOrdersBySearchName(searchValue);
}
@DeleteMapping
@PreAuthorize("hasRole('ADMIN')")
public void deleteOrder(@RequestParam("id")Long id) {
orderService.deleteOrder(id);
}
}
| true
|
aebede846dc82530ef6b1b1281548bf85628d3d3
|
Java
|
yasertirsen/student-interface-service
|
/src/main/java/com/fyp/studentinterfaceservice/controller/CourseController.java
|
UTF-8
| 1,202
| 2.34375
| 2
|
[] |
no_license
|
package com.fyp.studentinterfaceservice.controller;
import com.fyp.studentinterfaceservice.exceptions.ModuleParsingException;
import com.fyp.studentinterfaceservice.exceptions.StudentExceptionHandler;
import com.fyp.studentinterfaceservice.model.Course;
import com.fyp.studentinterfaceservice.services.interfaces.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class CourseController extends StudentExceptionHandler {
private final CourseService courseService;
@Autowired
public CourseController(CourseService courseService) {
this.courseService = courseService;
}
@PostMapping("/addCourse")
public Course add(@RequestBody Course course) throws ModuleParsingException {
return courseService.add(course);
}
@GetMapping("/getCourses")
public List<Course> getAllCourses() {
return courseService.getAllCourses();
}
}
| true
|
de1bc9c53bec28d1be13fbc17ecdbd3242e775eb
|
Java
|
choi970702/java_project
|
/src/com/ict0/Ex02.java
|
UTF-8
| 411
| 2.703125
| 3
|
[] |
no_license
|
package com.ict0;
public abstract class Ex02
{
private int energe;
private String productName;
public Ex02()
{
// TODO Auto-generated constructor stub
}
public int energe(int energe)
{
this.energe = energe;
return this.energe;
}
public String productName(String productName)
{
this.productName = productName;
return this.productName;
}
public abstract void electricMeter();
}
| true
|
ef508ded1238fd1b33b51972369a90b21c812d2a
|
Java
|
ghuntley/TraceTogether_1.6.1.apk
|
/jadx/sources/o/C3403fe.java
|
UTF-8
| 5,414
| 1.523438
| 2
|
[] |
no_license
|
package o;
import java.io.File;
import java.nio.charset.Charset;
import kotlin.Metadata;
@Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u001e\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u000e\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u0012\n\u0002\u0010\u0002\n\u0002\b\u0004\u001a\u001b\u0010\u0004\u001a\u00020\u0002*\u00020\u00032\b\b\u0002\u0010\u0001\u001a\u00020\u0000¢\u0006\u0004\b\u0004\u0010\u0005\u001a\u0019\u0010\u0004\u001a\u00020\u0007*\u00020\u00032\u0006\u0010\u0001\u001a\u00020\u0006¢\u0006\u0004\b\u0004\u0010\b\u001a#\u0010\n\u001a\u00020\u0007*\u00020\u00032\u0006\u0010\u0001\u001a\u00020\u00022\b\b\u0002\u0010\t\u001a\u00020\u0000¢\u0006\u0004\b\n\u0010\u000b"}, d2 = {"Ljava/nio/charset/Charset;", "p0", "", "Ljava/io/File;", "ι", "(Ljava/io/File;Ljava/nio/charset/Charset;)Ljava/lang/String;", "", "", "(Ljava/io/File;[B)V", "p1", "ɩ", "(Ljava/io/File;Ljava/lang/String;Ljava/nio/charset/Charset;)V"}, k = 5, mv = {1, 1, 15}, xi = 1, xs = "o/fc")
/* renamed from: o.fe reason: case insensitive filesystem */
public class C3403fe extends C3399fa {
/* JADX WARNING: Code restructure failed: missing block: B:10:0x0024, code lost:
throw r3;
*/
/* JADX WARNING: Code restructure failed: missing block: B:8:0x0020, code lost:
r3 = move-exception;
*/
/* JADX WARNING: Code restructure failed: missing block: B:9:0x0021, code lost:
o.eY.m2182(r0, r2);
*/
/* renamed from: ι reason: contains not printable characters */
/* Code decompiled incorrectly, please refer to instructions dump. */
public static final void m2290(java.io.File r2, byte[] r3) {
/*
java.lang.String r0 = ""
o.fM.m2254(r2, r0)
o.fM.m2254(r3, r0)
java.io.FileOutputStream r0 = new java.io.FileOutputStream
r0.<init>(r2)
java.io.Closeable r0 = (java.io.Closeable) r0
r2 = 0
java.lang.Throwable r2 = (java.lang.Throwable) r2
r1 = r0
java.io.FileOutputStream r1 = (java.io.FileOutputStream) r1 // Catch:{ all -> 0x001e }
r1.write(r3) // Catch:{ all -> 0x001e }
o.dF r3 = o.dF.f2032 // Catch:{ all -> 0x001e }
o.eY.m2182(r0, r2)
return
L_0x001e:
r2 = move-exception
throw r2 // Catch:{ all -> 0x0020 }
L_0x0020:
r3 = move-exception
o.eY.m2182(r0, r2)
throw r3
*/
throw new UnsupportedOperationException("Method not decompiled: o.C3403fe.m2290(java.io.File, byte[]):void");
}
/* JADX WARNING: Code restructure failed: missing block: B:10:0x002c, code lost:
throw r0;
*/
/* JADX WARNING: Code restructure failed: missing block: B:8:0x0028, code lost:
r0 = move-exception;
*/
/* JADX WARNING: Code restructure failed: missing block: B:9:0x0029, code lost:
o.eY.m2182(r1, r2);
*/
/* renamed from: ι reason: contains not printable characters */
/* Code decompiled incorrectly, please refer to instructions dump. */
public static final java.lang.String m2289(java.io.File r1, java.nio.charset.Charset r2) {
/*
java.lang.String r0 = ""
o.fM.m2254(r1, r0)
o.fM.m2254(r2, r0)
java.io.FileInputStream r0 = new java.io.FileInputStream
r0.<init>(r1)
java.io.InputStream r0 = (java.io.InputStream) r0
java.io.InputStreamReader r1 = new java.io.InputStreamReader
r1.<init>(r0, r2)
java.io.Closeable r1 = (java.io.Closeable) r1
r2 = 0
java.lang.Throwable r2 = (java.lang.Throwable) r2
r0 = r1
java.io.InputStreamReader r0 = (java.io.InputStreamReader) r0 // Catch:{ all -> 0x0026 }
java.io.Reader r0 = (java.io.Reader) r0 // Catch:{ all -> 0x0026 }
java.lang.String r0 = o.C3404ff.m2294(r0) // Catch:{ all -> 0x0026 }
o.eY.m2182(r1, r2)
return r0
L_0x0026:
r2 = move-exception
throw r2 // Catch:{ all -> 0x0028 }
L_0x0028:
r0 = move-exception
o.eY.m2182(r1, r2)
throw r0
*/
throw new UnsupportedOperationException("Method not decompiled: o.C3403fe.m2289(java.io.File, java.nio.charset.Charset):java.lang.String");
}
/* renamed from: ι$default reason: contains not printable characters */
public static /* synthetic */ String m2291$default(File file, Charset charset, int i, Object obj) {
if ((i & 1) != 0) {
charset = gL.f2204;
}
return C3401fc.m2289(file, charset);
}
/* renamed from: ɩ reason: contains not printable characters */
public static final void m2287(File file, String str, Charset charset) {
fM.m2254(file, "");
fM.m2254(str, "");
fM.m2254(charset, "");
byte[] bytes = str.getBytes(charset);
fM.m2252((Object) bytes, "");
C3401fc.m2290(file, bytes);
}
/* renamed from: ɩ$default reason: contains not printable characters */
public static /* synthetic */ void m2288$default(File file, String str, Charset charset, int i, Object obj) {
if ((i & 2) != 0) {
charset = gL.f2204;
}
C3401fc.m2287(file, str, charset);
}
}
| true
|
788fccb5d199982269909a69b46dd23c52763540
|
Java
|
kyusiks/probe
|
/src/main/java/com/probe/user/UserMainController.java
|
UTF-8
| 1,489
| 1.945313
| 2
|
[] |
no_license
|
package com.probe.user;
import java.util.List;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserMainController {
@Autowired
UserMainService userMainService;
@RequestMapping("/userMain")
public String userMain(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", "SpringBlog from Millky");
return "/user/userMain";
}
@RequestMapping("/userMain/searchAddressBySiDoNm")
@ResponseBody
public List<UserMainVo> searchAddressBySiDoNm(@RequestBody String body, Model model) {
JSONParser parser = new JSONParser();
String siDoNm = "";
try {
Object obj = parser.parse(body);
JSONObject jsonObj = (JSONObject)obj;
siDoNm = (String)jsonObj.get("siDoNm");
} catch (Exception e) {
e.printStackTrace();
}
List<UserMainVo> retList = userMainService.searchAddressBySiDoNm(siDoNm);
return retList;
}
}
| true
|
a4541145c8a28d87625009fc0444e58e65a35afa
|
Java
|
MobileSeoul/2018seoul-96
|
/Completion_Project/app/src/main/java/andbook/ecample/mun/pollution.java
|
UTF-8
| 2,181
| 2.046875
| 2
|
[] |
no_license
|
package andbook.ecample.mun;
import java.util.ArrayList;
/**
* Created by Administrator on 2018-05-03.
*/
public class pollution {
public String stationName="뭘가";
public String sidoName = ""; //도명
public String ssgName = "";//시 군 명
public String umdName = "";// 읍면동
public String tmX = ""; // 좌표 X
public String tmY = ""; // 좌표 Y
public ArrayList<String> tm = new ArrayList<String>(); // 측정소까지의 거리 |
public String ErrorCheck = ""; //| 값이 없을 때를 대비해 가까운 순으로 다른 측정소 이름도 어레이로 저장
public ArrayList<String> StationName = new ArrayList<String>(); //측정소 이름|
public String dataTime = ""; // 측정일
public String so2Value = ""; // 아황산가스 농도
public String coValue = ""; //일산화탄소 농도
public String o3Value = ""; //오존 농도
public String no2Value = ""; //이산화질소 농도
public String pm10Value = ""; //미세먼지(Pm10)농도
public String pm10Value24 = ""; //미세먼지 (pm10) 24시간 예측 이동농도
public String pm25Value = ""; //미세먼지(pm25) 농도
public String pm25Value24 = ""; //미세먼지(pm25) 농도
public String khaiValue = ""; //통합대기환경수치
public String khaiGrade = ""; //통합대기환경지수
public String so2Grade = ""; //아황산가스 지수
public String coGrade = ""; //일산화탄소 지수
public String o3Grade = ""; //오존 지수
public String no2Grade = ""; //이산화질소 지수
public String pm10Grade = ""; //미세먼지(Pm10) 24시간 등급
public String pm10Grade1h = ""; //미세먼지(Pm10) 1시간 등급
public String pm25Grade = ""; //미세먼지(Pm25) 24시간 등급
public ArrayList<String> pm25Grade1h = new ArrayList<>( ); //미세먼지(Pm25) 1시간 등급
public String dataTime1 ="";
public String dataTime2 ="";
public String dataTime3 ="";
public String informGrade1="";
public String informGrade2="";
public String informGrade3="";
}
| true
|
4d413a5a16296c8c758e3ce90061d25badfe0c36
|
Java
|
PatrickkZ/seminar_system
|
/src/main/java/com/loha/flippedclassroom/util/SortMap.java
|
UTF-8
| 594
| 2.84375
| 3
|
[] |
no_license
|
package com.loha.flippedclassroom.util;
import java.util.Iterator;
import java.util.Map;
public class SortMap {
public static Long getMapMaxKey(Map<Long,Integer> map){
Long maxKey=new Long(0);
Integer maxValue=0;
Iterator keys=map.keySet().iterator();
while (keys.hasNext()){
Object key=keys.next();
Integer value=Integer.parseInt(map.get(key).toString());
if(value>maxValue){
maxValue=value;
maxKey=Long.parseLong(key.toString());
}
}
return maxKey;
}
}
| true
|
af02a055d61c5204d8cb7bd45fd386c8fa631012
|
Java
|
lee1996/ResearchWebProject
|
/src/com/leet/manage/ManageProjectDao.java
|
UTF-8
| 2,383
| 2.453125
| 2
|
[] |
no_license
|
package com.leet.manage;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.leet.db.DBUtil;
public class ManageProjectDao {
public void addManage(ManageProject manpro) throws Exception{
Connection conn=DBUtil.getConnection();
String sql="insert into project_manage values(?,?,?);";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setString(1, manpro.getContract_id());
pre.setString(2, manpro.getUsername());
pre.setString(3,manpro.getProject_id());
pre.execute();
}
public void delManage(String con_id) throws Exception{
Connection conn=DBUtil.getConnection();
String sql="delete from project_manage where contract_id=?;";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setString(1, con_id);
pre.execute();
}
public ManageProject queryManage(String con_id) throws Exception{
Connection conn=DBUtil.getConnection();
String sql="select * from project_manage where contract_id=?;";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setString(1,con_id);
ManageProject manpro=new ManageProject();
ResultSet result=pre.executeQuery();
if(!result.next()){
return null;
}else{
manpro.setContract_id(con_id);
manpro.setProject_id(result.getString("project_id"));
manpro.setUsername(result.getString("username"));
return manpro;
}
}
public void updateManage(ManageProject manpro) throws Exception{
Connection conn=DBUtil.getConnection();
String sql="update project_manage set project_id=? where contract_id=?;";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setString(1, manpro.getProject_id());
pre.setString(2,manpro.getContract_id());
pre.execute();
}
public List<ManageProject> queryAll(String username) throws Exception{
Connection conn=DBUtil.getConnection();
List<ManageProject> list=new ArrayList<ManageProject>();
String sql="select contract_id,project_id from project_manage where username=?;";
PreparedStatement pre=conn.prepareStatement(sql);
pre.setString(1,username);
ResultSet result=pre.executeQuery();
ManageProject manpro=null;
while(result.next()){
manpro=new ManageProject();
manpro.setContract_id(result.getString("contract_id"));
manpro.setProject_id(result.getString("project_id"));
list.add(manpro);
}
return list;
}
}
| true
|
0dfedec36b440cf718a3311b35b359fa052f65ba
|
Java
|
vlasquez/JavaDesignPatterns
|
/src/design/principles/solid/openClose/IShape.java
|
UTF-8
| 101
| 2.0625
| 2
|
[] |
no_license
|
package design.principles.solid.openClose;
public interface IShape {
double calculateArea();
}
| true
|
ca3c5bc52164c4b0308d75a1bae1b486bb68ab55
|
Java
|
cping/RipplePower
|
/eclipse/RipplePower/src/org/ripple/power/RippleSeedAddress.java
|
UTF-8
| 1,067
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.ripple.power;
import java.util.HashMap;
public class RippleSeedAddress extends RippleIdentifier {
/**
*
*/
private static final long serialVersionUID = 1L;
private HashMap<Integer, RipplePrivateKey> _cache = new HashMap<Integer, RipplePrivateKey>(10);
public RippleSeedAddress(final byte[] payloadBytes) {
super(payloadBytes, 33);
}
public RippleSeedAddress(final String stringID) {
super(stringID);
}
public String getPublicKey() {
return getPublicRippleAddress().toString();
}
public String getPrivateKey() {
return toString();
}
public RipplePrivateKey getPrivateKey(int accountNumber) {
RipplePrivateKey signingPrivateKey = _cache.get(accountNumber);
if (signingPrivateKey == null) {
RippleGenerator generator = new RippleGenerator(payloadBytes);
signingPrivateKey = generator.getAccountPrivateKey(accountNumber);
_cache.put(accountNumber, signingPrivateKey);
}
return signingPrivateKey;
}
public RippleAddress getPublicRippleAddress() {
return getPrivateKey(0).getPublicKey().getAddress();
}
}
| true
|
78e6da1152a969f63d20d133588933dc8d493e87
|
Java
|
srj0x0/MVP_CF
|
/app/src/main/java/ua/vitamin/app/people_screen/PeopleScreenPresenter.java
|
UTF-8
| 833
| 2.125
| 2
|
[] |
no_license
|
package ua.vitamin.app.people_screen;
import android.util.Log;
import java.util.List;
import ua.vitamin.app.utils.Result;
public class PeopleScreenPresenter implements Contract.MainPresenter {
private static final String TAG = "PeopleScreenPresenter";
private Contract.MainView postScreenActivityView;
private PostScreenModel postScreenModel;
private List<Result> peopleList;
public PeopleScreenPresenter (Contract.MainView mainActivity) {
Log.d(TAG, "PeopleScreenPresenter()");
this.postScreenActivityView = mainActivity;
this.postScreenModel = new PostScreenModel();
}
@Override
public void onPostListLoad() {
Log.d(TAG, "onPostListLoad()");
peopleList = postScreenModel.loadPeople();
postScreenActivityView.onShowListPeople(peopleList);
}
}
| true
|
5257dd3f9cb6b5cefaa9c0bc35ab63e803306beb
|
Java
|
xuyuxin-star/WeiZiXun
|
/app/src/main/java/com/example/weizixun/common/Constants.java
|
UTF-8
| 231
| 1.757813
| 2
|
[] |
no_license
|
package com.example.weizixun.common;
public interface Constants {
//全局日志拦截器开关,只有debug模式才开启,上线以后关闭日志拦截器,为false
boolean IS_DEBUG=true;
String CACHE_NAME="cache";
}
| true
|
aeb6e6ef9341f48c6893dce823edff56d71f63d2
|
Java
|
dachrisch/LightningTalkTimer
|
/app/src/androidTest/java/com/muckibude/cda/lightningtalktimer/BackFragmentVariableRunTest.java
|
UTF-8
| 3,770
| 1.820313
| 2
|
[] |
no_license
|
package com.muckibude.cda.lightningtalktimer;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.muckibude.cda.lightningtalktimer.data.CountdownEntity;
import com.muckibude.cda.lightningtalktimer.domain.FrontModel;
import com.muckibude.cda.lightningtalktimer.injection.MockAppModule;
import com.muckibude.cda.lightningtalktimer.injection.TestAppComponentRule;
import com.muckibude.cda.lightningtalktimer.ui.BackCountdownDisplayFragment;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.assertThat;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static com.muckibude.cda.lightningtalktimer.matcher.TextViewMatcher.withTextOnView;
import static org.hamcrest.CoreMatchers.is;
@RunWith(AndroidJUnit4.class)
public class BackFragmentVariableRunTest {
@Rule
public final TestAppComponentRule componentRule = new TestAppComponentRule();
@Rule
public final ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
MainActivity.class, false, false);
private boolean blinkScreenInvoked = false;
private CountdownEntity minutesSecondsEntity;
@Before
@SuppressLint({"ValidFragment"})
public void mockModel() {
MockAppModule mockAppModule = componentRule.getMockAppModule();
minutesSecondsEntity = new CountdownEntity(0, 1);
mockAppModule.setOverrideFrontModel(new FrontModel(minutesSecondsEntity));
mockAppModule.setOverrideBackView(new BackCountdownDisplayFragment() {
@Override
public void blinkScreen() {
blinkScreenInvoked = true;
}
});
Intent intent = new Intent(getTargetContext(), MainActivity.class);
intent.putExtra("commitFragment", false);
mActivityRule.launchActivity(intent);
}
@Test
public void whenFinishedZeroSecondsDisplayed() throws InterruptedException {
onView(withId(R.id.minutes)).check(matches(withTextOnView("0")));
onView(withId(R.id.seconds)).check(matches(withTextOnView("01")));
onView(withId(R.id.startButton)).perform(click());
Thread.sleep(1500);
onView(withId(R.id.big_number_text_view)).check(matches(withTextOnView("0")));
onView(withId(R.id.small_number_text_view)).check(matches(withTextOnView("00")));
}
@Test
public void whenFinishedDisplayBlinks() throws InterruptedException {
onView(withId(R.id.minutes)).check(matches(withTextOnView("0")));
onView(withId(R.id.seconds)).check(matches(withTextOnView("01")));
onView(withId(R.id.startButton)).perform(click());
Thread.sleep(1500);
assertThat("blink screen not invoked", blinkScreenInvoked, is(true));
}
@Test
public void lastSecondOfAMinuteIsDisplayedAsMinuteWithZeroSeconds() throws InterruptedException {
minutesSecondsEntity.registerEntityChangeListener(null);
minutesSecondsEntity.updateFromMillis(61 * 1000);
onView(withId(R.id.startButton)).perform(click());
Thread.sleep(1100);
onView(withId(R.id.big_number_text_view)).check(matches(withTextOnView("1")));
onView(withId(R.id.small_number_text_view)).check(matches(withTextOnView("00")));
}
}
| true
|
8db3241f9e0d3afa47e02d6cd9e137685a700cc8
|
Java
|
sencae/e-learning-system
|
/e-learning-system-backend/src/main/java/com/e_learning_system/services/TopicsService.java
|
UTF-8
| 1,017
| 2.203125
| 2
|
[] |
no_license
|
package com.e_learning_system.services;
import com.e_learning_system.dao.TopicsRepository;
import com.e_learning_system.entities.TopicsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TopicsService {
private final TopicsRepository topicsRepository;
@Autowired
public TopicsService(TopicsRepository topicsRepository) {
this.topicsRepository = topicsRepository;
}
public TopicsEntity createTopic(TopicsEntity topicsEntity){
return topicsRepository.saveAndFlush(topicsEntity);
}
@Transactional
public void deleteTopic(TopicsEntity topicsEntity) {
topicsRepository.delete(topicsEntity);
}
public TopicsEntity save(TopicsEntity topicsEntity){
return topicsRepository.save(topicsEntity);
}
public TopicsEntity getById(Long id) {
return topicsRepository.getById(id);
}
}
| true
|
041820a46e54088f07dc41322b1e99be8f0123e2
|
Java
|
benliben/Day_03
|
/5.数据库中的事物/src/main/java/com/android/benben/a5/MainActivity.java
|
UTF-8
| 1,438
| 2.546875
| 3
|
[] |
no_license
|
package com.android.benben.a5;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.android.benben.a5.db.BankOpenHelper;
public class MainActivity extends AppCompatActivity {
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
}
public void transtation(View v){
/*创建一个帮助类对象*/
BankOpenHelper oPen = new BankOpenHelper(mContext);
/*调用数据库帮助类对象的getReadableDatabase创建数据库,初始化表数据,获取一个SqLiteDatabase对象去做砖帐*/
SQLiteDatabase db = oPen.getReadableDatabase();
/*转账*/
db.beginTransaction();//开启一个数据库事物
try{
db.execSQL("update account set money=money-2000 where name=?", new String[]{"蒋敏"});
db.execSQL("update account set money=money+2000 where name=?", new String[]{"李远雄"});
db.setTransactionSuccessful();//标记事物中的Sql语句全部执行成功执行
}finally {
db.endTransaction();//判断事物的标记是否成功,如果不成功,回滚错误之前那=的sql语句
}
}
}
| true
|
faffc84927305c45227745026ee83952d4be0ca6
|
Java
|
franzhill/stratifGUI
|
/src/main/java/utils/MyExceptionUtils.java
|
UTF-8
| 602
| 3.109375
| 3
|
[] |
no_license
|
package main.java.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author fhill
*/
public class MyExceptionUtils
{
/**
* Return messages of all chained cause exceptions of t, in a stack fashion
* @param t
* @return
*/
public static String getStackMessages(Throwable t)
{
List<String> stack = new ArrayList<String>();
while (t != null)
{ stack.add(t.getClass().getName() + " : " + t.getMessage());
t = t.getCause();
}
return StringUtils.join(stack, "\n");
}
}
| true
|
7ed0cced39708c85c2bb45c5492c54fd9837f61a
|
Java
|
jiuxiaosheng/code_wheel
|
/java-basic/src/main/java/com/acvoli/learning/leetcode/tree/SimpleBinaryTree.java
|
UTF-8
| 10,566
| 3.78125
| 4
|
[] |
no_license
|
package com.acvoli.learning.leetcode.tree;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Stack;
public class SimpleBinaryTree {
private TreeNode root = null;
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
// 查找, 二叉查找树才能这样用
public TreeNode findNode(int value) {
TreeNode current = root;
while (true) {
if (value == current.getValue()) {
return current;
} else if (value < current.getValue()) {
current = current.getLeftNode();
} else {
current = current.getRightNode();
}
if (current == null) {
return null;
}
}
}
// 插入
public String insert(int value) {
String result = "success";
TreeNode node = new TreeNode(value);
if (root == null) {
root = node;
root.setLeftNode(null);
root.setRightNode(null);
} else {
TreeNode current = root;
TreeNode parent = null;
while (true) {
if (value < current.getValue()) {
parent = current;
current = current.getLeftNode();
if (current == null) {
parent.setLeftNode(node);
break;
}
} else if (value > current.getValue()) {
parent = current;
current = current.getRightNode();
if (current == null) {
parent.setRightNode(node);
break;
}
} else {
result = "already having same value";
}
}
}
return result;
}
// 中序遍历递归操作,
// 中序遍历左子树、访问根节点、中序遍历右子树。
public void inOrderTraverse() {
inOrderTraverse(root);
}
private void inOrderTraverse(TreeNode node) {
if (node == null) {
return;
}
inOrderTraverse(node.getLeftNode());
node.display();
inOrderTraverse(node.getRightNode());
}
//中序遍历非递归操作
public void inOrderByStack() {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.getLeftNode();
}
if (!stack.isEmpty()) {
current = stack.pop();
current.display();
current = current.getRightNode();
}
}
}
//前序遍历,
//先序遍历, 访问根节点、先序遍历左子树、先序遍历右子树。
public void preOrderTraverse() {
preOrderTraverse(root);
}
private void preOrderTraverse(TreeNode node) {
if (node == null) {
return;
}
//打印表示遍历了该节点
node.display();
preOrderTraverse(node.getLeftNode());
preOrderTraverse(node.getRightNode());
}
//前序遍历非递归操作
public void preOrderByStack() {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
// 访问根节点
current.display();
// 把左节点押入栈中
current = current.getLeftNode();
}
if (!stack.isEmpty()) {
current = stack.pop();
current = current.getRightNode();
}
}
}
// 后序遍历
// 后序遍历:后续遍历左子树、后续遍历右子树、访问根节点。
public void postOrderTraverse() {
postOrderTraverse(root);
}
private void postOrderTraverse(TreeNode node) {
if (node == null) {
return;
}
postOrderTraverse(node.getLeftNode());
postOrderTraverse(node.getRightNode());
node.display();
}
//后序遍历非递归操作
public void postOrderByStack() {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
TreeNode preNode = null;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.getLeftNode();
}
if (!stack.isEmpty()) {
current = stack.peek().getRightNode();
if (current == null || current == preNode) {
current = stack.pop();
current.display();
preNode = current;
current = null;
}
}
}
}
// 获取最大值
public int getMaxValue() {
return 0;
}
// 获取最小值
public int getMinValue() {
return 0;
}
// 删除
public boolean delete(int value) {
TreeNode current = root;
TreeNode parent = null;
boolean isLeftNode = true;
while (true) {
if (value == current.getValue()) {
break;
} else if (value < current.getValue()) {
isLeftNode = true;
parent = current;
current = current.getLeftNode();
} else {
isLeftNode = false;
parent = current;
current = current.getRightNode();
}
}
if (current == null) {
return false;
}
// 需要删除的节点为叶子节点
if (current.getLeftNode() == null && current.getRightNode() == null) {
if (current == root) {
root = null;
} else if (parent != null) {
if (isLeftNode) {
parent.setLeftNode(null);
} else {
parent.setRightNode(null);
}
}
}
// 需要删除的节点有一个子节点,且该子节点为左子节点
else if (current.getRightNode() == null) {
if (current == root) {
root = root.getLeftNode();
} else if (parent != null) {
//如果该节点是父节点的左子节点,将该节点的左子节点变为父节点的左子节点
if (isLeftNode) {
parent.setLeftNode(current.getLeftNode());
}
//如果该节点是父节点的右子节点,将该节点的左子节点变为父节点的右子节点
else {
parent.setRightNode(current.getLeftNode());
}
}
}
// 需要删除的节点有一个子节点,且该子节点为右子节点
else if (current.getLeftNode() == null) {
if (current == root) {
root = current.getRightNode();
} else if (parent != null) {
//如果该节点是父节点的左子节点,将该节点的右子节点变为父节点的左子节点
if (isLeftNode) {
parent.setLeftNode(current.getRightNode());
}
//如果该节点是父节点的右子节点,将该节点的右子节点变为父节点的右子节点
else {
parent.setRightNode(current.getRightNode());
}
}
}
// 需要删除的节点有两个子节点,需要寻找该节点的后续节点替代删除节点
else {
TreeNode successor = getSuccessor(current);
if (current == root) {
root = successor;
} else if (parent != null) {
//如果该节点是父节点的左子节点,将该节点的后继节点变为父节点的左子节点
if (isLeftNode) {
parent.setLeftNode(successor);
}
//如果该节点是父节点的右子节点,将该节点的后继节点变为父节点的右子节点
else {
parent.setRightNode(successor);
}
}
}
return true;
}
private TreeNode getSuccessor(TreeNode delNode) {
TreeNode successor = delNode;
TreeNode successorParent = null;
TreeNode current = delNode.getRightNode();
while (current != null) {
successorParent = successor;
successor = current;
current = current.getLeftNode();
}
// 如果后继节点不是删除节点的右子节点时
if (successor != delNode.getRightNode() && successorParent != null) {
//要将后继节点的右子节点指向后继结点父节点的左子节点,
successorParent.setLeftNode(successor.getRightNode());
//并将删除节点的右子节点指向后继结点的右子节点
successor.setRightNode(delNode.getRightNode());
}
//任何情况下,都需要将删除节点的左子节点指向后继节点的左子节点
successor.setLeftNode(delNode.getLeftNode());
return successor;
}
public static class TreeNode {
private TreeNode leftNode;
private TreeNode rightNode;
private int value;
public TreeNode() {
}
public TreeNode(int value) {
this.value = value;
}
// display做为遍历访问了该节点
public void display() {
System.out.print(value + "\t");
}
public TreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public TreeNode getRightNode() {
return rightNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
| true
|
91ae3ab9643399b023c4ec03988a810a9109fb35
|
Java
|
zhangwei9757/xiaocaibao
|
/game8/xxkg/src/main/java/com/tumei/game/protos/group/RequestGroupGetSceneAwards.java
|
UTF-8
| 1,674
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tumei.game.protos.group;
import com.tumei.common.RemoteService;
import com.tumei.common.webio.AwardStruct;
import com.tumei.game.GameUser;
import com.tumei.model.GroupBean;
import com.tumei.model.beans.AwardBean;
import com.tumei.websocket.BaseProtocol;
import com.tumei.websocket.WebSocketUser;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/3/13 0013.
* 请求公会推荐列表
*/
@Component
public class RequestGroupGetSceneAwards extends BaseProtocol {
public int seq;
// 阵营[1,4]
public int index;
class ReturnGroupGetSceneAwards extends BaseProtocol {
public int seq;
public String result = "";
public List<AwardBean> awards = new ArrayList<>();
}
@Override
public void onProcess(WebSocketUser session) {
GameUser user = (GameUser)session;
ReturnGroupGetSceneAwards rl = new ReturnGroupGetSceneAwards();
rl.seq = seq;
GroupBean gb = user.getDao().findGroup(user.getUid());
if (gb.getGid() > 0) {
try {
if (gb.getFetch()[index - 1] == 1) {
rl.result = "奖励已经领取";
} else {
// 远程控制副本进度和当前副本关卡
AwardStruct gss = RemoteService.getInstance().askGroupGetSceneAwards(gb.getGid(), user.getUid(), index);
if (gss != null) {
gb.getFetch()[index - 1] = 1;
rl.awards.addAll(user.addItem(gss.id, gss.count, false, "公会阵营奖励"));
} else {
rl.result = "无法获取本章副本对应阵营的奖励";
}
}
} catch (Exception ex) {
rl.result = "无法获取本章副本对应阵营的奖励";
}
}
user.send(rl);
}
}
| true
|
e8ec59eb371ecf2202d5bc5dcbec97accb5c1a22
|
Java
|
adicomdotir/Just-Java
|
/QueraQuestion/16691/report/ReportService.java
|
UTF-8
| 4,735
| 3.125
| 3
|
[] |
no_license
|
package ir.javacup.report;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ReportService {
private List<Information> allList = new ArrayList<>();
public ReportService(InformationRepository repository) {
allList = repository.fetchAll();
}
public List<CityInformation> sumByCity(int year) {
List<CityInformation> temp = new ArrayList<>();
for (Information information : allList) {
if (information.getDate().substring(0, 4).equals("" + year)) {
if (temp.size() == 0) {
CityInformation ci = new CityInformation();
ci.setCity(information.getCity());
ci.setSum(information.getAmount());
temp.add(ci);
} else {
boolean exist = true;
for (CityInformation cityInformation : temp) {
if (cityInformation.getCity().equals(information.getCity())) {
exist = true;
cityInformation.setSum(cityInformation.getSum() + information.getAmount());
break;
} else {
exist = false;
}
}
if (!exist) {
CityInformation ci = new CityInformation();
ci.setCity(information.getCity());
ci.setSum(information.getAmount());
temp.add(ci);
}
}
}
}
Collections.sort(temp, new CityInformationComparator());
return temp;
}
public List<CityMonthInformation> averageByCityAndMonth(int year) {
List<CityMonthInformation> temp = new ArrayList<>();
for (Information information : allList) {
if (information.getDate().substring(0, 4).equals("" + year)) {
if (temp.size() == 0) {
CityMonthInformation ci = new CityMonthInformation();
ci.setCity(information.getCity());
ci.setMonth(Integer.parseInt(information.getDate().substring(5, 7)));
ci.setAverage(information.getAmount());
temp.add(ci);
} else {
boolean exist = true;
for (CityMonthInformation cmi : temp) {
if (cmi.getCity().equals(information.getCity()) && cmi.getMonth() == Integer.parseInt(information.getDate().substring(5, 7))) {
exist = true;
cmi.setAverage(cmi.getAverage() + information.getAmount());
break;
} else {
exist = false;
}
}
if (!exist) {
CityMonthInformation ci = new CityMonthInformation();
ci.setCity(information.getCity());
ci.setMonth(Integer.parseInt(information.getDate().substring(5, 7)));
ci.setAverage(information.getAmount());
temp.add(ci);
}
}
}
}
for (CityMonthInformation cmi : temp) {
if (cmi.getMonth() <= 6) {
cmi.setAverage(cmi.getAverage() / 31);
} else {
cmi.setAverage(cmi.getAverage() / 30);
}
}
Collections.sort(temp, new CityMonthInformationComparator());
return temp;
}
public static void main(String[] args) {
ReportService service = new ReportService(new InformationRepository() {
@Override
public List<Information> fetchAll() {
return Arrays.asList(
new Information("Kerman", "1395/03/11", 62L), new Information("Tehran", "1395/09/12", 90L),
new Information("Tehran", "1396/11/30", 31L), new Information("Semnan", "1396/01/13", 93L)
);
}
});
List<CityInformation> sumResults = service.sumByCity(1396);
System.out.printf("sum total: %d%n", sumResults.size());
CityInformation sumFirst = sumResults.get(0);
System.out.printf("1: %s %d%n", sumFirst.getCity(), sumFirst.getSum());
CityInformation sumSecond = sumResults.get(1);
System.out.printf("2: %s %d%n", sumSecond.getCity(), sumSecond.getSum());
List<CityMonthInformation> avgResults = service.averageByCityAndMonth(1395);
System.out.printf("avg total: %d%n", avgResults.size());
CityMonthInformation avgFirst = avgResults.get(0);
System.out.printf("1: %s %d %f%n", avgFirst.getCity(), avgFirst.getMonth(), avgFirst.getAverage());
CityMonthInformation avgSecond = avgResults.get(1);
System.out.printf("2: %s %d %f%n", avgSecond.getCity(), avgSecond.getMonth(), avgSecond.getAverage());
}
class CityInformationComparator implements Comparator<CityInformation> {
@Override
public int compare(CityInformation ci1, CityInformation ci2) {
return ci1.getCity().compareTo(ci2.getCity());
}
}
class CityMonthInformationComparator implements Comparator<CityMonthInformation> {
@Override
public int compare(CityMonthInformation ci1, CityMonthInformation ci2) {
String x1 = ci1.getCity();
String x2 = ci2.getCity();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
Integer x10 = ci1.getMonth();
Integer x20 = ci1.getMonth();
return x10.compareTo(x20);
}
}
}
| true
|
da415d1705822f657c0f27e483bd24f78ea07ba3
|
Java
|
chenxxin/ThreadDemo
|
/src/stack_queue/StackToQueueTest.java
|
UTF-8
| 725
| 3.328125
| 3
|
[] |
no_license
|
package stack_queue;
import java.util.Stack;
/**
* Created by xin on 2016/5/16.
*/
//用两个栈实现队列
public class StackToQueueTest<T> {
private Stack<T> stack1;
private Stack<T> stack2;
public StackToQueueTest(Stack<T> stack1, Stack<T> stack2) {
this.stack1 = stack1;
this.stack2 = stack2;
}
public void appendTail(T node){
stack1.push(node);
}
public T deleteHead(){
if (stack2.empty()){
while (stack1.size()>0){
stack2.push(stack1.pop());
}
}
if (stack2.empty()){
System.out.println("Quene is empty!");
System.exit(0);
}
return stack2.pop();
}
}
| true
|
7521089e55651185f484848913bd9a0d8eb0c9f7
|
Java
|
hifito/To-Do-List-with-Login-Register
|
/app/src/main/java/com/example/todolistwithloginregister/UpdateTaskAct.java
|
UTF-8
| 2,299
| 2.171875
| 2
|
[] |
no_license
|
package com.example.todolistwithloginregister;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.todolistwithloginregister.utils.DatabaseHandler;
public class UpdateTaskAct extends AppCompatActivity {
TextView titlepage, addtitle, adddesc, adddate;
EditText titledoes, descdoes, datedoes;
Button btnDelete, btnUpdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_task);
btnDelete = findViewById(R.id.btnDelete);
btnUpdate = findViewById(R.id.btnUpdate);
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
databaseHandler.openDatabase();
Bundle data = getIntent().getExtras();
if(data != null) {
String title = data.getString("title");
String desc = data.getString("desc");
String date = data.getString("date");
titledoes = findViewById(R.id.titledoes);
descdoes = findViewById(R.id.descdoes);
datedoes = findViewById(R.id.datedoes);
titledoes.setText(title);
descdoes.setText(desc);
datedoes.setText(date);
}
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
databaseHandler.updateTask(data.getInt("id"), titledoes.getText().toString(), datedoes.getText().toString(), descdoes.getText().toString());
Intent intent = new Intent(UpdateTaskAct.this, com.example.todolistwithloginregister.MainActivity.class);
startActivity(intent);
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
databaseHandler.deleteTask(data.getInt("id"));
Intent intent = new Intent(UpdateTaskAct.this, com.example.todolistwithloginregister.MainActivity.class);
startActivity(intent);
}
});
}
}
| true
|
179f166bd07b195bd8a0bc5818b7c3c17d2b2ffd
|
Java
|
adrian-wi/goeuro-task
|
/src/main/java/com/goeuro/GoEuroApplication.java
|
UTF-8
| 1,396
| 2.15625
| 2
|
[] |
no_license
|
package com.goeuro;
import com.goeuro.domain.City;
import com.goeuro.service.CityLocationService;
import com.goeuro.service.CsvWriterService;
import com.goeuro.service.InputValidator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.List;
@SpringBootApplication
@EnableAsync
public class GoEuroApplication implements CommandLineRunner {
private static final Logger LOGGER = Logger.getLogger(GoEuroApplication.class);
@Autowired
private CityLocationService cityLocationService;
@Autowired
private CsvWriterService csvWriterService;
@Autowired
private InputValidator inputValidator;
@Override
public void run(String... args) {
try {
inputValidator.validateInput(args);
List<City> cities = cityLocationService.queryRemoteService(args[0]);
csvWriterService.write(cities);
} catch (Exception ex) {
LOGGER.info("The following problem occurred:" + ex.getMessage(), ex);
}
}
public static void main(String[] args) {
SpringApplication.run(GoEuroApplication.class, args);
}
}
| true
|
88b66979079ec822b85c206272ace533b9327cb8
|
Java
|
AsafLe5/Easy-Differentiate
|
/src/Plus.java
|
UTF-8
| 2,901
| 3.765625
| 4
|
[] |
no_license
|
import java.util.Map;
/**
* 205543317.
*/
public class Plus extends BinaryExpression implements Expression {
/**
* Initialize the expression with his format.
*
* @param expression1 first expression.
* @param expression2 second expression.
*/
public Plus(Expression expression1, Expression expression2) {
super("(%s + %s)", expression1, expression2);
}
/**
* Evaluate the expression.
*
* @param assignment Mapping var to their values.
* @return the var's
* @throws Exception no needed.
*/
public double evaluate(Map<String, Double> assignment) throws Exception {
return super.getExpression1().evaluate(assignment) + super.getExpression2().evaluate(assignment);
}
/**
* Evaluate the expression.
*
* @return the var's
* @throws Exception no needed.
*/
public double evaluate() throws Exception {
return super.getExpression1().evaluate() + super.getExpression2().evaluate();
}
/**
* Assign the var's given expressions.
*
* @param var a variable.
* @param expression an Expression.
* @return a new expression in which all occurrences of the variable
* var are replaced with the provided expression.
*/
public Expression assign(String var, Expression expression) {
return new Plus(super.getExpression1().assign(var, expression), super.getExpression2().assign(var, expression));
}
/**
* differentiating the current expression.
*
* @param var a variable.
* @return the expression tree resulting from differentiating
* the current expression relative to variable `var`.
*/
public Expression differentiate(String var) {
return new Plus(super.getExpression1().differentiate(var), super.getExpression2().differentiate(var));
}
/**
* Simplifying the expression,
* if its plus zero its the same expression,
* if its zero plus something then its still the same expression.
*
* @return a simplified version of the current expression.
*/
public Expression simplify() {
if (this.getVariables().isEmpty()) {
try {
return new Num(this.evaluate());
} catch (Exception e) {
System.out.println("Error");
}
}
if (super.getExpression1().simplify().toString().equals("0")
|| super.getExpression1().simplify().toString().equals("0.0")) {
return super.getExpression2().simplify();
}
if (super.getExpression2().simplify().toString().equals("0")
|| super.getExpression2().simplify().toString().equals("0.0")) {
return super.getExpression1().simplify();
}
return new Plus(super.getExpression1().simplify(), super.getExpression2().simplify());
}
}
| true
|
3aa206254e2f1e29ed87daf6473c744f4823ef55
|
Java
|
jemxz/java-algorithm-practice
|
/practise-questions/ZeroBalanced.java
|
UTF-8
| 906
| 3.9375
| 4
|
[] |
no_license
|
/*
11. An array is called zero-balanced if its elements sum to 0 and for each positive
element n, there exists another element that is the negative of n. Write a function named
isZeroBalanced that returns 1 if its argument is a zero-balanced array. Otherwise it
returns 0.
*/
public class ZeroBalanced {
public static void main(String[] args){
int[] x = {};
System.out.println(f(x));
}
public static int f(int[] a){
// take care of special cases
if(a.length==0)
return 0;
for(int i=0; i<a.length; i++){
int target = a[i];
int positiveCount = 0;
int negativeCount = 0;
// calculate positiveCount and negativeCount
for(int j=0; j<a.length; j++){
if(a[j]==target)
positiveCount++;
if(a[j]==-target)
negativeCount++;
}
if(negativeCount!=positiveCount)
return 0;
}
return 1;
}
}
| true
|
c9d00d3267a9b32ae656b7fab972000ef099cfb7
|
Java
|
raju525525/spring-boot-integration-test1
|
/src/test/java/com/springboot/testrunner/E2eJunitSuiteRunner.java
|
UTF-8
| 406
| 1.765625
| 2
|
[
"MIT"
] |
permissive
|
package com.springboot.testrunner;
import com.springboot.Application;
import org.jsmart.zerocode.core.runner.ZeroCodePackageRunner;
import org.junit.runners.model.InitializationError;
public class E2eJunitSuiteRunner extends ZeroCodePackageRunner {
static{
Application.start();
}
public E2eJunitSuiteRunner(Class<?> klass) throws InitializationError {
super(klass);
}
}
| true
|
36c5fc33eb24a5bd9001764ab8e49518bfc801f4
|
Java
|
RealJasomo/JavaJoust
|
/JavaJoust/src/entities/InvincibleTimerEvent.java
|
UTF-8
| 417
| 2.359375
| 2
|
[] |
no_license
|
package entities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class InvincibleTimerEvent implements ActionListener {
Player player;
public InvincibleTimerEvent(Player player) {
// TODO Auto-generated constructor stub
this.player = player;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
player.stopInvincibility();
}
}
| true
|
069e3949636445c01fefc9ef1d58e73062fcb478
|
Java
|
mzkaramat/AlternateRouteMetro
|
/app/src/main/java/route/alternate/xeaphii/com/alternateroute/TrainClassesAdapter.java
|
UTF-8
| 2,612
| 2.109375
| 2
|
[] |
no_license
|
package route.alternate.xeaphii.com.alternateroute;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Administrator on 8/31/2015.
*/
public class TrainClassesAdapter extends BaseAdapter
{
private Context mContext;
private int mSelectedVariation;
String[] AvailableClasses;
Dialog dialog;
Button BtToSave;
@Override
public long getItemId(int position) {
return position;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getCount() {
return AvailableClasses.length;
}
public TrainClassesAdapter(Context context, int selectedVariation,String[] AvailableClasses,Dialog d,Button temp1)
{
mContext = context;
mSelectedVariation = selectedVariation;
this.AvailableClasses = AvailableClasses;
this.dialog = d;
this.BtToSave = temp1;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view==null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.train_class_list_item, null);
}
TextView name = (TextView) view.findViewById(R.id.class_name);
RadioButton radio = (RadioButton) view.findViewById(R.id.class_checkbox);
name.setText(AvailableClasses[position]);
if(position==mSelectedVariation) radio.setChecked(true);
else radio.setChecked(false);
radio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedVariation = position;
TrainClassesAdapter.this.notifyDataSetChanged();
dialog.dismiss();
BtToSave.setText(AvailableClasses[position]);
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedVariation = position;
TrainClassesAdapter.this.notifyDataSetChanged();
dialog.dismiss();
BtToSave.setText(AvailableClasses[position]);
}
});
return view;
}
}
| true
|
333de9e819d7dfdc214b22c05ac9a8b43790b5dd
|
Java
|
dparada8817/paisa-flix-programacion
|
/src/main/java/io/swagger/api/SerieApi.java
|
UTF-8
| 5,649
| 2.15625
| 2
|
[] |
no_license
|
package io.swagger.api;
import io.swagger.model.Capitulo;
import io.swagger.model.Serie;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2017-11-09T01:33:59.673Z")
@Api(value = "serie", description = "the serie API")
public interface SerieApi {
@ApiOperation(value = "Consultar capitulo por id", notes = "Con el parametro adecuado busca un capitulo ", response = Object.class, tags={ "administradores","programadores","clientes", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resultado de la busqueda", response = Object.class),
@ApiResponse(code = 400, message = "Parametros de entrada erroneos", response = Object.class) })
@RequestMapping(value = "/serie/{idSerie}/capitulo/{idCapitulo}",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<Object> buscarCapituloPorId(@ApiParam(value = "Ingrese el id del capitulo por el cual desea buscar",required=true ) @PathVariable("idCapitulo") String idCapitulo,
@ApiParam(value = "Ingrese el id de la serie por el cual desea buscar",required=true ) @PathVariable("idSerie") String idSerie);
@ApiOperation(value = "Consultar todos los capitulos por id de serie", notes = "Con el parametro adecuado busca todos los capitulos de la serie ", response = Capitulo.class, responseContainer = "List", tags={ "administradores","programadores","clientes", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resultado de la busqueda", response = Capitulo.class),
@ApiResponse(code = 400, message = "Parametros de entrada erroneos", response = Capitulo.class) })
@RequestMapping(value = "/serie/{idSerie}/capitulo",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<Capitulo>> buscarCapitulosPorIdSerie(@ApiParam(value = "Ingrese el id de la serie por el cual desea buscar",required=true ) @PathVariable("idSerie") String idSerie);
@ApiOperation(value = "Consultar series disponibles", notes = "Consulta todas las series ", response = Serie.class, responseContainer = "List", tags={ "administradores","programadores","clientes", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resultados de la busqueda", response = Serie.class),
@ApiResponse(code = 400, message = "Parametros de entrada erroneos", response = Serie.class) })
@RequestMapping(value = "/serie",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<Serie>> buscarSerie();
@ApiOperation(value = "Consultar serie por id", notes = "Con el parametro adecuado busca una serie ", response = Object.class, tags={ "administradores","programadores","clientes", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resultado de la busqueda", response = Object.class),
@ApiResponse(code = 400, message = "Parametros de entrada erroneos", response = Object.class) })
@RequestMapping(value = "/serie/{id}",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<Object> buscarSeriePorId(@ApiParam(value = "Ingrese el id por el cual desea buscar",required=true ) @PathVariable("id") String id);
@ApiOperation(value = "Crea/Actualiza un capitulo", notes = "Crea/Actualiza un capitulo", response = Void.class, tags={ "administradores", })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Capitulo Creado/Actualizado", response = Void.class),
@ApiResponse(code = 400, message = "Entrada erronea, objeto no válido", response = Void.class) })
@RequestMapping(value = "/serie/{idSerie}/capitulo/{idCapitulo}",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.PUT)
ResponseEntity<Void> crearActualizarCapitulo(@ApiParam(value = "Ingrese el id del capitulo por el cual desea actualizar",required=true ) @PathVariable("idCapitulo") String idCapitulo,
@ApiParam(value = "Ingrese el id de la serie por el cual desea actualizar",required=true ) @PathVariable("idSerie") String idSerie,
@ApiParam(value = "Capitulo a crear" ) @RequestBody Capitulo capitulo);
@ApiOperation(value = "Crea/Actualiza una serie", notes = "Crea/Actualiza una serie", response = Void.class, tags={ "administradores", })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Serie Creada/Actualizada", response = Void.class),
@ApiResponse(code = 400, message = "Entrada erronea, objeto no válido", response = Void.class) })
@RequestMapping(value = "/serie/{id}",
produces = { "application/json" },
consumes = { "application/json" },
method = RequestMethod.PUT)
ResponseEntity<Void> crearActualizarSerie(@ApiParam(value = "Ingrese el id que desea actualizar",required=true ) @PathVariable("id") String id,
@ApiParam(value = "Serie a crear" ) @RequestBody Serie serie);
}
| true
|
d69118d1fe8305b2c9eaa9a773268efdd4930511
|
Java
|
Fonzeca/Tercera-Nota-AED2
|
/src/estructura/Nodo.java
|
UTF-8
| 464
| 2.921875
| 3
|
[] |
no_license
|
package estructura;
public class Nodo {
NodoHuffman info;
Nodo ref;
public Nodo(byte info, Nodo ref) {
this.info = new NodoHuffman(info);
this.ref = ref;
}
public Nodo(NodoHuffman info,Nodo ref){
this.info = info;
this.ref = ref;
}
public NodoHuffman getInfo() {
return info;
}
public void setInfo(NodoHuffman info) {
this.info = info;
}
public Nodo getRef() {
return ref;
}
public void setRef(Nodo ref) {
this.ref = ref;
}
}
| true
|
cd2b0034880730067c450b238404f81323687a71
|
Java
|
NicholasZhaoSier/BookStore
|
/src/com/lanou/user/service/UserService.java
|
UTF-8
| 213
| 1.851563
| 2
|
[] |
no_license
|
package com.lanou.user.service;
import com.lanou.user.domian.User;
import java.util.List;
public interface UserService {
boolean regist(User user);
List<User> login(String username, String password);
}
| true
|
4ff395b9e49ea31da0085eaf49083d9180479e42
|
Java
|
IcedCrescent/MusicAppDownload
|
/app/src/main/java/com/example/trungspc/musicapp/adapters/TopSongAdapter.java
|
UTF-8
| 2,762
| 2.109375
| 2
|
[] |
no_license
|
package com.example.trungspc.musicapp.adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.trungspc.musicapp.R;
import com.example.trungspc.musicapp.database.TopSongModel;
import com.example.trungspc.musicapp.events.OnClickTopSong;
import com.squareup.picasso.Picasso;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.picasso.transformations.CropCircleTransformation;
public class TopSongAdapter extends RecyclerView.Adapter<TopSongAdapter.TopSongViewHolder> {
List<TopSongModel> topSongModels = new ArrayList<>();
public TopSongAdapter(List<TopSongModel> topSongModels) {
this.topSongModels = topSongModels;
}
@NonNull
@Override
public TopSongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.item_list_topsong, parent, false);
return new TopSongViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull TopSongViewHolder holder, int position) {
holder.setData(topSongModels.get(position));
}
@Override
public int getItemCount() {
return topSongModels.size();
}
public class TopSongViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.iv_topsong)
ImageView ivTopSong;
@BindView(R.id.tv_song)
TextView tvSong;
@BindView(R.id.tv_artist)
TextView tvArtist;
public TopSongViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void setData(final TopSongModel topSongModel) {
if (topSongModel.getImage() == null) {
Picasso.get().load(R.drawable.no_network).transform(new CropCircleTransformation()).into(ivTopSong);
} else {
Picasso.get().load(topSongModel.getImage()).transform(new CropCircleTransformation()).into(ivTopSong);
}
tvSong.setText(topSongModel.getSong());
tvArtist.setText(topSongModel.getArtist());
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().postSticky(new OnClickTopSong(topSongModel));
}
});
}
}
}
| true
|
b27e3f62a0d93d94143b18723359c4066015b673
|
Java
|
mask-hao/MvpReader
|
/app/src/main/java/com/zhanghao/reader/ui/adapter/base/ComViewHolder.java
|
UTF-8
| 2,919
| 2.078125
| 2
|
[] |
no_license
|
package com.zhanghao.reader.ui.adapter.base;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.zhanghao.reader.R;
import com.zhanghao.reader.contract.GankDailyAllContract;
import com.zhanghao.reader.ui.view.GankPicTransformation;
/**
* Created by zhanghao on 2016/11/21.
*/
public class ComViewHolder extends RecyclerView.ViewHolder{
private SparseArray<View> mViews;
private View mConvertView;
private Context context;
public ComViewHolder(Context context, View itemView) {
super(itemView);
this.mConvertView=itemView;
this.context=context;
mViews=new SparseArray<>();
}
public static ComViewHolder createViewHolder(Context context, ViewGroup parent, int layoutId){
View itemView= LayoutInflater.from(context).inflate(layoutId,parent,false);
ComViewHolder holder=new ComViewHolder(context,itemView);
return holder;
}
public static ComViewHolder createViewHolder(Context context, View itemView){
ComViewHolder holder=new ComViewHolder(context,itemView);
return holder;
}
/**
* 通过控件获取控件
* @param ViewId
* @param <T>
* @return
*/
public <T extends View> T getView(int ViewId){
View view =mViews.get(ViewId);
if (view==null){
view=mConvertView.findViewById(ViewId);
mViews.put(ViewId,view);
}
return (T) view;
}
public View getConvertView(){
return mConvertView;
}
public ComViewHolder setText(int viewId,String text){
TextView textView=getView(viewId);
textView.setText(text);
return this;
}
public ComViewHolder setTextAutoAdapter(int viewId, String text){
TextView textView=getView(viewId);
ViewGroup.LayoutParams lp=textView.getLayoutParams();
lp.height= ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(lp);
textView.setText(text);
return this;
}
public ComViewHolder setImageResource(int viewId,String path){
ImageView imageView=getView(viewId);
Picasso.with(context)
.load(path)
.into(imageView);
return this;
}
public ComViewHolder setGankImageResource(int viewId,String path){
ImageView imageView=getView(viewId);
Picasso.with(context)
.load(path)
.placeholder(R.drawable.default_pic_content_image_loading_light)
.transform(new GankPicTransformation(imageView))
.into(imageView);
return this;
}
}
| true
|
304cf076c84d20201839b306cf64485661cec50f
|
Java
|
SonaGamaryan/ATM_Tasks
|
/ATM3.1_UnitTest/junit-maven/src/test/java/CalculatorIsNegativeTest.java
|
UTF-8
| 875
| 2.859375
| 3
|
[] |
no_license
|
import com.epam.tat.module4.Calculator;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Created by Sona_Gamaryan on 6/7/2017.
*/
public class CalculatorIsNegativeTest {
@Test
public void testIsNegativePositiveValue(){
Calculator calculator = new Calculator();
boolean result = calculator.isNegative(30);
System.out.println(result);
assertTrue(result == false);
}
@Test
public void testIsNegativeNetativeValue(){
Calculator calculator = new Calculator();
boolean result = calculator.isNegative(-9);
System.out.println(result);
assertTrue(result == true);
}
@Test
public void testIsNegative0Value(){
Calculator calculator = new Calculator();
boolean result = calculator.isNegative(0);
assertTrue(result == false);
}
}
| true
|
18ca142bdfa2502e57984f371342173ee440ba7e
|
Java
|
lsst-camera-dh/portal-web
|
/src/main/java/org/lsst/camera/portal/data/HdwStatusLoc.java
|
UTF-8
| 4,150
| 2.15625
| 2
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* 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 org.lsst.camera.portal.data;
import java.util.Date;
import java.util.HashMap;
/**
*
* @author heather
*/
public class HdwStatusLoc {
private String lsstId;
private String status;
private String location;
private String site;
private java.util.Date creationDate;
private String curTravelerName;
private String curActivityProcName;
private String curActivityStatus;
private java.util.Date curTravBeginTime;
private java.util.Date curActivityLastTime;
private long elapsedTravTime;
private Boolean inNCR;
private HashMap<Integer,String> labelMap = new HashMap<>();
public void setLsstId(String id) {
lsstId = id == null || "".equals(id) ? "NA" : id;
}
public void setStatus(String s) {
status = s == null || "".equals(s) ? "NA" : s;
}
public void setLocation(String l) {
location = l == null || "".equals(l) ? "NA" : l;
}
public void setSite(String l) {
location = l == null || "".equals(l) ? "NA" : l;
}
public void setCreationDate(Date l) {
creationDate = l;
}
public void setCurTravelerName(String l) {
curTravelerName = l == null || "".equals(l) ? "NA" : l;
}
public void setCurActivityProcName(String l) {
curActivityProcName = l == null || "".equals(l) ? "NA" : l;
}
public void setCurActivityStatus(String l) {
curActivityStatus = l == null || "".equals(l) ? "NA" : l;
}
public void setCurActivityLastTime(Date l) {
curActivityLastTime = l;
}
public void setTravBeginTime(Date l) {
curTravBeginTime = l;
}
public void setValues(String id, String stat, String loc, String s, Date c, String name,
String actName, String actStat, Date actLastTime, Date travBeginTime, Boolean ncr) {
lsstId = id == null || "".equals(id) ? "NA" : id;
status = stat == null || "".equals(stat) ? "NA" : stat;
location = loc == null || "".equals(loc) ? "NA" : loc;
site = s == null || "".equals(s) ? "NA" : s;
creationDate = c;
curTravelerName = name == null || "".equals(name) ? "NA" : name;
curActivityProcName = actName == null || "".equals(actName) ? "NA" : actName;
curActivityStatus = actStat == null || "".equals(actStat) ? "NA" : actStat;
curTravBeginTime = travBeginTime;
curActivityLastTime = actLastTime;
inNCR = ncr;
}
public void setLabelMap(HashMap<Integer,String> labels) {
if (!labels.isEmpty()) labelMap.putAll(labels);
}
public HashMap<Integer,String> getLabelMap() {
return labelMap;
}
public String getLabel(Integer labelId) {
return labelMap.get(labelId);
}
public String getLsstId() {
return lsstId;
}
public String getStatus() {
return status;
}
public String getLocation() {
return location;
}
public String getSite() {
return site;
}
public Date getCreationDate() {
return creationDate;
}
public String getCurTravelerName() {
return curTravelerName;
}
public String getCurActivityProcName() {
return curActivityProcName;
}
public String getCurActivityStatus(){
return curActivityStatus;
}
public Date getCurActivityLastTime(){
return curActivityLastTime;
}
public Date getCurTravBeginTime () {
return curTravBeginTime;
}
public long getElapsedTravTime() {
long secondsInMilli = 1000;
if (curTravBeginTime != null && curActivityLastTime != null)
return ( (curActivityLastTime.getTime() - curTravBeginTime.getTime()) / secondsInMilli );
else
return -1;
}
public Boolean getInNCR() {
return inNCR;
}
public void setInNCR(Boolean ncr) {
inNCR = ncr;
}
}
| true
|
fc7d31ce291f4be981041cbbc8a206bf9dc311bb
|
Java
|
mrchaipats/SAD-project
|
/app/src/main/java/com/example/bigchaipat/sad/LoginActivity.java
|
UTF-8
| 1,087
| 2.171875
| 2
|
[] |
no_license
|
package com.example.bigchaipat.sad;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
EditText etUsername;
EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.username);
etPassword = findViewById(R.id.password);
Button loginBtn = findViewById(R.id.login);
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Login(view);
}
});
}
public void Login(View view) {
System.out.println(etUsername.getText() + ", " + etPassword.getText());
Intent intent = new Intent(this, QRScanActivity.class);
startActivity(intent);
finish();
}
}
| true
|
6473b787522ac6063f70d47e5aaab4a3b3256e00
|
Java
|
MauroBassan/webapps-prova
|
/webapps/src/it/corso/java/business/CorsoWebRemote.java
|
UTF-8
| 149
| 1.523438
| 2
|
[] |
no_license
|
package it.corso.java.business;
import javax.ejb.Remote;
@Remote
public interface CorsoWebRemote extends CorsoWeb {
public void collegati();
}
| true
|
a5c59ed1d06ff95fa4c0a98772b6c7f75862da4b
|
Java
|
lugowskii/psso1
|
/src/main/java/gof/decorator/UnpackerInputStream.java
|
UTF-8
| 6,766
| 2.78125
| 3
|
[] |
no_license
|
package main.java.gof.decorator;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class UnpackerInputStream extends FilterInputStream {
private static final int FILTER_BITS = 6;
public UnpackerInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
return in.read();
}
@Override
public int read(byte[] resultArray) throws IOException {
int encodedArrayLength = resultArray.length * FILTER_BITS / 8;
byte[] array = new byte[encodedArrayLength];
int result = in.read(array, 0, encodedArrayLength);
if (result == -1) {
return result;
}
String decoded = decode(Arrays.copyOfRange(array, 0, result), FILTER_BITS);
byte[] decodedBytes = decoded.getBytes();
for (int i = 0; i < decodedBytes.length; i++) {
resultArray[i] = decodedBytes[i];
}
return decodedBytes.length;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
private String decode(byte[] encoded, int bit) {
String strTemp = new String("");
String strBinary = new String("");
String strText = new String("");
Integer tempInt = new Integer(0);
int intTemp = 0;
for (int i = 0; i < encoded.length; i++) {
if (encoded[i] < 0) {
intTemp = (int) encoded[i] + 256;
} else
intTemp = (int) encoded[i];
strTemp = Integer.toBinaryString(intTemp);
while (strTemp.length() % 8 != 0) {
strTemp = "0" + strTemp;
}
strBinary = strBinary + strTemp;
}
for (int i = 0; i < strBinary.length(); i = i + bit) {
if (i + bit <= strBinary.length()) {
tempInt = tempInt.valueOf(strBinary.substring(i, i + bit), 2);
strText = strText + toChar(tempInt.intValue());
}
}
return strText;
}
private char toChar(int val) {
char ch = ' ';
switch (val) {
case 0:
ch = ' ';
break;
case 1:
ch = 'a';
break;
case 2:
ch = 'b';
break;
case 3:
ch = 'c';
break;
case 4:
ch = 'd';
break;
case 5:
ch = 'e';
break;
case 6:
ch = 'f';
break;
case 7:
ch = 'g';
break;
case 8:
ch = 'h';
break;
case 9:
ch = 'i';
break;
case 10:
ch = 'j';
break;
case 11:
ch = 'k';
break;
case 12:
ch = 'l';
break;
case 13:
ch = 'm';
break;
case 14:
ch = 'n';
break;
case 15:
ch = 'o';
break;
case 16:
ch = 'p';
break;
case 17:
ch = 'q';
break;
case 18:
ch = 'r';
break;
case 19:
ch = 's';
break;
case 20:
ch = 't';
break;
case 21:
ch = 'u';
break;
case 22:
ch = 'v';
break;
case 23:
ch = 'w';
break;
case 24:
ch = 'x';
break;
case 25:
ch = 'y';
break;
case 26:
ch = 'z';
break;
case 27:
ch = '.';
break;
case 28:
ch = '*';
break;
case 29:
ch = ',';
break;
case 30:
ch = '\\';
break;
case 31:
ch = '2';
break;
case 32:
ch = 'A';
break;
case 33:
ch = 'B';
break;
case 34:
ch = 'C';
break;
case 35:
ch = 'D';
break;
case 36:
ch = 'E';
break;
case 37:
ch = 'F';
break;
case 38:
ch = 'G';
break;
case 39:
ch = 'H';
break;
case 40:
ch = 'I';
break;
case 41:
ch = 'J';
break;
case 42:
ch = 'K';
break;
case 43:
ch = 'L';
break;
case 44:
ch = 'M';
break;
case 45:
ch = 'N';
break;
case 46:
ch = 'O';
break;
case 47:
ch = 'P';
break;
case 48:
ch = 'Q';
break;
case 49:
ch = 'R';
break;
case 50:
ch = 'S';
break;
case 51:
ch = 'T';
break;
case 52:
ch = 'U';
break;
case 53:
ch = 'V';
break;
case 54:
ch = 'W';
break;
case 55:
ch = '0';
break;
case 56:
ch = '1';
break;
case 57:
ch = '3';
break;
case 58:
ch = '4';
break;
case 59:
ch = '5';
break;
case 60:
ch = '6';
break;
case 61:
ch = '7';
break;
case 62:
ch = '8';
break;
case 63:
ch = '9';
break;
default:
ch = ' ';
}
return ch;
}
}
| true
|
677ca5179d9511a976aafc26cb4e244740196ebc
|
Java
|
7FBI/ElderlyManagementSystem7FBI
|
/src/main/java/com/bean/Matchpeoplevideo.java
|
UTF-8
| 24,532
| 1.953125
| 2
|
[] |
no_license
|
package com.bean;
import java.util.List;
public class Matchpeoplevideo {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.vid
*
* @mbggenerated
*/
private Integer vid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.did
*
* @mbggenerated
*/
private Integer did;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended1
*
* @mbggenerated
*/
private OldUsers oldUsers;
private OldDiseasedetails oldDiseasedetails;
private OldDiseaselibrary oldDiseaselibrary;
private OldSickness oldSickness;
private Video video;
private List<OldDiseaselibrary> oldDiseaselibraryLists;
public OldUsers getOldUsers() {
return oldUsers;
}
public void setOldUsers(OldUsers oldUsers) {
this.oldUsers = oldUsers;
}
public OldDiseasedetails getOldDiseasedetails() {
return oldDiseasedetails;
}
public void setOldDiseasedetails(OldDiseasedetails oldDiseasedetails) {
this.oldDiseasedetails = oldDiseasedetails;
}
public OldDiseaselibrary getOldDiseaselibrary() {
return oldDiseaselibrary;
}
public void setOldDiseaselibrary(OldDiseaselibrary oldDiseaselibrary) {
this.oldDiseaselibrary = oldDiseaselibrary;
}
public OldSickness getOldSickness() {
return oldSickness;
}
public void setOldSickness(OldSickness oldSickness) {
this.oldSickness = oldSickness;
}
public Video getVideo() {
return video;
}
public void setVideo(Video video) {
this.video = video;
}
public List<OldDiseaselibrary> getOldDiseaselibraryLists() {
return oldDiseaselibraryLists;
}
public void setOldDiseaselibraryLists(List<OldDiseaselibrary> oldDiseaselibraryLists) {
this.oldDiseaselibraryLists = oldDiseaselibraryLists;
}
private String extended1;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended2
*
* @mbggenerated
*/
private String extended2;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended3
*
* @mbggenerated
*/
private String extended3;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended4
*
* @mbggenerated
*/
private String extended4;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended5
*
* @mbggenerated
*/
private String extended5;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended6
*
* @mbggenerated
*/
private String extended6;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended7
*
* @mbggenerated
*/
private String extended7;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended8
*
* @mbggenerated
*/
private String extended8;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended9
*
* @mbggenerated
*/
private String extended9;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended10
*
* @mbggenerated
*/
private String extended10;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended11
*
* @mbggenerated
*/
private String extended11;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended12
*
* @mbggenerated
*/
private String extended12;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended13
*
* @mbggenerated
*/
private String extended13;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended14
*
* @mbggenerated
*/
private String extended14;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended15
*
* @mbggenerated
*/
private String extended15;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended16
*
* @mbggenerated
*/
private String extended16;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended17
*
* @mbggenerated
*/
private String extended17;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended18
*
* @mbggenerated
*/
private String extended18;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended19
*
* @mbggenerated
*/
private String extended19;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column matchpeoplevideo.extended20
*
* @mbggenerated
*/
private String extended20;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table matchpeoplevideo
*
* @mbggenerated
*/
public Matchpeoplevideo(Integer id, Integer vid, Integer did, String extended1, String extended2, String extended3, String extended4, String extended5, String extended6, String extended7, String extended8, String extended9, String extended10, String extended11, String extended12, String extended13, String extended14, String extended15, String extended16, String extended17, String extended18, String extended19, String extended20) {
this.id = id;
this.vid = vid;
this.did = did;
this.extended1 = extended1;
this.extended2 = extended2;
this.extended3 = extended3;
this.extended4 = extended4;
this.extended5 = extended5;
this.extended6 = extended6;
this.extended7 = extended7;
this.extended8 = extended8;
this.extended9 = extended9;
this.extended10 = extended10;
this.extended11 = extended11;
this.extended12 = extended12;
this.extended13 = extended13;
this.extended14 = extended14;
this.extended15 = extended15;
this.extended16 = extended16;
this.extended17 = extended17;
this.extended18 = extended18;
this.extended19 = extended19;
this.extended20 = extended20;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table matchpeoplevideo
*
* @mbggenerated
*/
public Matchpeoplevideo() {
super();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.id
*
* @return the value of matchpeoplevideo.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.id
*
* @param id the value for matchpeoplevideo.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.vid
*
* @return the value of matchpeoplevideo.vid
*
* @mbggenerated
*/
public Integer getVid() {
return vid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.vid
*
* @param vid the value for matchpeoplevideo.vid
*
* @mbggenerated
*/
public void setVid(Integer vid) {
this.vid = vid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.did
*
* @return the value of matchpeoplevideo.did
*
* @mbggenerated
*/
public Integer getDid() {
return did;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.did
*
* @param did the value for matchpeoplevideo.did
*
* @mbggenerated
*/
public void setDid(Integer did) {
this.did = did;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended1
*
* @return the value of matchpeoplevideo.extended1
*
* @mbggenerated
*/
public String getExtended1() {
return extended1;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended1
*
* @param extended1 the value for matchpeoplevideo.extended1
*
* @mbggenerated
*/
public void setExtended1(String extended1) {
this.extended1 = extended1 == null ? null : extended1.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended2
*
* @return the value of matchpeoplevideo.extended2
*
* @mbggenerated
*/
public String getExtended2() {
return extended2;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended2
*
* @param extended2 the value for matchpeoplevideo.extended2
*
* @mbggenerated
*/
public void setExtended2(String extended2) {
this.extended2 = extended2 == null ? null : extended2.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended3
*
* @return the value of matchpeoplevideo.extended3
*
* @mbggenerated
*/
public String getExtended3() {
return extended3;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended3
*
* @param extended3 the value for matchpeoplevideo.extended3
*
* @mbggenerated
*/
public void setExtended3(String extended3) {
this.extended3 = extended3 == null ? null : extended3.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended4
*
* @return the value of matchpeoplevideo.extended4
*
* @mbggenerated
*/
public String getExtended4() {
return extended4;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended4
*
* @param extended4 the value for matchpeoplevideo.extended4
*
* @mbggenerated
*/
public void setExtended4(String extended4) {
this.extended4 = extended4 == null ? null : extended4.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended5
*
* @return the value of matchpeoplevideo.extended5
*
* @mbggenerated
*/
public String getExtended5() {
return extended5;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended5
*
* @param extended5 the value for matchpeoplevideo.extended5
*
* @mbggenerated
*/
public void setExtended5(String extended5) {
this.extended5 = extended5 == null ? null : extended5.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended6
*
* @return the value of matchpeoplevideo.extended6
*
* @mbggenerated
*/
public String getExtended6() {
return extended6;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended6
*
* @param extended6 the value for matchpeoplevideo.extended6
*
* @mbggenerated
*/
public void setExtended6(String extended6) {
this.extended6 = extended6 == null ? null : extended6.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended7
*
* @return the value of matchpeoplevideo.extended7
*
* @mbggenerated
*/
public String getExtended7() {
return extended7;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended7
*
* @param extended7 the value for matchpeoplevideo.extended7
*
* @mbggenerated
*/
public void setExtended7(String extended7) {
this.extended7 = extended7 == null ? null : extended7.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended8
*
* @return the value of matchpeoplevideo.extended8
*
* @mbggenerated
*/
public String getExtended8() {
return extended8;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended8
*
* @param extended8 the value for matchpeoplevideo.extended8
*
* @mbggenerated
*/
public void setExtended8(String extended8) {
this.extended8 = extended8 == null ? null : extended8.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended9
*
* @return the value of matchpeoplevideo.extended9
*
* @mbggenerated
*/
public String getExtended9() {
return extended9;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended9
*
* @param extended9 the value for matchpeoplevideo.extended9
*
* @mbggenerated
*/
public void setExtended9(String extended9) {
this.extended9 = extended9 == null ? null : extended9.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended10
*
* @return the value of matchpeoplevideo.extended10
*
* @mbggenerated
*/
public String getExtended10() {
return extended10;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended10
*
* @param extended10 the value for matchpeoplevideo.extended10
*
* @mbggenerated
*/
public void setExtended10(String extended10) {
this.extended10 = extended10 == null ? null : extended10.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended11
*
* @return the value of matchpeoplevideo.extended11
*
* @mbggenerated
*/
public String getExtended11() {
return extended11;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended11
*
* @param extended11 the value for matchpeoplevideo.extended11
*
* @mbggenerated
*/
public void setExtended11(String extended11) {
this.extended11 = extended11 == null ? null : extended11.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended12
*
* @return the value of matchpeoplevideo.extended12
*
* @mbggenerated
*/
public String getExtended12() {
return extended12;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended12
*
* @param extended12 the value for matchpeoplevideo.extended12
*
* @mbggenerated
*/
public void setExtended12(String extended12) {
this.extended12 = extended12 == null ? null : extended12.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended13
*
* @return the value of matchpeoplevideo.extended13
*
* @mbggenerated
*/
public String getExtended13() {
return extended13;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended13
*
* @param extended13 the value for matchpeoplevideo.extended13
*
* @mbggenerated
*/
public void setExtended13(String extended13) {
this.extended13 = extended13 == null ? null : extended13.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended14
*
* @return the value of matchpeoplevideo.extended14
*
* @mbggenerated
*/
public String getExtended14() {
return extended14;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended14
*
* @param extended14 the value for matchpeoplevideo.extended14
*
* @mbggenerated
*/
public void setExtended14(String extended14) {
this.extended14 = extended14 == null ? null : extended14.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended15
*
* @return the value of matchpeoplevideo.extended15
*
* @mbggenerated
*/
public String getExtended15() {
return extended15;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended15
*
* @param extended15 the value for matchpeoplevideo.extended15
*
* @mbggenerated
*/
public void setExtended15(String extended15) {
this.extended15 = extended15 == null ? null : extended15.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended16
*
* @return the value of matchpeoplevideo.extended16
*
* @mbggenerated
*/
public String getExtended16() {
return extended16;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended16
*
* @param extended16 the value for matchpeoplevideo.extended16
*
* @mbggenerated
*/
public void setExtended16(String extended16) {
this.extended16 = extended16 == null ? null : extended16.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended17
*
* @return the value of matchpeoplevideo.extended17
*
* @mbggenerated
*/
public String getExtended17() {
return extended17;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended17
*
* @param extended17 the value for matchpeoplevideo.extended17
*
* @mbggenerated
*/
public void setExtended17(String extended17) {
this.extended17 = extended17 == null ? null : extended17.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended18
*
* @return the value of matchpeoplevideo.extended18
*
* @mbggenerated
*/
public String getExtended18() {
return extended18;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended18
*
* @param extended18 the value for matchpeoplevideo.extended18
*
* @mbggenerated
*/
public void setExtended18(String extended18) {
this.extended18 = extended18 == null ? null : extended18.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended19
*
* @return the value of matchpeoplevideo.extended19
*
* @mbggenerated
*/
public String getExtended19() {
return extended19;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended19
*
* @param extended19 the value for matchpeoplevideo.extended19
*
* @mbggenerated
*/
public void setExtended19(String extended19) {
this.extended19 = extended19 == null ? null : extended19.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column matchpeoplevideo.extended20
*
* @return the value of matchpeoplevideo.extended20
*
* @mbggenerated
*/
public String getExtended20() {
return extended20;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column matchpeoplevideo.extended20
*
* @param extended20 the value for matchpeoplevideo.extended20
*
* @mbggenerated
*/
public void setExtended20(String extended20) {
this.extended20 = extended20 == null ? null : extended20.trim();
}
}
| true
|
46db25939082f48f8e9d58b0e7b38b08d281767b
|
Java
|
titikkoma88/ModernlandTicket
|
/app/src/main/java/ticket/modernland/co/id/ListAdapter.java
|
UTF-8
| 1,122
| 2.1875
| 2
|
[] |
no_license
|
package ticket.modernland.co.id;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class ListAdapter extends RecyclerView.Adapter<ListViewHolder> {
public ArrayList<ListTicketUser> data;
@NonNull
@Override
public ListViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View x = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_list_user, viewGroup,
false);
ListViewHolder lu = new ListViewHolder(x);
return lu;
}
@Override
public void onBindViewHolder(@NonNull ListViewHolder listViewHolder, int i) {
ListTicketUser lu = data.get(i);
listViewHolder.et_reported.setText(lu.reported);
listViewHolder.et_prosummary.setText(lu.problem_summary);
listViewHolder.et_idticket.setText(lu.id_ticket+ "");
}
@Override
public int getItemCount() {
return data.size();
}
}
| true
|
f1327707f39542d40e20da8dbc38236a02900ad7
|
Java
|
Rowell972/Java-courses
|
/src/Calculator.java
|
UTF-8
| 1,845
| 3.59375
| 4
|
[] |
no_license
|
/**
* Class Класс реализующий основную логику работы калькулятора.
* @author Kovalev
* @since 13.08.2019
* @version 1
*/
public class Calculator {
/**
* Переменная для хранения результат вычислений.
*/
private int result = 0;
/**
* Метод сложения.
* @param params Аргументы
*/
public void add(int ... params) {
if (params.length > 0) {
this.result = params[0];
for (int index = 1; index != params.length ; index++) {
this.result += params[index];
}
}
}
/**
* Метод вычитания.
* @param params Аргументы
*/
public void sub(int ... params) {
if (params.length > 0) {
this.result = params[0];
for (int index = 1; index != params.length ; index++) {
this.result -= params[index];
}
}
}
/**
* Метод умножения.
* @param params Аргументы
*/
public void mult(int ... params) {
if (params.length > 0) {
this.result = params[0];
for (int index = 1; index != params.length ; index++) {
this.result *= params[index];
}
}
}
/**
* Метод деления.
* @param params Аргументы
*/
public void div(int ... params) {
if (params.length > 0) {
this.result = params[0];
for (int index = 1; index != params.length ; ++index) {
if (params[index] != 0) {
this.result /= params[index];
}
}
}
}
/**
* Метод возвращающий значения результата вычисления
* для вызывающей части кода.
*/
public int getResult() {
return this.result;
}
/**
* Метод очищающий значение результата вычислений.
*/
public void cleanResult() {
this.result = 0;
}
}
| true
|
084aa7e0ca306f2b97df399a851b30ec274ff0af
|
Java
|
alisonwood29/W7D3AdventureTimeLab
|
/src/test/java/DwarfTest.java
|
UTF-8
| 1,925
| 2.921875
| 3
|
[] |
no_license
|
import Players.NonMagicalPlayers.Dwarf;
import Players.NonMagicalPlayers.Weapon;
import RoomObjects.Treasure;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DwarfTest {
Dwarf dwarf;
@Before
public void before(){
dwarf = new Dwarf("Gimli", Weapon.AXE, 10);
}
@Test
public void dwarfHasName(){
assertEquals("Gimli", dwarf.getName());
}
@Test
public void healthValueStartsAt100(){
assertEquals(100, dwarf.getHealthValue());
}
@Test
public void treasureStartsEmpty(){
assertEquals(0, dwarf.treasureCount());
}
@Test
public void scoreStartsAt0(){
assertEquals(0, dwarf.getScore());
}
@Test
public void hasWeapon(){
assertEquals(Weapon.AXE, dwarf.getWeapon());
}
@Test
public void weaponHasDamage(){
assertEquals(15, dwarf.getWeaponDamage());
}
@Test
public void hasChainmailProtection(){
assertEquals(10, dwarf.getChainmailProtection());
}
@Test
public void canAddToScore(){
dwarf.addToScore(10);
assertEquals(10, dwarf.getScore());
}
@Test
public void canSetWeapon(){
dwarf.setWeapon(Weapon.STAFF);
assertEquals(Weapon.STAFF, dwarf.getWeapon());
}
@Test
public void canDecreaseHealthValue(){
dwarf.decreaseHealthValue(10);
assertEquals(90, dwarf.getHealthValue());
}
@Test
public void canIncreaseHealthValue(){
dwarf.increaseHealthValue(10);
assertEquals(110, dwarf.getHealthValue());
}
@Test
public void canAddTreasure(){
dwarf.addTreasure(Treasure.GOLD);
assertEquals(1, dwarf.treasureCount());
}
@Test
public void treasureValueAddsToScore(){
dwarf.addTreasure(Treasure.GOLD);
assertEquals(10, dwarf.getScore());
}
}
| true
|
f8e66e1bb9db26681649ff46fb5c32ce64c5f786
|
Java
|
rico2004/PokeMeow-Renderer
|
/src/main/java/org/cytoscape/pokemeow/internal/nodeshape/pmDiamondNodeShape.java
|
UTF-8
| 472
| 2.1875
| 2
|
[] |
no_license
|
package main.java.org.cytoscape.pokemeow.internal.nodeshape;
import com.jogamp.opengl.GL4;
import main.java.org.cytoscape.pokemeow.internal.algebra.Vector4;
/**
* Created by ZhangMenghe on 2017/6/22.
*/
public class pmDiamondNodeShape extends pmRectangleNodeShape{
public pmDiamondNodeShape(GL4 gl4){
super(gl4);
setRotation((float) Math.PI/4);
}
public pmDiamondNodeShape(){
super();
setRotation((float) Math.PI/4);
}
}
| true
|
79c846aac36667260234a570106120678f169f71
|
Java
|
isaroium/simulator
|
/src/main/java/com/adswizz/model/Comparator.java
|
UTF-8
| 671
| 2.828125
| 3
|
[] |
no_license
|
package com.adswizz.model;
/**
* @author mihaiisaroiu
*/
public class Comparator implements java.util.Comparator<Electable> {
int n;
public static final Comparator provide(int pricePerSecondPriority) {
Comparator toRet = new Comparator();
toRet.n = pricePerSecondPriority < 0 ? 0 : pricePerSecondPriority > 100 ? 100 : pricePerSecondPriority;
return toRet;
}
public int compare(Electable o1, Electable o2) {
return Double.compare(yieldFunction(o2), yieldFunction(o1));
}
private double yieldFunction(Electable o) {
return (n * ((1.0 * o.price) / o.duration) + (100 - n) * o.getAllocation());
}
}
| true
|
b2a4d7cdc61d942ea0afd26fee6eab0046bd0f7f
|
Java
|
anony88888/regain
|
/src/net/sf/regain/search/sharedlib/hit/TypeiconTag.java
|
UTF-8
| 3,870
| 2.203125
| 2
|
[] |
no_license
|
/*
* regain - A file search engine providing plenty of formats
* Copyright (C) 2004 Til Schneider
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: Til Schneider, info@murfman.de
*/
package net.sf.regain.search.sharedlib.hit;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import net.sf.regain.RegainException;
import net.sf.regain.search.SearchToolkit;
import net.sf.regain.search.results.SearchResults;
import net.sf.regain.util.sharedtag.PageRequest;
import net.sf.regain.util.sharedtag.PageResponse;
import org.apache.lucene.document.Document;
/**
* Generates an img showing the hit's type using its extension.
* <p>
* Tag Parameters:
* <ul>
* <li><code>imgpath</code>: The path where the type icons are located.</li>
* <li><code>iconextension</code>: The extension used by the type icons (default is "gif").</li>
* </ul>
*
* @author Til Schneider, www.murfman.de
*/
public class TypeiconTag extends AbstractHitTag {
/**
* A map holding for a lowercase extension (String) whether there is an icon
* for that extension (Boolean).
*/
private static HashMap mExtensionAvailableMap = new HashMap();
/**
* Generates the tag.
*
* @param request The page request.
* @param response The page response.
* @param hit The current search hit.
* @param hitIndex The index of the hit.
* @throws RegainException If there was an exception.
*/
protected void printEndTag(PageRequest request, PageResponse response,
Document hit, int hitIndex)
throws RegainException
{
SearchResults results = SearchToolkit.getSearchResults(request);
String imgpath = getParameter("imgpath");
String iconextension = getParameter("iconextension");
if (iconextension == null) {
iconextension = "gif";
}
// Get the extension of this hit
String extension = null;
String url = results.getHitUrl(hitIndex);
int lastDot = url.lastIndexOf('.');
if (lastDot != -1) {
extension = url.substring(lastDot + 1).toLowerCase();
}
// Check whether this extension is available
String imgFile = imgpath + "/ext_" + extension + "." + iconextension;
Boolean available;
synchronized (mExtensionAvailableMap) {
available = (Boolean) mExtensionAvailableMap.get(extension);
if (available == null) {
// This entry is not yet cached -> Check whether there is an icon for
// that extension (e.g. img/ext/ext_pdf.gif)
try {
URL iconUrl = new URL(request.getResourceBaseUrl(), imgpath + "/ext_"
+ extension + "." + iconextension);
InputStream stream = iconUrl.openStream();
stream.close();
available = Boolean.TRUE;
} catch (Throwable thr) {
available = Boolean.FALSE;
}
mExtensionAvailableMap.put(extension, available);
}
}
// Show the appropriate icon
if (! available.booleanValue()) {
imgFile = imgpath + "/no_ext" + "." + iconextension;
}
response.print("<img src=\"" + imgFile + "\"></img>");
}
}
| true
|
01d93273a385949782d238ff382106f7e88ec8e1
|
Java
|
Pilasilda/IN1000
|
/oblig7/DVDAdministrasjon.java
|
UTF-8
| 7,578
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
import java.util.HashMap; //Importerer hashmap
import java.util.Scanner; //Importerer scanner
import java.io.File; //Import for aa lese fil
//Klassen DVDAdministrasjon
public class DVDAdministrasjon{
//Opretter et hashmap som inneholder alle navn
private HashMap <String, Person> navneListe = new HashMap<String, Person>();
Scanner scan = new Scanner(System.in);
private String navn;
private String linje;
//Metode for som returerer den private hashmap-en
public HashMap<String, Person> getnavneListe(){
return navneListe;
}
//Metode som lesefil og legger objekt i hashmap
public void lesInn(String filnavn) throws Exception{
Scanner fil = new Scanner(new File(filnavn));//lager ett nytt scannerobjekt
linje = fil.nextLine();
//Leser inn navn og legger navn i hashmap
while(fil.hasNextLine()){
while(!linje.equals("-")){
navneListe.put(linje, new Person(linje)); //legger til i navneliste hashmap
//Leser linje
linje = fil.nextLine();
}
//Leser linje
linje = fil.nextLine();
//Henter personer lagret i hashmap
Person p = navneListe.get(linje);
while(!linje.equals("-")){
//Hvis linje inneholder tegnet *
if(linje.charAt(0) == '*'){
String bruh = linje.substring(1);
DVD dtmb = new DVD(bruh, p); //legg til ny DVD
p.leggTilDVD(dtmb);//Legger til i personens eierarkiv
linje = fil.nextLine(); //leser linje
Person laaner = navneListe.get(linje); //henter personer
laaner.getLaanere().put(bruh, dtmb); //legger laante DVD i lanere hashmaps
p.getUtlaanere().put(bruh, dtmb); // maa legge til person som laaner dvden
}else{
DVD dtmb = new DVD(linje, p); //Legger til ny DVD
p.leggTilDVD(dtmb);//
}
linje = fil.nextLine();//Leser linje
}
}
}
//Metode for meny som viser overiskt over hva bruker kan velge
public void meny(){
System.out.println(" ");
System.out.println("*******DVDAdministrasjon*******");
System.out.println("1 : nyPerson ");
System.out.println("2 : kjop ");
System.out.println("3 : laan ");
System.out.println("4 : visPerson");
System.out.println("5 : visOversikt");
System.out.println("6 : retur");
System.out.println("7 : avslutt ");
System.out.println(" ");
System.out.println("***");
System.out.println(" ");
System.out.println("Gi en kommando ved aa skrive ett tall");
}
//Ordrelokke som skal gå gjennom alle metodene
public void ordrelokke(){
int valg = Integer.parseInt(scan.nextLine());
while(valg != 7){
if(valg == 1){
nyPerson();
}else if(valg == 2){
kjop();
}else if(valg == 3){
laan();
}else if(valg == 4){
visPersoner();
}else if(valg == 5){
visOversikt();
}else if(valg == 6){
retur();
}else{
//Hvis bruker taster 7 gå gis denne utksriften
System.out.println("Ugyldig kommando!!!! Vennligst oppgi et lovlig kommando.");
}
meny();
valg = Integer.parseInt(scan.nextLine());
}
}
//Metode for å opprette ny person som legges i navneListe hashmapet
public void nyPerson(){
//Skriver til terminal
System.out.println("Legg til ny person: ");
//Input fra bruker
String navn = scan.nextLine();
//Oppretter et personobjekt og legger til den nye personen i HashMapen ved navn navneListe
navneListe.put(navn, new Person(navn));
}
//Metode som viser oversikt over hva en spesifikk person eier
public void visPersoner(){
System.out.println("Hvilken person vil du se? (* for alle)");
String tekst = scan.nextLine();
if(tekst.equals("*")){
for(Person p : navneListe.values()){
p.utskrift();
}
} else{
navneListe.get(tekst).utskrift();
}
}
//Metode som viser oversikt over alle personene i arkivet
public void visOversikt(){
for(Person p : navneListe.values()){
System.out.println("Person: " + p.toString()); //Henter person sitt navn
System.out.println("Eier: " + p.getEier().size()); //antall eide
System.out.println("Laant: " + p.getLaanere().size()); //antall laante
System.out.println("Utlaant: " + p.getUtlaanere().size()); //antall utlaant
System.out.println(" ");
}
}
//Metode for aa gjore et kjop
public void kjop(){
System.out.println("Hva heter eieren? "); //Kommando til terminal
String navn = scan.nextLine();
if(navneListe.containsKey(navn)) {
System.out.println("Personen finnes i systemet"); //Kommando til terminal
}else {
System.out.println("Personen finnes ikke i systemet");//Kommando til terminal
return;
}
System.out.println("Hva er tittelen paa DVD-en? "); //KOmmando til terminal
String tittel = scan.nextLine();
Person kjoper = navneListe.get(navn);
kjoper.getEier().put(tittel, new DVD(tittel, kjoper));
HashMap<String, DVD> temp = kjoper.getEier();//Kjopet legges i en temprary HashMap
}
//Metode for å gjore et laa
public void laan(){
//Sjekker om hvem som laaner DVD-en
System.out.println("Hvem vil laane DVD-en?"); //Kommando til terminal
String laan = scan.nextLine();
if(!navneListe.containsKey(laan)) {
System.out.println("Personen finnes ikke i systemet");
return;
}
//Sjekker om hvem som utlaant dvd-en
System.out.println("Hvem skal laane bort DVD-en?"); //Kommando til terminal
String utlaan = scan.nextLine();
if(!navneListe.containsKey(utlaan)) {
System.out.println("Utlaaneren finnes ikke i systemet");
return;
}
//Sjekker om hva tittel på dvd-en som laanes ut er
System.out.println("Hvilken DVD skal laanes?");
String dvd = scan.nextLine();
if(!navneListe.get(utlaan).getEier().containsKey(dvd)) {
System.out.println("DVDen finnes ikke i systemet");
return;
}
Person utLaaner = navneListe.get(utlaan);
DVD dvden = utLaaner.getEier().get(dvd);
Person laaner = navneListe.get(laan);
utLaaner.getUtlaanere().put(dvd, dvden);
dvden.settLaaner(laaner);
laaner.getLaanere().put(dvd, dvden);
}
//Metode for å retunrere DVD
public void retur(){
System.out.println("Hvem har laant DVD-en? ");
String returNavn = scan.nextLine();
if(navneListe.get(returNavn).getLaanere().size() == 0){
System.out.println("Person laaner ikke DVD fra noen. ");
return;
}
System.out.println("Hva er navnet til eieren ? ");
String eierNavn = scan.nextLine();
if(navneListe.get(eierNavn).getUtlaanere().size() == 0){
System.out.println("Personen utlaaner ikke DVD-er til noen. ");
return;
}
System.out.println("Hvilken DVD skal personen returnere? ");
String returDVD = scan.nextLine();
if(!navneListe.get(returNavn).getLaanere().containsKey(returDVD)){
System.out.println("Personen har ikke laant en saan DVD. ");
return;
}
Person laaner = navneListe.get(returNavn); //Henter personer i hashmap til den som DVD skal returneres til
Person utlaante = navneListe.get(eierNavn); //Henter person i hashmap til person som eier DVD
laaner.getLaanere().remove(returDVD); //Fjerner laante DVD fra hashmap
utlaante.getUtlaanere().remove(returDVD); //Fjerner utlaante DVD fra hashmap
}
}
| true
|
d45c3cacaa08d5051f98b35ec04bc6e37bdab547
|
Java
|
afrussel/W3engineers_assignment_three_android
|
/app/src/main/java/io/left/core/assignment/ui/theme_color_change/ThemeColorChangeActivity.java
|
UTF-8
| 7,614
| 1.921875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.left.core.assignment.ui.theme_color_change;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import io.left.core.assignment.data.helper.UtilityForProfileImage;
import io.left.core.assignment.ui.base.BaseActivity;
import io.left.core.util.R;
import io.left.core.util.helper.GetColorUtil;
public class ThemeColorChangeActivity extends BaseActivity<ThemeColorChangeMvpView, ThemeColorChangePresenter> implements ThemeColorChangeMvpView, View.OnClickListener {
private static final int REQUEST_CAMERA = 1;
private static final int SELECT_FILE = 2;
@BindView(R.id.imageview_user)
CircleImageView imageviewUser;
Bitmap bm;
@BindView(R.id.relative_layout)
RelativeLayout relativeLayout;
String userChoosenTask;
Bitmap thumbnail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_theme_color_change);
ButterKnife.bind(this);
imageviewUser.setOnClickListener(this);
}
@Override
protected ThemeColorChangePresenter initPresenter() {
return new ThemeColorChangePresenter();
}
//take image from camera and device
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case UtilityForProfileImage.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Take Photo"))
cameraIntent();
else if (userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
/*
* select image from camera and mobile device
* */
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(ThemeColorChangeActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
boolean result = UtilityForProfileImage.checkPermission(ThemeColorChangeActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
//onCaptureImageResult
public void onCaptureImageResult(Intent data) {
thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Glide.with(this)
.load(bytes.toByteArray())
.asBitmap()
.into(imageviewUser);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
relativeLayout.setBackgroundColor(GetColorUtil.PalletColorFromImage(thumbnail));
}
}, 500);
}
//onSelectFromGalleryResult
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
bm = null;
if (data != null) {
try {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Glide.with(this)
.load(bytes.toByteArray())
.asBitmap()
.into(imageviewUser);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
relativeLayout.setBackgroundColor(GetColorUtil.PalletColorFromImage(bm));
}
}, 500);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onClick(View view) {
selectImage();
}
}
| true
|
89bfdd75b2822e8e7e272546d90635af72c38678
|
Java
|
lesliedou/iResearch
|
/src/main/java/com/research/domain/UploadInfo.java
|
UTF-8
| 2,955
| 2.375
| 2
|
[] |
no_license
|
package com.research.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A UploadInfo.
*/
@Entity
@Table(name = "ddy_info_upload")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class UploadInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "info_id")
private Long id;
@Column(name = "info_type")
private String infoType;
@Column(name = "subj")
private String subj;
@Column(name = "content")
private String content;
@OneToOne
@JoinColumn(unique = true)
private Department department;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInfoType() {
return infoType;
}
public UploadInfo infoType(String infoType) {
this.infoType = infoType;
return this;
}
public void setInfoType(String infoType) {
this.infoType = infoType;
}
public String getSubj() {
return subj;
}
public UploadInfo subj(String subj) {
this.subj = subj;
return this;
}
public void setSubj(String subj) {
this.subj = subj;
}
public String getContent() {
return content;
}
public UploadInfo content(String content) {
this.content = content;
return this;
}
public void setContent(String content) {
this.content = content;
}
public Department getDepartment() {
return department;
}
public UploadInfo department(Department department) {
this.department = department;
return this;
}
public void setDepartment(Department department) {
this.department = department;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadInfo uploadInfo = (UploadInfo) o;
if (uploadInfo.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), uploadInfo.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "UploadInfo{" +
"id=" + getId() +
", infoType='" + getInfoType() + "'" +
", subj='" + getSubj() + "'" +
", content='" + getContent() + "'" +
"}";
}
}
| true
|
e81b9cbb27ebf7687a4b0fb5bfe087da958939a1
|
Java
|
RezaEftekharzadeh/leetcode
|
/src/leet/HowManyNumbersAreSmallerThanTheCurrentNumber1365.java
|
UTF-8
| 760
| 3.5
| 4
|
[] |
no_license
|
package leet;
public class HowManyNumbersAreSmallerThanTheCurrentNumber1365 {
public static void main(String[] args) {
int [] nums = {8,8,8,8,8};
HowManyNumbersAreSmallerThanTheCurrentNumber1365 howMany=
new HowManyNumbersAreSmallerThanTheCurrentNumber1365();
int[] tempb= howMany.smallerNumbersThanCurrent(nums);
for(int s: tempb) {
System.out.println(s);
}
}
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] result= new int[nums.length];
int temp=0;
for(int i=0;i<nums.length;i++) {
temp=0;
for(int j=0;j<nums.length;j++) {
if (j==i) continue;
if(nums[j]<nums[i]) {
temp++;
}
}
result[i]=temp;
}
return result;
}
}
| true
|
dbc424278a9b92e79b23c1576d519fb86e3e17de
|
Java
|
Arushi-Jain/FirebaseNotification-onLocationChangeServiceNativeApp
|
/app/src/main/java/com/example/arushi_jain/myapplication/NotificationClick.java
|
UTF-8
| 329
| 1.71875
| 2
|
[] |
no_license
|
package com.example.arushi_jain.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class NotificationClick extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notificationclick);
}
}
| true
|
96756cb9f63c413f2e2ed99e3c1203fb95b7ff77
|
Java
|
prasannaramkumar/random
|
/java/src/com/madhu/minc/jburg/JBurg.java
|
UTF-8
| 6,314
| 2.296875
| 2
|
[] |
no_license
|
package com.madhu.minc.jburg;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
/*
* Created on Jul 13, 2007 at 2:25:01 PM
*/
public class JBurg {
public static final int MAX_COST = Short.MAX_VALUE;
private int ntNumber;
private Symbol start;
private Symbol terminals;
private Symbol nonTerminals;
private Rule rules;
private int nRules;
private HashMap<String,Symbol> symbolTable;
private Emitter emitter;
public static void main(String[] args) throws IOException {
JBurg p = new JBurg();
p.addSymbol("CNSTI", 21);
p.addSymbol("ASGNI", 53);
p.addSymbol("INDIRC", 67);
p.addSymbol("CVCI", 85);
p.addSymbol("ADDRLP", 295);
p.addSymbol("ADDI", 309);
p.addSymbol("I0I", 661);
p.addSymbol("stmt");
p.addSymbol("disp");
p.addSymbol("reg");
p.addSymbol("rc");
p.addSymbol("con");
p.addRule("stmt", p.tree("ASGNI", p.tree("disp"), p.tree("reg")), 4, 1);
p.addRule("stmt", p.tree("reg"), 5);
p.addRule("reg", p.tree("ADDI", p.tree("reg"), p.tree("rc")), 6, 1);
p.addRule("reg", p.tree("CVCI", p.tree("INDIRC", p.tree("disp"))), 7, 1);
p.addRule("reg", p.tree("I0I"), 8);
p.addRule("reg", p.tree("disp"), 9, 1);
p.addRule("disp", p.tree("ADDI", p.tree("reg"), p.tree("con")), 10);
p.addRule("disp", p.tree("ADDRLP"), 11);
p.addRule("rc", p.tree("con"), 12);
p.addRule("rc", p.tree("reg"), 13);
p.addRule("con", p.tree("CNSTI"), 14);
p.addRule("con", p.tree("I0I"), 15);
p.generateMatcher("src", ".com.madhu.minc.jburg", "Sample4");
}
public JBurg() {
symbolTable = new HashMap<String,Symbol>();
}
public void addSymbol(String name) {
addSymbol(name, 0);
}
public void addSymbol(String name, int number) {
Symbol s = new Symbol(name, number);
symbolTable.put(name, s);
if (s.isTerminal()) {
s.arity = -1;
if (terminals == null) {
terminals = s;
return;
}
Symbol q = terminals;
while (q.next != null) {
q = q.next;
}
q.next = s;
} else {
s.number = ++ntNumber;
if (s.number == 1) {
start = s;
}
if (nonTerminals == null) {
nonTerminals = s;
return;
}
Symbol q = nonTerminals;
while (q.next != null) {
q = q.next;
}
q.next = s;
}
}
public void generateMatcher(String dest, String packageName, String className) throws IOException {
String fileName = dest + "/" + packageName.replace('.', '/') + "/" + className + ".java";
emitter = new Emitter(
new PrintWriter(
new FileWriter(fileName)));
if (start != null) {
ckreach(start);
}
for (Symbol p = nonTerminals; p != null; p = p.next) {
if (!p.reached) {
throw new AssertionError("can't reach non-terminal " + p.name);
}
}
emitter.emitHeader(packageName, className);
emitter.emitDefinitions(nonTerminals, ntNumber);
emitter.emitNonTerminals(rules, nRules);
emitter.emitTerminals(terminals);
emitter.emitRules(rules);
emitter.emitRule(nonTerminals, ntNumber);
emitter.emitClosures(nonTerminals);
if (start != null) {
emitter.emitState(terminals, start, ntNumber);
}
emitter.emitKids(rules, nRules);
emitter.emitTrailer();
emitter.close();
System.out.println("All done!");
}
public RTree tree(String id) {
return tree(id, null);
}
public RTree tree(String id, RTree left) {
return tree(id, left, null);
}
/* tree - create & initialize a tree node with the given fields */
public RTree tree(String id, RTree left, RTree right) {
RTree t = new RTree();
Symbol p = (Symbol) symbolTable.get(id);
int arity = 0;
if (left != null && right != null) {
arity = 2;
} else if (left != null) {
arity = 1;
}
if (p == null && arity > 0) {
p = new Symbol(id, -1);
throw new AssertionError(String.format("undefined terminal `%s'\n", id));
} else if (p == null && arity == 0) {
p = symbolTable.get(id);
throw new AssertionError("bogus case: " + id);
}
else if (p != null && !p.isTerminal() && arity > 0) {
p = new Symbol(id, -1);
throw new AssertionError(String.format("`%s' is a non-terminal\n", id));
}
if (p.isTerminal() && p.arity == -1) {
p.arity = arity;
}
if (p.isTerminal() && arity != p.arity) {
throw new AssertionError(String.format("inconsistent arity for terminal `%s'\n", id));
}
t.op = p;
t.nTerminals = t.op.isTerminal() ? 1 : 0;
if ((t.left = left) != null)
t.nTerminals += left.nTerminals;
if ((t.right = right) != null)
t.nTerminals += right.nTerminals;
return t;
}
private int defaultRuleNumber = 1;
public Rule addRule(String id, RTree pattern) {
return addRule(id, pattern, "");
}
public Rule addRule(String id, RTree pattern, String template) {
return addRule(id, pattern, template, 0);
}
public Rule addRule(String id, RTree pattern, String template, int cost) {
Rule r = addRule(id, pattern, defaultRuleNumber++, cost);
r.template = template;
return r;
}
public Rule addRule(String id, RTree pattern, int ern) {
return addRule(id, pattern, ern, 0);
}
/* rule - create & initialize a rule with the given fields */
public Rule addRule(String id, RTree pattern, int ern, int cost) {
Rule r = new Rule(), q;
nRules++;
r.lhs = symbolTable.get(id);
r.packedErn = ++r.lhs.lhsCount;
if (r.lhs.rules == null) {
r.lhs.rules = r;
} else {
for (q = r.lhs.rules; q.decode != null; q = q.decode);
q.decode = r;
}
r.pattern = pattern;
r.ern = ern;
r.cost = cost;
Symbol p = (Symbol) pattern.op;
if (p.isTerminal()) {
r.next = p.rules;
p.rules = r;
} else if (pattern.left == null && pattern.right == null) {
Symbol p1 = (Symbol) pattern.op;
r.chain = p1.chain;
p1.chain = r;
}
if (rules == null) {
rules = r;
return r;
}
for (q = rules; q.link != null; q = q.link);
q.link = r;
return r;
}
/* reach - mark all non-terminals in tree t as reachable */
private void reach(RTree t) {
Symbol p = (Symbol) t.op;
if (!p.isTerminal()) {
Symbol q = (Symbol) p;
if (!q.reached)
ckreach(q);
}
if (t.left != null)
reach(t.left);
if (t.right != null)
reach(t.right);
}
/* ckreach - mark all non-terminals reachable from p */
private void ckreach(Symbol p) {
p.reached = true;
for (Rule r = p.rules; r != null; r = r.decode) {
reach(r.pattern);
}
}
}
| true
|
31625adc09a80f6c8e86188d6e60e3f1bf2021f4
|
Java
|
hufan30/JavaCodePractice
|
/JavaBasicDemo/src/main/java/ReflectionDemo/StaticLoadDemo.java
|
UTF-8
| 823
| 3.359375
| 3
|
[] |
no_license
|
package ReflectionDemo;
/**
* @description:
* @author: HuFan
* @time: 2020/2/172:39 下午
**/
public class StaticLoadDemo {
static{
System.out.println("Main初始化");
}
public static void main(String[] args) {
A a = new A();
System.out.println(A.m);
/**
* 1.加载到内存,会产生一个类对应class对象
* 2.链接,链接结束后m=0;默认值
* 3.初始化
* <clinit>(){
* sout(A的静态代码块);
* m=300;
* m=100;
* }
* 合并之后,m=100;
*/
}
}
class A{
static{
System.out.println("A的静态代码块");
m = 300;
}
static int m = 100;
public A(){
System.out.println("A的无参数构造");
}
}
| true
|
3cb14ad429137e3eccf4674184e280f7629e201d
|
Java
|
0moura/tiktok_source
|
/df_miniapp/classes/com/tt/miniapp/msg/ApisetKeepScreenOnCtrl.java
|
UTF-8
| 1,381
| 1.632813
| 2
|
[] |
no_license
|
package com.tt.miniapp.msg;
import com.tt.frontendapiinterface.a;
import com.tt.frontendapiinterface.b;
import com.tt.frontendapiinterface.e;
import com.tt.miniapphost.AppbrandApplication;
import com.tt.miniapphost.AppbrandContext;
import com.tt.option.e.e;
import org.json.JSONObject;
public class ApisetKeepScreenOnCtrl extends b {
public ApisetKeepScreenOnCtrl(String paramString, int paramInt, e parame) {
super(paramString, paramInt, parame);
}
public void act() {
try {
final boolean keepScreen = (new JSONObject(this.mArgs)).optBoolean("keepScreenOn");
final e iActivityLife = AppbrandApplication.getInst().getActivityLife();
if (e != null) {
AppbrandContext.mainHandler.post(new Runnable() {
public void run() {
iActivityLife.setKeepScreenOn(keepScreen);
}
});
callbackOk();
return;
}
callbackFail(a.c("iActivityLife"));
return;
} catch (Exception exception) {
callbackFail(exception);
return;
}
}
public String getActionName() {
return "setKeepScreenOn";
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ApisetKeepScreenOnCtrl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
| true
|
29d1a90b8c298c599a430cb32eb4a798a15a8d31
|
Java
|
emilyttran/OrlystAndroid
|
/app/src/main/java/com/example/stephanieangulo/orlyst/AppData.java
|
UTF-8
| 1,114
| 2.234375
| 2
|
[] |
no_license
|
package com.example.stephanieangulo.orlyst;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
public class AppData {
private static final String GS_BUCKET = "gs://orlystapp.appspot.com/";
private static final String USERS_ROOT = "users";
private static final String ITEMS_ROOT = "items";
protected static FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
protected static FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(GS_BUCKET);
protected static FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
protected static DatabaseReference userRootReference = firebaseDatabase.getReference().child(USERS_ROOT);
protected static DatabaseReference itemRootReference = firebaseDatabase.getReference().child(ITEMS_ROOT);
protected static DatabaseReference getItemReference(String id) {
return firebaseDatabase.getReference().child(USERS_ROOT).child(id).child(ITEMS_ROOT);
}
}
| true
|
e2f2aaf25bb9842c2a81e0cbbfc8c336494344bc
|
Java
|
chujiang/ccc
|
/kingnod-etraining-full/src/main/java/com/kingnod/etraining/exam/action/GeneratingPaperScopeAction.java
|
UTF-8
| 4,232
| 1.8125
| 2
|
[] |
no_license
|
package com.kingnod.etraining.exam.action;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import com.kingnod.core.extensions.struts2.action.EntityAction;
import com.kingnod.core.extensions.struts2.action.FilterableEntityAction;
import com.kingnod.core.extensions.struts2.annotation.ErrorMapping;
import com.kingnod.core.util.web.Struts2Utils;
import com.kingnod.etraining.exam.ExamConstant;
import com.kingnod.etraining.exam.entity.GeneratingPaperScope;
import com.kingnod.etraining.exam.service.GeneratingPaperScopeService;
import com.kingnod.etraining.exam.service.TestGroupService;
@org.springframework.stereotype.Controller
@Namespace("/exm")
@Results
({
@Result(name = EntityAction.RELOAD, type = "redirectAction", params = { "actionName", "generating-paper-scope", "namespace", "/exm"}),
@Result(name = "rule", type = "redirectAction", params = { "actionName", "generating-paper-rule", "namespace", "/exm", "examPaperId", "${examPaperId}", "testGroupId", "${testGroupId}", "questionType", "${questionType}"})
})
@com.kingnod.core.annotation.Generated("2012-05-09 10:19")
public class GeneratingPaperScopeAction extends FilterableEntityAction<GeneratingPaperScope, Long> {
/**
* 自动组卷范围action
*/
private static final long serialVersionUID=-2007689384292309632L;
private Long examPaperId; // 试卷ID
private Long testGroupId; // 测试区ID
private String questionType; // 试题类型
// @Override
// public String save() throws Exception {
// super.save();
// return "rule";
// }
@Override
@ErrorMapping(result=INPUT)
public String save() {
// 查询该试卷是否已发布 如果是发布状态 则不可以再组卷
testGroupService.getPaper(examPaperId);
try {
super.save();
} catch (Exception e) {
e.printStackTrace();
ServletActionContext.getValueStack(Struts2Utils.getRequest()).set(ExamConstant.ACTION_JSONROOT, -1);
return ExamConstant.ACTION_JSONRESULT;
}
ServletActionContext.getValueStack(Struts2Utils.getRequest()).set(ExamConstant.ACTION_JSONROOT, 1);
return ExamConstant.ACTION_JSONRESULT;
}
@Override
@ErrorMapping(result="rule")
public String delete() throws Exception {
// 查询该试卷是否已发布 如果是发布状态 则不可以再组卷
testGroupService.getPaper(examPaperId);
super.delete();
return "rule";
}
@Override
@ErrorMapping(result=INPUT)
public String input() throws Exception {
// 查询该试卷是否已发布 如果是发布状态 则不可以再组卷
testGroupService.getPaper(examPaperId);
Long[] ids = this.getIdValues();
if(null != ids && 0 != ids.length) {
entity = generatingPaperScopeService.getGeneratingPaperScope(ids[0]);
}
return INPUT;
}
@Autowired
@com.kingnod.core.annotation.Generated("2012-05-09 10:19")
private GeneratingPaperScopeService generatingPaperScopeService;
@Autowired
private TestGroupService testGroupService;
@com.kingnod.core.annotation.Generated("2012-05-09 10:19")
public String filterDefines() {
return "exm.generatingPaperScopeFilterItems";
}
@com.kingnod.core.annotation.Generated("2012-05-09 10:19")
protected Object getEntityService() {
return this.generatingPaperScopeService;
}
public Long getExamPaperId() {
return examPaperId;
}
public void setExamPaperId(Long examPaperId) {
this.examPaperId = examPaperId;
}
public Long getTestGroupId() {
return testGroupId;
}
public void setTestGroupId(Long testGroupId) {
this.testGroupId = testGroupId;
}
protected Long[] getIdValues() {
String[] idsParam = request.getParameterValues("scopeIds");
if(null != idsParam) {
Long[] ids = new Long[idsParam.length];
for (int i = 0; i < idsParam.length; i++) {
ids[i] = Long.parseLong(idsParam[i]);
}
return ids;
}
return null;
}
public String getQuestionType() {
return questionType;
}
public void setQuestionType(String questionType) {
this.questionType = questionType;
}
}
| true
|
186ae0efa6cae83152632fb0a2d264d5e90e7b5a
|
Java
|
nkoder/CraftingCodeWorkshop
|
/exercise3/src/test/java/org/craftedsw/tripservicekata/user/UserBuilder.java
|
UTF-8
| 786
| 2.78125
| 3
|
[] |
no_license
|
package org.craftedsw.tripservicekata.user;
import org.craftedsw.tripservicekata.trip.Trip;
import java.util.List;
import static org.assertj.core.util.Lists.newArrayList;
public class UserBuilder {
private List<User> friends;
private List<Trip> trips;
public static UserBuilder user() {
return new UserBuilder();
}
public UserBuilder whoIsFriendOf(User... anotherUsers) {
this.friends = newArrayList(anotherUsers);
return this;
}
public User andWhosTripsAre(Trip... trips) {
this.trips = newArrayList(trips);
return createUser();
}
private User createUser() {
User user = new User();
friends.forEach(user::addFriend);
trips.forEach(user::addTrip);
return user;
}
}
| true
|
349b80cb5644ed9a0409a6d0302544097e896580
|
Java
|
626sy/Java_SSM_Learn
|
/Dtest/src/main/java/org/example/po/Dept.java
|
UTF-8
| 815
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.example.po;
import java.util.List;
/**
* @author shihaobo
* @date 2020/9/11 9:52
*/
public class Dept {
private int deptid;
private String dname;
private List<Emp> les;
public int getDeptid() {
return deptid;
}
public void setDeptid(int deptid) {
this.deptid = deptid;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public List<Emp> getLes() {
return les;
}
public void setLes(List<Emp> les) {
this.les = les;
}
@Override
public String toString() {
return "Dept{" +
"deptid=" + deptid +
", dname='" + dname + '\'' +
", les=" + les +
'}';
}
}
| true
|
51c1787c9def6007173c24836e4bdb3652dc5fa1
|
Java
|
youchangxu1205/CommonSystem
|
/src/main/java/top/youchangxu/model/system/StaffingEnterprise.java
|
UTF-8
| 1,235
| 2.03125
| 2
|
[] |
no_license
|
package top.youchangxu.model.system;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
/**
* Created by dtkj_android on 2017/5/26.
* 企业表
*/
@TableName("staffing_enterprise")
public class StaffingEnterprise {
@TableId
private Long enterpriseId;
private String enterpriseName;
private String enterpriseCode;
public Long getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(Long enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getEnterpriseName() {
return enterpriseName;
}
public void setEnterpriseName(String enterpriseName) {
this.enterpriseName = enterpriseName;
}
public String getEnterpriseCode() {
return enterpriseCode;
}
public void setEnterpriseCode(String enterpriseCode) {
this.enterpriseCode = enterpriseCode;
}
@Override
public String toString() {
return "StaffingEnterprise{" +
"enterpriseId=" + enterpriseId +
", enterpriseName='" + enterpriseName + '\'' +
", enterpriseCode='" + enterpriseCode + '\'' +
'}';
}
}
| true
|
db3a40cbc3d6ef812bbaf00bb0f8e350e85ef549
|
Java
|
amits7204/NewsApp
|
/app/src/main/java/com/example/amit/newsapp/viewpageradapter/NewsViewPagerAdapter.java
|
UTF-8
| 1,172
| 2.40625
| 2
|
[] |
no_license
|
package com.example.amit.newsapp.viewpageradapter;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.amit.newsapp.fragment.IndianExpressFragment;
import com.example.amit.newsapp.fragment.PIBNewsFragment;
import com.example.amit.newsapp.fragment.TheHinduFragment;
public class NewsViewPagerAdapter extends FragmentPagerAdapter {
private Fragment[] mFragmentPageAdapter;
public NewsViewPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentPageAdapter = new Fragment[]{new TheHinduFragment(),
new IndianExpressFragment(), new PIBNewsFragment()};
}
@Override
public Fragment getItem(int aPosition) {
return mFragmentPageAdapter[aPosition];
}
@Override
public int getCount() {
return mFragmentPageAdapter.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int aPosition) {
String[] lPageTittle = new String[]{"The Hindu", "Indian Express", "Pib News"};
return lPageTittle[aPosition];
}
}
| true
|
beacafe2f9d41978d8b6efe6e2c6dfddd893e2b1
|
Java
|
xinjingjie/SimpleBottomNav
|
/app/src/main/java/com/example/simplebottomnav/bean/TotalPics.java
|
UTF-8
| 1,656
| 2.59375
| 3
|
[] |
no_license
|
package com.example.simplebottomnav.bean;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class TotalPics implements Parcelable {
private int total;
private int totalHits;
private List<Picture> hits;
public TotalPics() {
}
public TotalPics(int total, int totalHits, List<Picture> hits) {
this.total = total;
this.totalHits = totalHits;
this.hits = hits;
}
protected TotalPics(Parcel in) {
total = in.readInt();
totalHits = in.readInt();
hits = in.createTypedArrayList(Picture.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(total);
dest.writeInt(totalHits);
dest.writeTypedList(hits);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<TotalPics> CREATOR = new Creator<TotalPics>() {
@Override
public TotalPics createFromParcel(Parcel in) {
return new TotalPics(in);
}
@Override
public TotalPics[] newArray(int size) {
return new TotalPics[size];
}
};
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotalHits() {
return totalHits;
}
public void setTotalHits(int totalHits) {
this.totalHits = totalHits;
}
public List<Picture> getHits() {
return hits;
}
public void setHits(ArrayList<Picture> hits) {
this.hits = hits;
}
}
| true
|
a4deba548af62ab5be77b25e3ad71a7b1b39d26c
|
Java
|
xujiansen/grasp
|
/src/main/java/com/rooten/help/filehttp/FileDownloadMgr.java
|
UTF-8
| 10,388
| 2.46875
| 2
|
[] |
no_license
|
package com.rooten.help.filehttp;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import com.rooten.AppHandler;
import com.rooten.interf.IHandler;
import com.rooten.util.Util;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import lib.grasp.util.FileUtil;
import lib.grasp.util.L;
import lib.grasp.util.PathUtil;
public class FileDownloadMgr implements IHandler {
/** 锁 - 实现[添加]与[读取]任务都是同步互斥的 */
private Lock mLock = new ReentrantLock();
/** 是否准备停止各传输线程 */
protected boolean mQuit = false;
/** 最大下载线程数(包含各类传输任务) */
private int DOWNLOAD_MAX = 2;
/** <传输任务种类ID, 每个任务种类(多个线程)的说明> */
private Map<String, String> mTypeDescription = new HashMap<>();
/** <传输任务种类ID, 每个任务种类(多个线程)的线程数> */
private Map<String, Integer> mTypeThreadNum = new HashMap<>();
/** <传输任务种类ID, 每个任务种类(多个线程)的信号量> */
private Map<String, Semaphore> mTypeSemaphore = new HashMap<>();
/** <传输任务种类ID, 线程队列> */
private Map<String, Queue<HttpDownloadRequest>> mTypeThreadQueue = new HashMap<>();
/** 下载成功 */
public static final long DOWNLOADSTATUS_SUCCESS = -1;
/** 下载失败 */
public static final long DOWNLOADSTATUS_FALIURE = -2;
public AppHandler mHandler = new AppHandler(this);
/** 下载线程数量 */
public FileDownloadMgr(int threadNum) {
DOWNLOAD_MAX = threadNum;
}
/** 开始运行传输线程(没有传入任务) */
public void startDownload() {
mQuit = false;
for (Map.Entry<String, Integer> entry : mTypeThreadNum.entrySet()) {
String categoryID = entry.getKey();
int threadNum = entry.getValue();
String description = getDescription(categoryID);
for (int i = 0; i < threadNum; i++) {
String threadName = description + "线程" + (i + 1);
Thread t = new Thread(new DownRun(categoryID), threadName);
t.start();
}
}
}
/** 停止传输线程 (这里允许各传输线程将当前的任务执行完成, 但不接收新任务) */
public void stopDownload() {
mQuit = true; // 置退出标签
for (Map.Entry<String, Integer> entry : mTypeThreadNum.entrySet()) {
String categoryID = entry.getKey();
int threadNum = entry.getValue();
// 这里允许各传输线程将当前的任务执行完成, 但不接收新任务
Semaphore semaphore = getSemaphore(categoryID);
if (semaphore == null) continue;
semaphore.release(threadNum);
}
mTypeDescription.clear();
mTypeThreadNum.clear();
mTypeSemaphore.clear();
mTypeThreadQueue.clear();
}
/** 注册下载类型,返回注册成功的id,否则返回空字符串 */
public String registerCategory(String description, int threadNum) {
if (threadNum <= 0 || threadNum > DOWNLOAD_MAX) return "";
int hasRegisterThreadNum = 0;
for (Map.Entry<String, Integer> entry : mTypeThreadNum.entrySet()) {
hasRegisterThreadNum += entry.getValue();
}
if (hasRegisterThreadNum >= DOWNLOAD_MAX) return "";
int left = DOWNLOAD_MAX - hasRegisterThreadNum;
if (threadNum > left) return "";
String categoryID = UUID.randomUUID().toString();
mTypeDescription.put(categoryID, description);
mTypeThreadNum.put(categoryID, threadNum);
init();
return categoryID;
}
/** 解注册下载类型,返回解注册执行结果 */
public boolean unRegisterCategory(String categoryID) {
if (TextUtils.isEmpty(categoryID)) return false;
if (!mTypeThreadNum.containsKey(categoryID)) return false;
mTypeThreadNum.remove(categoryID);
mTypeDescription.remove(categoryID);
mTypeSemaphore.remove(categoryID);
mTypeThreadQueue.remove(categoryID);
init();
return true;
}
/** 传入一个[传输任务种类ID] + [传输任务], 开始传输 */
public void addDownWork(String categoryID, HttpDownloadRequest req) {
Semaphore semaphore = getSemaphore(categoryID);
if (semaphore == null) return;
Queue<HttpDownloadRequest> queue = mTypeThreadQueue.get(categoryID);
if(queue == null) return;
mLock.lock();
queue.add(req);
semaphore.release();
mLock.unlock();
}
/** 初始化新增任务类型的[信号量]与[线程队列] */
private void init() {
for (Map.Entry<String, Integer> entry : mTypeThreadNum.entrySet()) {
String categoryID = entry.getKey();
if (mTypeSemaphore.containsKey(categoryID)) continue;
if (mTypeThreadQueue.containsKey(categoryID)) continue;
Semaphore newSemaphore = new Semaphore(0);
mTypeSemaphore.put(categoryID, newSemaphore);
Queue<HttpDownloadRequest> queue = new LinkedList<>();
mTypeThreadQueue.put(categoryID, queue);
}
}
private Semaphore getSemaphore(String categoryID) {
return mTypeSemaphore.get(categoryID);
}
private String getDescription(String categoryID) {
return mTypeDescription.get(categoryID);
}
/** 单传输线程的run方法 */
private class DownRun implements Runnable {
String mCategoryID;
DownRun(String categoryID) {
mCategoryID = categoryID;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
L.log("下载线程:" + threadName + "开始运行");
while (!mQuit) {
if (TextUtils.isEmpty(mCategoryID)) break;
Semaphore semaphore = getSemaphore(mCategoryID);
if (semaphore == null) break;
try {
semaphore.acquire();
if (mQuit) break;
HttpDownloadRequest req = getReq(mCategoryID);
if (req == null) continue;
doDownload(mCategoryID, req); // 开始下载
} catch (Exception e) {
L.log("下载线程异常:" + e.toString());
}
}
L.log("下载线程:" + threadName + "停止运行");
}
}
/** 按照传入参数获取指定的下载请求对象 */
private HttpDownloadRequest getReq(String categoryID) {
Queue<HttpDownloadRequest> queue = mTypeThreadQueue.get(categoryID);
if(queue == null) return null;
mLock.lock();
HttpDownloadRequest req = queue.poll();
mLock.unlock();
return req;
}
/** 开始一个传输任务, 回调传输过程中的各种数据 */
protected void doDownload(String categoryID, HttpDownloadRequest req) {
DownloadTask task = new DownloadTask(categoryID, req);
if (task.doRealDownload()) {
L.log("传输完成");
sendMsg(req, categoryID, req.requestUrl, DOWNLOADSTATUS_SUCCESS, 1); // 传输成功
} else {
L.log("传输失败");
sendMsg(req, categoryID, req.requestUrl, DOWNLOADSTATUS_FALIURE, 1); // 传输成功
}
}
/** 传输任务封装类, 传输过程中会不断回调进度 */
private class DownloadTask implements HttpUtil.onHttpProgressListener {
private String mCategoryID;
private HttpDownloadRequest mReq;
/** 下载任务 */
DownloadTask(String categoryID, HttpDownloadRequest req) {
mCategoryID = categoryID;
mReq = req;
}
/** 真正开始下载(会阻塞线程, 等到传输结束时返回传输结果) */
private boolean doRealDownload() {
String okFilePath = PathUtil.getDownOkPath() + mReq.saveFile.getName();
L.log(okFilePath + "文件已经存在, 且传输完成");
if(FileUtil.isFileExists(new File(okFilePath))) return true;
return HttpUtil.downloadFile(mReq, this);
}
/** 是否取消 */
@Override
public boolean isQuit() {
return mQuit;
}
/** 进度回调 */
@Override
public void onProgress(String requestID, String url, long curSize, long allLen) {
boolean hasCategory = mTypeThreadNum.containsKey(mCategoryID);
if (mReq.mProgressListener == null || !hasCategory) return;
sendMsg(mReq, requestID, url, curSize, allLen);
}
}
private void sendMsg(HttpDownloadRequest mReq, String requestID, String url, long curSize, long allLen){
Bundle bundle = new Bundle();
bundle.putString("uuid", requestID);
bundle.putString("url", url);
bundle.putLong("curSize", curSize);
bundle.putLong("allLen", allLen);
Message msg = new Message();
msg.setData(bundle);
msg.obj = mReq;
mHandler.sendMessage(msg);
}
@Override
public boolean handleMessage(Message msg) {
Object o = msg.obj;
if(!(o instanceof HttpDownloadRequest)) return false;
HttpDownloadRequest request = (HttpDownloadRequest)o;
Bundle bundle = msg.getData();
String uuid = Util.getString(bundle, "uuid");
String url = Util.getString(bundle, "url");
long curSize = Util.getLong(bundle, "curSize");
long allLen = Util.getLong(bundle, "allLen");
request.mProgressListener.onProgress(uuid, url, curSize, allLen);
if(curSize == DOWNLOADSTATUS_SUCCESS){ // 下载成功, 将temp文件转移到OK文件夹
String oldFile = request.saveFile.getAbsolutePath();
String newFile = PathUtil.getDownOkPath() + request.saveFile.getName();
FileUtil.renameFile(oldFile, newFile);
}
return true;
}
}
| true
|
d606401e4fbdda8e78e5a29e53138f24a741723a
|
Java
|
jcpg1982/seleccionMultiple
|
/app/src/main/java/pe/com/dms/movilasist/ui/fragment/filtersFragments/filtroAproSolic/FiltroAprobSolicFragmentPresenter.java
|
UTF-8
| 5,702
| 1.914063
| 2
|
[] |
no_license
|
package pe.com.dms.movilasist.ui.fragment.filtersFragments.filtroAproSolic;
import android.app.DatePickerDialog;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;
import androidx.fragment.app.FragmentManager;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Named;
import io.reactivex.Scheduler;
import pe.com.dms.movilasist.bd.PreferenceManager;
import pe.com.dms.movilasist.bd.entity.StatusSolicitud;
import pe.com.dms.movilasist.iterator.FiltroListAprobSolicPermFragment.local.IFiltroListAprobSolicPermFragmentIteratorLocal;
import pe.com.dms.movilasist.iterator.FiltroListAprobSolicPermFragment.remote.IFiltroListAprobSolicPermFragmentIteratorRemote;
import pe.com.dms.movilasist.iterator.loginFragment.local.ILoginFragmentInteractorLocal;
import pe.com.dms.movilasist.model.filterModel.ResultListApobSolic;
import pe.com.dms.movilasist.ui.activities.base.BasePresenter;
import pe.com.dms.movilasist.ui.dialog.DatePickerFragment;
import pe.com.dms.movilasist.util.DateUtils;
public class FiltroAprobSolicFragmentPresenter extends BasePresenter<IFiltroAprobSolicFragmentContract.View>
implements IFiltroAprobSolicFragmentContract.Presenter {
String TAG = FiltroAprobSolicFragmentPresenter.class.getSimpleName();
@Inject
IFiltroListAprobSolicPermFragmentIteratorLocal iteratorLocal;
@Inject
IFiltroListAprobSolicPermFragmentIteratorRemote iteratorRemote;
@Inject
@Named("executor_thread")
Scheduler ExecutorThread;
@Inject
@Named("ui_thread")
Scheduler UiThread;
@Inject
PreferenceManager preferenceManager;
private String mDateIni, mDateFin, mcodPers, mNameLastName;
private int mStatusSolicitud;
private Calendar calendar;
private List<StatusSolicitud> mListStatusSolicitud;
@Inject
public FiltroAprobSolicFragmentPresenter() {
calendar = Calendar.getInstance(Locale.getDefault());
if (mListStatusSolicitud == null)
mListStatusSolicitud = new ArrayList<>();
}
@Override
public void showDatePickerDialog(FragmentManager fragment, final EditText editText, Long dateTime) {
DatePickerFragment newFragment = DatePickerFragment.newInstance(
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Log.e(TAG, "year: " + year + ", month: " + month + ", dayOfMonth: " + dayOfMonth);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String date = DateUtils.dateToStringFormat(calendar.getTime(),
DateUtils.PATTERN_DATE_LECTURA);
Log.e(TAG, "date: " + date);
editText.setText(date);
}
}, dateTime);
newFragment.show(fragment, DatePickerFragment.TAG);
}
@Override
public void setDateIni(String dateIni) {
mDateIni = dateIni;
}
@Override
public void setDateFin(String dateFin) {
mDateFin = dateFin;
}
@Override
public void setCodPersonal(String codPers) {
mcodPers = codPers;
}
@Override
public void setNameLastName(String nameLastName) {
mNameLastName = nameLastName;
}
@Override
public void setStatusSolicitud(int statusSolicitud) {
mStatusSolicitud = statusSolicitud;
}
@Override
public ResultListApobSolic filtroListAprobSolic() {
ResultListApobSolic listApobSolic = new ResultListApobSolic();
listApobSolic.setCodPersonal(mcodPers);
listApobSolic.setNameLastName(mNameLastName);
listApobSolic.setDateIni(mDateIni);
listApobSolic.setDateFin(mDateFin);
listApobSolic.setStatus(mStatusSolicitud);
Log.e(TAG, "saveDataInModel: " + listApobSolic);
return listApobSolic;
}
@Override
public void getListStatusSolicitud() {
Log.e(TAG, "obtainMotivoOffLine");
getCompositeDisposable().add(iteratorLocal.getListStatusSolicitudOffLine()
.subscribeOn(ExecutorThread)
.observeOn(UiThread)
.subscribe(statusSolicitudList -> {
Log.e(TAG, "obtainMotivoOffLine subscribe : " + statusSolicitudList);
if (statusSolicitudList != null && statusSolicitudList.size() > 0) {
mListStatusSolicitud.clear();
mListStatusSolicitud.add(new StatusSolicitud(-1, "Seleccione"));
for (StatusSolicitud item : statusSolicitudList) {
mListStatusSolicitud.add(item);
}
getView().llenarSpinnerSolicitud(mListStatusSolicitud);
}
}, error -> {
Log.e(TAG, "obtainMotivoOffLine error : " + error);
Log.e(TAG, "obtainMotivoOffLine error : " + error.toString());
Log.e(TAG, "obtainMotivoOffLine error : " + error.getMessage());
Log.e(TAG, "obtainMotivoOffLine error : " + error.getLocalizedMessage());
getView().showErrorMessage("No hay conexion con la base de datos.", error.getMessage());
}));
}
@Override
public List<StatusSolicitud> listStatusSolicitud() {
return mListStatusSolicitud;
}
}
| true
|